<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
header('Content-Type: application/json; charset=utf-8');

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) { jsonResponse(false, 'Unauthorized', [], 401); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { jsonResponse(false, 'Invalid method.'); }

$csrf = new CSRF();
if (!$csrf->verify($_POST['csrf_token'] ?? '')) { jsonResponse(false, 'Invalid CSRF token.'); }

$db = Database::getInstance();
$action = $_POST['action'] ?? '';
$userId = $_SESSION['user_id'];

if ($action === 'update_profile') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');

    if (empty($name) || empty($email)) {
        jsonResponse(false, 'Name and email are required.');
    }

    $existingEmail = $db->query("SELECT id FROM users WHERE email = ? AND id != ?", [$email, $userId])->fetch();
    if ($existingEmail) {
        jsonResponse(false, 'Email address is already in use.');
    }

    $data = [
        'name' => $name,
        'email' => $email,
        'phone' => $phone,
        'updated_at' => date('Y-m-d H:i:s'),
    ];

    $upload = new Upload();
    if (!empty($_FILES['avatar']['name'])) {
        $result = $upload->uploadFile($_FILES['avatar'], 'avatars');
        if ($result['success']) {
            $data['avatar'] = $result['path'];
        } else {
            jsonResponse(false, 'Avatar upload failed: ' . implode(', ', $result['errors']));
        }
    }

    $db->update('users', $data, 'id = ?', [$userId]);
    $_SESSION['user_name'] = $name;
    $_SESSION['user_email'] = $email;

    jsonResponse(true, 'Profile updated successfully.');
}

if ($action === 'change_password') {
    $currentPassword = $_POST['current_password'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';

    if (empty($currentPassword) || empty($newPassword)) {
        jsonResponse(false, 'All password fields are required.');
    }

    if ($newPassword !== $confirmPassword) {
        jsonResponse(false, 'New passwords do not match.');
    }

    if (strlen($newPassword) < 6) {
        jsonResponse(false, 'New password must be at least 6 characters.');
    }

    $user = $db->query("SELECT password FROM users WHERE id = ?", [$userId])->fetch();
    if (!$user || !password_verify($currentPassword, $user['password'])) {
        jsonResponse(false, 'Current password is incorrect.');
    }

    $db->update('users', [
        'password' => password_hash($newPassword, PASSWORD_DEFAULT),
        'updated_at' => date('Y-m-d H:i:s'),
    ], 'id = ?', [$userId]);

    jsonResponse(true, 'Password changed successfully.');
}

jsonResponse(false, 'Invalid action.');
