<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
header('Content-Type: application/json');

try {
    require_once '../db.php';

    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Non autorisé.']);
        exit;
    }

    $userId = $_SESSION['user_id'];
    $method = $_SERVER['REQUEST_METHOD'];

    if ($method === 'POST') {
        $username = trim($_POST['username'] ?? '');
        
        // Récupération explicite des préférences (0 si décoché, 1 si coché)
        $darkMode = isset($_POST['dark_mode']) ? (int)$_POST['dark_mode'] : 0;
        $dyslexiaMode = isset($_POST['dyslexia_mode']) ? (int)$_POST['dyslexia_mode'] : 0;
        $themeColor = trim($_POST['theme_color'] ?? 'indigo');
        
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $avatarUrl = null;

        // Gestion de l'avatar avec limite de 5 Mo
        if (isset($_FILES['avatar_file']) && $_FILES['avatar_file']['error'] === UPLOAD_ERR_OK) {
            $maxSize = 5 * 1024 * 1024; // 5 Mo max
            if ($_FILES['avatar_file']['size'] > $maxSize) {
                echo json_encode(['success' => false, 'message' => 'L\'image est trop lourde (5 Mo maximum).']);
                exit;
            }

            $uploadDir = '../uploads/avatars/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $ext = pathinfo($_FILES['avatar_file']['name'], PATHINFO_EXTENSION);
            $filename = 'avatar_' . $userId . '_' . time() . '.' . $ext;
            $targetFile = $uploadDir . $filename;

            if (move_uploaded_file($_FILES['avatar_file']['tmp_name'], $targetFile)) {
                $avatarUrl = 'uploads/avatars/' . $filename;
            }
        }

        // Mise à jour de base (Pseudo & Préférences)
        if (!empty($username)) {
            $stmt = $pdo->prepare("UPDATE users SET username = :username, dark_mode = :dark, dyslexia_mode = :dyslexia, theme_color = :theme WHERE id = :id");
            $stmt->execute([
                'username' => $username,
                'dark' => $darkMode,
                'dyslexia' => $dyslexiaMode,
                'theme' => $themeColor,
                'id' => $userId
            ]);
        }

        // Changement de mot de passe sécurisé si demandé
        if (!empty($currentPassword) && !empty($newPassword)) {
            $stmtUser = $pdo->prepare("SELECT password_hash FROM users WHERE id = :id");
            $stmtUser->execute(['id' => $userId]);
            $userData = $stmtUser->fetch();

            if ($userData && password_verify($currentPassword, $userData['password_hash'])) {
                $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
                $stmtPass = $pdo->prepare("UPDATE users SET password_hash = :hash WHERE id = :id");
                $stmtPass->execute(['hash' => $newHash, 'id' => $userId]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Mot de passe actuel incorrect.']);
                exit;
            }
        }

        // Mise à jour avatar si présent
        if ($avatarUrl) {
            $stmt = $pdo->prepare("UPDATE users SET avatar_url = :avatar WHERE id = :id");
            $stmt->execute(['avatar' => $avatarUrl, 'id' => $userId]);
        }

        echo json_encode(['success' => true, 'message' => 'Paramètres enregistrés avec succès ! ✨']);
        exit;
    }

    if ($method === 'DELETE') {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
        $stmt->execute(['id' => $userId]);
        session_destroy();
        echo json_encode(['success' => true, 'message' => 'Compte supprimé.']);
        exit;
    }

} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>