<?php
// ─── API GROUPES ──────────────────────────────────────────────────────────────
// Routes :
//   POST   /api/groups.php?action=create            → créer un groupe
//   POST   /api/groups.php?action=join              → rejoindre via code
//   GET    /api/groups.php?action=list              → mes groupes
//   POST   /api/groups.php?action=leave             → quitter un groupe
//   POST   /api/groups.php?action=create_challenge  → lancer un défi catégorie
//   POST   /api/groups.php?action=submit_challenge  → soumettre résultats défi
//   GET    /api/groups.php?action=get_challenge     → récupérer défi + résultats

header('Content-Type: application/json; charset=utf-8');
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) ?? [];

// ─── Génère un code unique de 6 caractères ────────────────────────────────────
function generateCode($pdo) {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    do {
        $code = '';
        for ($i = 0; $i < 6; $i++) {
            $code .= $chars[random_int(0, strlen($chars) - 1)];
        }
        $stmt = $pdo->prepare("SELECT id FROM `groups` WHERE code = ?");
        $stmt->execute([$code]);
    } while ($stmt->fetch());
    return $code;
}

// ─── Charge les infos d'un groupe avec ses membres ───────────────────────────
function loadGroup($pdo, $groupId, $userId) {
    $stmt = $pdo->prepare("SELECT g.*, u.username AS creator_name FROM `groups` g JOIN users u ON u.id = g.creator_id WHERE g.id = ?");
    $stmt->execute([$groupId]);
    $group = $stmt->fetch();
    if (!$group) return null;

    // Membres
    $stmt = $pdo->prepare("SELECT u.id, u.username FROM group_members gm JOIN users u ON u.id = gm.user_id WHERE gm.group_id = ? ORDER BY gm.joined_at ASC");
    $stmt->execute([$groupId]);
    $group['members'] = $stmt->fetchAll();

    // Défis
    $stmt = $pdo->prepare("SELECT gc.id, gc.category, gc.created_at, u.username AS created_by_name,
        (SELECT COUNT(*) FROM challenge_results cr WHERE cr.challenge_id = gc.id) AS results_count,
        (SELECT COUNT(*) FROM group_members gm2 WHERE gm2.group_id = gc.group_id) AS member_count,
        (SELECT score FROM challenge_results WHERE challenge_id = gc.id AND user_id = ?) AS my_score,
        (SELECT finished_at FROM challenge_results WHERE challenge_id = gc.id AND user_id = ?) AS my_finished_at
        FROM group_challenges gc JOIN users u ON u.id = gc.created_by
        WHERE gc.group_id = ? ORDER BY gc.created_at DESC");
    $stmt->execute([$userId, $userId, $groupId]);
    $group['challenges'] = $stmt->fetchAll();

    // Question du jour — statut pour cet utilisateur
    $ref = new DateTime('2025-01-01');
    $now = new DateTime();
    $day = (int)$now->diff($ref)->days;
    $stmt = $pdo->prepare("SELECT answer, correct FROM group_daily_answers WHERE group_id = ? AND user_id = ? AND day = ?");
    $stmt->execute([$groupId, $userId, $day]);
    $group['my_daily'] = $stmt->fetch() ?: null;
    $group['today_day'] = $day;

    // Nombre de réponses aujourd'hui dans ce groupe
    $stmt = $pdo->prepare("SELECT COUNT(*) AS cnt FROM group_daily_answers WHERE group_id = ? AND day = ?");
    $stmt->execute([$groupId, $day]);
    $group['daily_answered_count'] = (int)$stmt->fetch()['cnt'];

    return $group;
}

// ─── CREATE ───────────────────────────────────────────────────────────────────
if ($action === 'create' && $method === 'POST') {
    $userId = requireAuth();
    $name   = trim($body['name'] ?? '');

    if (!$name || strlen($name) < 2 || strlen($name) > 50) {
        http_response_code(400);
        echo json_encode(['message' => 'Nom de groupe invalide (2-50 caractères)']);
        exit;
    }

    $code = generateCode($pdo);

    $pdo->prepare("INSERT INTO `groups` (name, code, creator_id) VALUES (?, ?, ?)")
        ->execute([$name, $code, $userId]);
    $groupId = (int)$pdo->lastInsertId();

    // Le créateur est automatiquement membre
    $pdo->prepare("INSERT INTO group_members (group_id, user_id) VALUES (?, ?)")
        ->execute([$groupId, $userId]);

    $group = loadGroup($pdo, $groupId, $userId);
    http_response_code(201);
    echo json_encode(['message' => 'Groupe créé', 'group' => $group]);
    exit;
}

// ─── JOIN ─────────────────────────────────────────────────────────────────────
if ($action === 'join' && $method === 'POST') {
    $userId = requireAuth();
    $code   = strtoupper(trim($body['code'] ?? ''));

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

    $stmt = $pdo->prepare("SELECT id FROM `groups` WHERE code = ?");
    $stmt->execute([$code]);
    $group = $stmt->fetch();

    if (!$group) {
        http_response_code(404);
        echo json_encode(['message' => 'Code invalide — groupe introuvable']);
        exit;
    }

    // Déjà membre ?
    $stmt = $pdo->prepare("SELECT 1 FROM group_members WHERE group_id = ? AND user_id = ?");
    $stmt->execute([$group['id'], $userId]);
    if ($stmt->fetch()) {
        http_response_code(409);
        echo json_encode(['message' => 'Tu es déjà membre de ce groupe']);
        exit;
    }

    $pdo->prepare("INSERT INTO group_members (group_id, user_id) VALUES (?, ?)")
        ->execute([$group['id'], $userId]);

    $fullGroup = loadGroup($pdo, $group['id'], $userId);
    echo json_encode(['message' => 'Groupe rejoint !', 'group' => $fullGroup]);
    exit;
}

// ─── LIST ─────────────────────────────────────────────────────────────────────
if ($action === 'list' && $method === 'GET') {
    $userId = requireAuth();

    $stmt = $pdo->prepare("SELECT g.id FROM `groups` g JOIN group_members gm ON gm.group_id = g.id WHERE gm.user_id = ? ORDER BY g.created_at DESC");
    $stmt->execute([$userId]);
    $ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

    $groups = [];
    foreach ($ids as $id) {
        $g = loadGroup($pdo, $id, $userId);
        if ($g) $groups[] = $g;
    }

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

// ─── LEAVE ────────────────────────────────────────────────────────────────────
if ($action === 'leave' && $method === 'POST') {
    $userId  = requireAuth();
    $groupId = (int)($body['group_id'] ?? 0);

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

    // Vérif membre
    $stmt = $pdo->prepare("SELECT 1 FROM group_members WHERE group_id = ? AND user_id = ?");
    $stmt->execute([$groupId, $userId]);
    if (!$stmt->fetch()) {
        http_response_code(403);
        echo json_encode(['message' => 'Tu n\'es pas membre de ce groupe']);
        exit;
    }

    $pdo->prepare("DELETE FROM group_members WHERE group_id = ? AND user_id = ?")
        ->execute([$groupId, $userId]);

    // Si plus aucun membre, on supprime le groupe
    $stmt = $pdo->prepare("SELECT COUNT(*) AS cnt FROM group_members WHERE group_id = ?");
    $stmt->execute([$groupId]);
    if ((int)$stmt->fetch()['cnt'] === 0) {
        $pdo->prepare("DELETE FROM `groups` WHERE id = ?")->execute([$groupId]);
    }

    echo json_encode(['message' => 'Tu as quitté le groupe']);
    exit;
}

// ─── CREATE CHALLENGE ─────────────────────────────────────────────────────────
if ($action === 'create_challenge' && $method === 'POST') {
    $userId   = requireAuth();
    $groupId  = (int)($body['group_id']  ?? 0);
    $category = trim($body['category']   ?? '');
    $questions = $body['questions']      ?? []; // Les 15 questions envoyées depuis le front

    if (!$groupId || !$category || empty($questions)) {
        http_response_code(400);
        echo json_encode(['message' => 'group_id, category et questions requis']);
        exit;
    }

    // Vérif membre
    $stmt = $pdo->prepare("SELECT 1 FROM group_members WHERE group_id = ? AND user_id = ?");
    $stmt->execute([$groupId, $userId]);
    if (!$stmt->fetch()) {
        http_response_code(403);
        echo json_encode(['message' => 'Tu n\'es pas membre de ce groupe']);
        exit;
    }

    // Défi déjà existant pour cette catégorie dans ce groupe ?
    $stmt = $pdo->prepare("SELECT id FROM group_challenges WHERE group_id = ? AND category = ?");
    $stmt->execute([$groupId, $category]);
    if ($stmt->fetch()) {
        http_response_code(409);
        echo json_encode(['message' => 'Un défi existe déjà pour cette catégorie dans ce groupe']);
        exit;
    }

    // On garde max 15 questions, on nettoie les données
    $clean = array_slice($questions, 0, 15);
    $json  = json_encode($clean, JSON_UNESCAPED_UNICODE);

    $pdo->prepare("INSERT INTO group_challenges (group_id, category, questions_json, created_by) VALUES (?, ?, ?, ?)")
        ->execute([$groupId, $category, $json, $userId]);
    $challengeId = (int)$pdo->lastInsertId();

    echo json_encode([
        'message'      => 'Défi créé !',
        'challenge_id' => $challengeId,
        'category'     => $category,
        'group_id'     => $groupId
    ]);
    exit;
}

// ─── SUBMIT CHALLENGE ─────────────────────────────────────────────────────────
if ($action === 'submit_challenge' && $method === 'POST') {
    $userId      = requireAuth();
    $challengeId = (int)($body['challenge_id'] ?? 0);
    $score       = (int)($body['score']        ?? 0);
    $good        = (int)($body['good']         ?? 0);
    $bad         = (int)($body['bad']          ?? 0);
    $answers     = $body['answers']            ?? [];

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

    // Vérif challenge existe + user est membre du groupe
    $stmt = $pdo->prepare("SELECT gc.group_id FROM group_challenges gc JOIN group_members gm ON gm.group_id = gc.group_id AND gm.user_id = ? WHERE gc.id = ?");
    $stmt->execute([$userId, $challengeId]);
    if (!$stmt->fetch()) {
        http_response_code(403);
        echo json_encode(['message' => 'Challenge introuvable ou accès refusé']);
        exit;
    }

    // Déjà soumis ?
    $stmt = $pdo->prepare("SELECT 1 FROM challenge_results WHERE challenge_id = ? AND user_id = ?");
    $stmt->execute([$challengeId, $userId]);
    if ($stmt->fetch()) {
        http_response_code(409);
        echo json_encode(['message' => 'Tu as déjà soumis ce défi']);
        exit;
    }

    $json = json_encode($answers, JSON_UNESCAPED_UNICODE);
    $pdo->prepare("INSERT INTO challenge_results (challenge_id, user_id, score, good, bad, answers_json) VALUES (?, ?, ?, ?, ?, ?)")
        ->execute([$challengeId, $userId, $score, $good, $bad, $json]);

    // Retourne les résultats de tous les joueurs
    $stmt = $pdo->prepare("SELECT cr.score, cr.good, cr.bad, cr.answers_json, cr.finished_at, u.username FROM challenge_results cr JOIN users u ON u.id = cr.user_id WHERE cr.challenge_id = ? ORDER BY cr.score DESC");
    $stmt->execute([$challengeId]);
    $results = $stmt->fetchAll();
    foreach ($results as &$r) {
        $r['answers'] = json_decode($r['answers_json'], true);
        unset($r['answers_json']);
    }

    echo json_encode(['message' => 'Résultat enregistré', 'results' => $results]);
    exit;
}

// ─── GET CHALLENGE ────────────────────────────────────────────────────────────
if ($action === 'get_challenge' && $method === 'GET') {
    $userId      = requireAuth();
    $challengeId = (int)($_GET['challenge_id'] ?? 0);

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

    // Vérif accès
    $stmt = $pdo->prepare("SELECT gc.*, u.username AS created_by_name FROM group_challenges gc JOIN group_members gm ON gm.group_id = gc.group_id AND gm.user_id = ? JOIN users u ON u.id = gc.created_by WHERE gc.id = ?");
    $stmt->execute([$userId, $challengeId]);
    $challenge = $stmt->fetch();

    if (!$challenge) {
        http_response_code(403);
        echo json_encode(['message' => 'Challenge introuvable ou accès refusé']);
        exit;
    }

    $challenge['questions'] = json_decode($challenge['questions_json'], true);
    unset($challenge['questions_json']);

    // Mon résultat
    $stmt = $pdo->prepare("SELECT score, good, bad, answers_json FROM challenge_results WHERE challenge_id = ? AND user_id = ?");
    $stmt->execute([$challengeId, $userId]);
    $myResult = $stmt->fetch();
    $challenge['my_result'] = null;

    if ($myResult) {
        $myResult['answers'] = json_decode($myResult['answers_json'], true);
        unset($myResult['answers_json']);
        $challenge['my_result'] = $myResult;

        // Si j'ai fini → je vois les résultats de tous
        $stmt = $pdo->prepare("SELECT cr.score, cr.good, cr.bad, cr.answers_json, cr.finished_at, u.username FROM challenge_results cr JOIN users u ON u.id = cr.user_id WHERE cr.challenge_id = ? ORDER BY cr.score DESC");
        $stmt->execute([$challengeId]);
        $results = $stmt->fetchAll();
        foreach ($results as &$r) {
            $r['answers'] = json_decode($r['answers_json'], true);
            unset($r['answers_json']);
        }
        $challenge['results'] = $results;
    } else {
        $challenge['results'] = null; // Pas encore fini → pas de résultats
    }

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

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