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

const GAME_ADMIN_KEY = 'titoue-2026';

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

function respond($data, int $status = 200): void {
    http_response_code($status);
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function requireGameAdmin(): void {
    $key = $_GET['key'] ?? ($_SERVER['HTTP_X_ADMIN_KEY'] ?? '');
    if (!hash_equals(GAME_ADMIN_KEY, (string)$key)) {
        respond(['message' => 'Clé admin invalide'], 403);
    }
}

function ensureGameQuestionsTable(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS game_questions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        game_type ENUM('blitz','memory','imposteur','geo','sondage','juste_prix','timeline','popcorn','alcool_order') NOT NULL,
        question TEXT NOT NULL,
        options TEXT NOT NULL,
        answer VARCHAR(255) NOT NULL,
        explanation TEXT,
        date_event VARCHAR(100) DEFAULT NULL,
        hints TEXT DEFAULT NULL,
        active TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        KEY idx_game_type_active (game_type, active)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
}

function validGameTypes(): array {
    return ['memory','timeline','popcorn','geo','sondage','juste_prix','alcool_order'];
}

function normalizeList($value): array {
    if (is_array($value)) {
        return array_values(array_filter(array_map('trim', $value), fn($v) => $v !== ''));
    }
    if (is_string($value)) {
        $decoded = json_decode($value, true);
        if (is_array($decoded)) return normalizeList($decoded);
        $parts = preg_split('/[;\n|]+/', $value);
        return array_values(array_filter(array_map('trim', $parts), fn($v) => $v !== ''));
    }
    return [];
}

function normalizeGameQuestion(array $q): array {
    $gameType = trim((string)($q['game_type'] ?? ''));
    if (!in_array($gameType, validGameTypes(), true)) {
        throw new InvalidArgumentException('game_type invalide');
    }
    $question = trim((string)($q['question'] ?? ''));
    $answer = trim((string)($q['answer'] ?? ''));
    if ($question === '' || $answer === '') {
        throw new InvalidArgumentException('question et answer sont requis');
    }
    return [
        'game_type' => $gameType,
        'question' => $question,
        'options' => normalizeList($q['options'] ?? []),
        'answer' => $answer,
        'explanation' => trim((string)($q['explanation'] ?? '')),
        'date_event' => trim((string)($q['date_event'] ?? '')),
        'hints' => normalizeList($q['hints'] ?? []),
        'active' => !empty($q['active']) ? 1 : 0,
    ];
}

function rowToGameQuestion(array $row): array {
    $row['id'] = (int)$row['id'];
    $row['active'] = (int)$row['active'];
    $options = json_decode($row['options'] ?? '[]', true);
    $hints = json_decode($row['hints'] ?? '[]', true);
    $row['options'] = is_array($options) ? $options : [];
    $row['hints'] = is_array($hints) ? $hints : [];
    return $row;
}

ensureGameQuestionsTable($pdo);

if ($action === 'types' && $method === 'GET') {
    $stmt = $pdo->query("SELECT game_type, COUNT(*) AS total, SUM(active = 1) AS active_count
        FROM game_questions
        GROUP BY game_type
        ORDER BY game_type ASC");
    respond(['types' => $stmt->fetchAll()]);
}

if ($action === 'list' && $method === 'GET') {
    requireGameAdmin();
    $gameType = trim($_GET['game_type'] ?? '');
    $search = trim($_GET['q'] ?? '');
    $active = $_GET['active'] ?? '';
    $page = max(1, (int)($_GET['page'] ?? 1));
    $limit = max(10, min(100, (int)($_GET['limit'] ?? 30)));
    $offset = ($page - 1) * $limit;

    $where = [];
    $params = [];
    if ($gameType !== '') { $where[] = 'game_type = ?'; $params[] = $gameType; }
    if ($search !== '') {
        $where[] = '(question LIKE ? OR answer LIKE ? OR explanation LIKE ? OR date_event LIKE ?)';
        $needle = '%' . $search . '%';
        array_push($params, $needle, $needle, $needle, $needle);
    }
    if ($active !== '') { $where[] = 'active = ?'; $params[] = (int)$active; }
    $sqlWhere = $where ? 'WHERE ' . implode(' AND ', $where) : '';

    $count = $pdo->prepare("SELECT COUNT(*) FROM game_questions $sqlWhere");
    $count->execute($params);
    $total = (int)$count->fetchColumn();

    $stmt = $pdo->prepare("SELECT * FROM game_questions $sqlWhere ORDER BY id DESC LIMIT $limit OFFSET $offset");
    $stmt->execute($params);
    respond([
        'questions' => array_map('rowToGameQuestion', $stmt->fetchAll()),
        'page' => $page,
        'limit' => $limit,
        'total' => $total,
    ]);
}

if ($action === 'save' && $method === 'POST') {
    requireGameAdmin();
    try {
        $q = normalizeGameQuestion($body);
    } catch (InvalidArgumentException $e) {
        respond(['message' => $e->getMessage()], 400);
    }
    $id = (int)($body['id'] ?? 0);
    $optionsJson = json_encode($q['options'], JSON_UNESCAPED_UNICODE);
    $hintsJson = $q['hints'] ? json_encode($q['hints'], JSON_UNESCAPED_UNICODE) : null;
    $dateEvent = $q['date_event'] !== '' ? $q['date_event'] : null;

    if ($id > 0) {
        $stmt = $pdo->prepare("UPDATE game_questions
            SET game_type = ?, question = ?, options = ?, answer = ?, explanation = ?, date_event = ?, hints = ?, active = ?
            WHERE id = ?");
        $stmt->execute([$q['game_type'], $q['question'], $optionsJson, $q['answer'], $q['explanation'], $dateEvent, $hintsJson, $q['active'], $id]);
        respond(['message' => 'Question de jeu modifiée', 'id' => $id]);
    }

    $stmt = $pdo->prepare("INSERT INTO game_questions
        (game_type, question, options, answer, explanation, date_event, hints, active)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$q['game_type'], $q['question'], $optionsJson, $q['answer'], $q['explanation'], $dateEvent, $hintsJson, $q['active']]);
    respond(['message' => 'Question de jeu ajoutée', 'id' => (int)$pdo->lastInsertId()]);
}

if ($action === 'bulk' && $method === 'POST') {
    requireGameAdmin();
    $items = $body['questions'] ?? [];
    if (!is_array($items)) respond(['message' => 'questions doit être une liste'], 400);
    $stmt = $pdo->prepare("INSERT INTO game_questions
        (game_type, question, options, answer, explanation, date_event, hints, active)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $imported = 0;
    $skipped = 0;
    foreach ($items as $item) {
        try {
            $q = normalizeGameQuestion($item);
            $stmt->execute([
                $q['game_type'],
                $q['question'],
                json_encode($q['options'], JSON_UNESCAPED_UNICODE),
                $q['answer'],
                $q['explanation'],
                $q['date_event'] !== '' ? $q['date_event'] : null,
                $q['hints'] ? json_encode($q['hints'], JSON_UNESCAPED_UNICODE) : null,
                $q['active']
            ]);
            $imported++;
        } catch (Throwable $e) {
            $skipped++;
        }
    }
    respond(['message' => 'Import terminé', 'imported' => $imported, 'skipped' => $skipped]);
}

if ($action === 'toggle' && $method === 'POST') {
    requireGameAdmin();
    $id = (int)($body['id'] ?? 0);
    $active = !empty($body['active']) ? 1 : 0;
    if (!$id) respond(['message' => 'id requis'], 400);
    $stmt = $pdo->prepare("UPDATE game_questions SET active = ? WHERE id = ?");
    $stmt->execute([$active, $id]);
    respond(['message' => $active ? 'Question activée' : 'Question désactivée']);
}

if ($action === 'delete' && $method === 'POST') {
    requireGameAdmin();
    $id = (int)($body['id'] ?? 0);
    if (!$id) respond(['message' => 'id requis'], 400);
    $stmt = $pdo->prepare("DELETE FROM game_questions WHERE id = ?");
    $stmt->execute([$id]);
    respond(['message' => 'Question supprimée']);
}

respond(['message' => 'Action inconnue'], 404);
