<?php
// ─── API STATS ────────────────────────────────────────────────────────────────
// Routes :
//   POST   /api/stats.php?action=session      → sauvegarde fin de partie
//   GET    /api/stats.php?action=leaderboard  → top 10
//   DELETE /api/stats.php?action=mistakes     → vider ses fautes

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, 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'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];
$body   = json_decode(file_get_contents('php://input'), true) ?? [];

// ─── POST session ─────────────────────────────────────────────────────────────
if ($action === 'session' && $method === 'POST') {
    $userId = requireAuth();

    $category   = $body['category']   ?? '';
    $score      = (int)($body['score']      ?? 0);
    $good       = (int)($body['good']       ?? 0);
    $bad        = (int)($body['bad']        ?? 0);
    $bestStreak = (int)($body['bestStreak'] ?? 0);
    $mistakes   = $body['mistakes'] ?? [];

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

    // Met à jour best_global et played
    $pdo->prepare("
        UPDATE users
        SET played = played + 1,
            best_global = GREATEST(best_global, ?)
        WHERE id = ?
    ")->execute([$score, $userId]);

    // Upsert cat_stats
    $pdo->prepare("
        INSERT INTO cat_stats (user_id, category, good, bad, played_cat, best_score)
        VALUES (?, ?, ?, ?, 1, ?)
        ON DUPLICATE KEY UPDATE
            good       = good + VALUES(good),
            bad        = bad  + VALUES(bad),
            played_cat = played_cat + 1,
            best_score = GREATEST(best_score, VALUES(best_score))
    ")->execute([$userId, $category, $good, $bad, $score]);

    // Ajoute les fautes (max 200)
    if (!empty($mistakes)) {
        $ins = $pdo->prepare("
            INSERT INTO mistakes (user_id, category, question, user_answer, correct, explanation)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        foreach ($mistakes as $m) {
            $ins->execute([
                $userId,
                $m['category']    ?? $category,
                $m['question']    ?? '',
                $m['user']        ?? $m['userAnswer'] ?? '',
                $m['correct']     ?? '',
                $m['explanation'] ?? ''
            ]);
        }
        // Garde seulement les 200 dernières fautes
        $pdo->prepare("
            DELETE FROM mistakes
            WHERE user_id = ?
              AND id NOT IN (
                  SELECT id FROM (
                      SELECT id FROM mistakes WHERE user_id = ? ORDER BY date DESC LIMIT 200
                  ) t
              )
        ")->execute([$userId, $userId]);
    }

    // Retourne les stats à jour
    $row = $pdo->prepare("SELECT best_global, played FROM users WHERE id = ?");
    $row->execute([$userId]);
    $u = $row->fetch();

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

    echo json_encode([
        'message'    => 'Session sauvegardée',
        'bestGlobal' => $u['best_global'],
        'played'     => $u['played'],
        'catStats'   => $cats->fetchAll()
    ]);
    exit;
}

// ─── GET leaderboard ─────────────────────────────────────────────────────────
if ($action === 'leaderboard' && $method === 'GET') {
    requireAuth();

    $stmt = $pdo->query("
        SELECT username, best_global AS bestGlobal, played
        FROM users
        ORDER BY best_global DESC
        LIMIT 10
    ");
    $top = $stmt->fetchAll();

    $board = array_map(function($u, $i) {
        return array_merge(['rank' => $i + 1], $u);
    }, $top, array_keys($top));

    echo json_encode(['leaderboard' => $board]);
    exit;
}

// ─── DELETE mistakes ─────────────────────────────────────────────────────────
if ($action === 'mistakes' && $method === 'DELETE') {
    $userId = requireAuth();
    $pdo->prepare("DELETE FROM mistakes WHERE user_id = ?")->execute([$userId]);
    echo json_encode(['message' => 'Fautes effacées']);
    exit;
}

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