<?php
ini_set("display_errors", 1); error_reporting(E_ALL);
// ─── API AUTH ─────────────────────────────────────────────────────────────────
// Routes :
//   POST /api/auth.php?action=register   → inscription
//   POST /api/auth.php?action=login      → connexion
//   GET  /api/auth.php?action=me         → profil (token requis)

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

require 'db.php';
require 'jwt_helper.php';

$action = $_GET['action'] ?? '';
$body   = json_decode(file_get_contents('php://input'), true) ?? [];

// ─── REGISTER ────────────────────────────────────────────────────────────────
if ($action === 'register' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($body['username'] ?? '');
    $email    = trim($body['email']    ?? '');
    $password =      $body['password'] ?? '';

    if (!$username || !$password) {
        http_response_code(400);
        echo json_encode(['message' => 'username et password requis']);
        exit;
    }

    // Validation longueur pseudo
    if (strlen($username) < 2 || strlen($username) > 30) {
        http_response_code(400);
        echo json_encode(['message' => 'Le pseudo doit faire entre 2 et 30 caractères']);
        exit;
    }

    // Vérif unicité pseudo
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->execute([$username]);
    if ($stmt->fetch()) {
        http_response_code(409);
        echo json_encode(['message' => 'Ce pseudo est déjà pris']);
        exit;
    }

    // Vérif unicité email (si fourni)
    if ($email) {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            http_response_code(409);
            echo json_encode(['message' => 'Cet email est déjà utilisé']);
            exit;
        }
    }

    $hash = password_hash($password, PASSWORD_DEFAULT);
    $emailVal = $email ?: null; // NULL au lieu de '' pour le UNIQUE
    $stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
    $stmt->execute([$username, $emailVal, $hash]);
    $userId = $pdo->lastInsertId();

    $token = generateJWT(['id' => $userId]);
    http_response_code(201);
    echo json_encode([
        'token' => $token,
        'user'  => [
            'id'         => $userId,
            'username'   => $username,
            'bestGlobal' => 0,
            'played'     => 0,
            'catStats'   => [],
            'mistakes'   => [],
            'dailyHistory' => []
        ]
    ]);
    exit;
}

// ─── LOGIN ────────────────────────────────────────────────────────────────────
if ($action === 'login' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($body['username'] ?? '');
    $password =      $body['password'] ?? '';

    if (!$username || !$password) {
        http_response_code(400);
        echo json_encode(['message' => 'username et password requis']);
        exit;
    }

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if (!$user || !password_verify($password, $user['password'])) {
        http_response_code(401);
        echo json_encode(['message' => 'Pseudo ou mot de passe incorrect']);
        exit;
    }


    $token = generateJWT(['id' => $user['id']]);

    // Récupère cat_stats
    $cats = $pdo->prepare("SELECT category, good, bad, played_cat AS played, best_score AS bestScore FROM cat_stats WHERE user_id = ?");
    $cats->execute([$user['id']]);

    // Récupère dernières 50 fautes
    $mist = $pdo->prepare("SELECT category, question, user_answer AS userAnswer, correct, explanation FROM mistakes WHERE user_id = ? ORDER BY date DESC LIMIT 50");
    $mist->execute([$user['id']]);

    // Récupère daily history
    $daily = $pdo->prepare("SELECT day, correct FROM daily_history WHERE user_id = ? ORDER BY date DESC LIMIT 30");
    $daily->execute([$user['id']]);

    echo json_encode([
        'token' => $token,
        'user'  => [
            'id'           => $user['id'],
            'username'     => $user['username'],
            'bestGlobal'   => $user['best_global'],
            'played'       => $user['played'],
            'catStats'     => $cats->fetchAll(),
            'mistakes'     => $mist->fetchAll(),
            'dailyHistory' => $daily->fetchAll()
        ]
    ]);
    exit;
}

// ─── ME (profil courant) ──────────────────────────────────────────────────────
if ($action === 'me' && $_SERVER['REQUEST_METHOD'] === 'GET') {
    $userId = requireAuth();

    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    if (!$user) { http_response_code(404); echo json_encode(['message' => 'Utilisateur introuvable']); exit; }

    $cats = $pdo->prepare("SELECT category, good, bad, played_cat AS played, best_score AS bestScore FROM cat_stats WHERE user_id = ?");
    $cats->execute([$userId]);

    $mist = $pdo->prepare("SELECT category, question, user_answer AS userAnswer, correct, explanation FROM mistakes WHERE user_id = ? ORDER BY date DESC LIMIT 50");
    $mist->execute([$userId]);

    $daily = $pdo->prepare("SELECT day, correct FROM daily_history WHERE user_id = ? ORDER BY date DESC LIMIT 30");
    $daily->execute([$userId]);

    echo json_encode([
        'user' => [
            'id'           => $user['id'],
            'username'     => $user['username'],
            'bestGlobal'   => $user['best_global'],
            'played'       => $user['played'],
            'catStats'     => $cats->fetchAll(),
            'mistakes'     => $mist->fetchAll(),
            'dailyHistory' => $daily->fetchAll(),
            'createdAt'    => $user['created_at'],
            'lastSeen'     => $user['last_seen']
        ]
    ]);
    exit;
}

http_response_code(404);
echo json_encode(['message' => 'Action inconnue']);
