<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Basic security: must be logged in
if (!isset($_SESSION['user']['username'])) {
    header('Location: ../login.php');
    exit;
}

if (!defined('LUNA_APP')) {
    define('LUNA_APP', true);
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/messages.php';

$currentLocale = $_SESSION['lang'] ?? 'vn';
$messages = load_messages($currentLocale);

function flash_message(string $type, string $message): void {
    $_SESSION['flash'][$type] = $message;
}

$msnv = $_SESSION['user']['username'];
$hoten = $_SESSION['user']['hoten'] ?? '';

// If Hoten is not in session, fetch it from DB
if (empty($hoten)) {
    try {
        $conn = db_connect();
        if ($conn) {
            $sql = "SELECT Hoten FROM DataWork WHERE Maso_NV = ?";
            $stmt = sqlsrv_query($conn, $sql, [$msnv]);
            if ($stmt && ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
                $hoten = $row['Hoten'];
            }
            db_disconnect($conn);
        }
    } catch (Throwable $e) {
        // Log error but proceed, filename might be incomplete
        error_log('Avatar Upload: DB error fetching name for ' . $msnv . ': ' . $e->getMessage());
    }
}

if (isset($_FILES['avatar_file']) && $_FILES['avatar_file']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['avatar_file'];
    $uploadDir = __DIR__ . '/../data/avatar/';

    // Create directory if it doesn't exist
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($file['type'], $allowedTypes)) {
        flash_message('error', $messages['profile_avatar_invalid_file'] ?? 'Invalid image format.');
        header('Location: ../index.php?profile');
        exit;
    }

$safeNameSource = trim($hoten) !== '' ? trim($hoten) : 'avatar';
    $newFileName = $msnv . '_' . $safeNameSource . '.jpg';
    $destination = $uploadDir . $newFileName;

    // Delete old avatars for this user (if any)
    $oldFiles = glob($uploadDir . $msnv . '_*.jpg');
    foreach ($oldFiles as $oldFile) {
        if (is_file($oldFile)) {
            unlink($oldFile);
        }
    }

    // Move the new file
    if (move_uploaded_file($file['tmp_name'], $destination)) {
        flash_message('success', $messages['profile_avatar_update_success'] ?? 'Avatar updated successfully.');
        header('Location: ../index.php?profile');
    } else {
        flash_message('error', $messages['profile_avatar_update_error'] ?? 'Unable to update avatar. Please try again.');
        header('Location: ../index.php?profile');
    }
} else {
    $error = 'No file uploaded or an error occurred.';
    if (isset($_FILES['avatar_file']['error'])) {
        switch ($_FILES['avatar_file']['error']) {
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                $error = 'File is too large.';
                break;
            case UPLOAD_ERR_NO_FILE:
                $error = 'No file was selected.';
                break;
            default:
                $error = 'An unknown error occurred during upload.';
        }
    }
    flash_message('error', $messages['profile_avatar_update_error'] ?? $error);
    header('Location: ../index.php?profile');
}
exit;

