<?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 QUIZ_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 requireQuizAdmin(): void {
    $key = $_GET['key'] ?? ($_SERVER['HTTP_X_ADMIN_KEY'] ?? '');
    if (!hash_equals(QUIZ_ADMIN_KEY, (string)$key)) {
        respond(['message' => 'Clé admin invalide'], 403);
    }
}

function ensureQuizQuestionsTable(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS quiz_questions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        category VARCHAR(80) NOT NULL,
        question TEXT NOT NULL,
        options LONGTEXT NOT NULL,
        answer VARCHAR(500) NOT NULL,
        explanation TEXT,
        difficulty VARCHAR(40) DEFAULT 'standard',
        active TINYINT(1) NOT NULL DEFAULT 1,
        source_hash CHAR(40) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_quiz_source_hash (source_hash),
        KEY idx_quiz_category_active (category, active),
        KEY idx_quiz_active (active)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
}

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

function questionHash(string $category, string $question, string $answer): string {
    $base = trim($category) . '|' . trim($question) . '|' . trim($answer);
    $base = function_exists('mb_strtolower') ? mb_strtolower($base, 'UTF-8') : strtolower($base);
    return sha1($base);
}

function normalizeQuestion(array $q): array {
    $category = trim((string)($q['category'] ?? ''));
    $question = trim((string)($q['question'] ?? ''));
    $answer = trim((string)($q['answer'] ?? ''));
    if ($category === '' || $question === '' || $answer === '') {
        throw new InvalidArgumentException('category, question et answer sont requis');
    }
    $difficulty = trim((string)($q['difficulty'] ?? 'standard')) ?: 'standard';
    $options = normalizeOptions($q['options'] ?? []);
    $explanation = trim((string)($q['explanation'] ?? ''));
    return [
        'category' => $category,
        'question' => $question,
        'options' => $options,
        'answer' => $answer,
        'explanation' => $explanation,
        'difficulty' => $difficulty,
        'active' => !empty($q['active']) ? 1 : 0,
        'source_hash' => questionHash($category, $question, $answer),
    ];
}

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

ensureQuizQuestionsTable($pdo);

if ($action === 'public' && $method === 'GET') {
    $category = trim($_GET['category'] ?? '');
    $limit = max(1, min(1000, (int)($_GET['limit'] ?? 500)));
    if ($category !== '') {
        $stmt = $pdo->prepare("SELECT id, category, question, options, answer, explanation, difficulty
            FROM quiz_questions
            WHERE active = 1 AND category = ?
            ORDER BY id DESC
            LIMIT $limit");
        $stmt->execute([$category]);
    } else {
        $stmt = $pdo->query("SELECT id, category, question, options, answer, explanation, difficulty
            FROM quiz_questions
            WHERE active = 1
            ORDER BY id DESC
            LIMIT $limit");
    }
    respond(['questions' => array_map('rowToQuestion', $stmt->fetchAll())]);
}

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

if ($action === 'list' && $method === 'GET') {
    requireQuizAdmin();
    $category = trim($_GET['category'] ?? '');
    $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 ($category !== '') { $where[] = 'category = ?'; $params[] = $category; }
    if ($search !== '') {
        $where[] = '(question LIKE ? OR answer LIKE ? OR explanation LIKE ?)';
        $needle = '%' . $search . '%';
        array_push($params, $needle, $needle, $needle);
    }
    if ($active !== '') { $where[] = 'active = ?'; $params[] = (int)$active; }
    $sqlWhere = $where ? 'WHERE ' . implode(' AND ', $where) : '';

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

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

if ($action === 'save' && $method === 'POST') {
    requireQuizAdmin();
    try {
        $q = normalizeQuestion($body);
    } catch (InvalidArgumentException $e) {
        respond(['message' => $e->getMessage()], 400);
    }
    $id = (int)($body['id'] ?? 0);
    if ($id > 0) {
        $stmt = $pdo->prepare("UPDATE quiz_questions
            SET category = ?, question = ?, options = ?, answer = ?, explanation = ?, difficulty = ?, active = ?, source_hash = ?
            WHERE id = ?");
        $stmt->execute([
            $q['category'], $q['question'], json_encode($q['options'], JSON_UNESCAPED_UNICODE), $q['answer'],
            $q['explanation'], $q['difficulty'], $q['active'], $q['source_hash'], $id
        ]);
        respond(['message' => 'Question modifiée', 'id' => $id]);
    }
    $stmt = $pdo->prepare("INSERT INTO quiz_questions
        (category, question, options, answer, explanation, difficulty, active, source_hash)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
          options = VALUES(options),
          explanation = VALUES(explanation),
          difficulty = VALUES(difficulty),
          active = VALUES(active),
          updated_at = CURRENT_TIMESTAMP");
    $stmt->execute([
        $q['category'], $q['question'], json_encode($q['options'], JSON_UNESCAPED_UNICODE), $q['answer'],
        $q['explanation'], $q['difficulty'], $q['active'], $q['source_hash']
    ]);
    respond(['message' => 'Question enregistrée', 'id' => (int)$pdo->lastInsertId()]);
}

if ($action === 'bulk' && $method === 'POST') {
    requireQuizAdmin();
    $items = $body['questions'] ?? [];
    if (!is_array($items)) respond(['message' => 'questions doit être une liste'], 400);
    $stmt = $pdo->prepare("INSERT INTO quiz_questions
        (category, question, options, answer, explanation, difficulty, active, source_hash)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
          options = VALUES(options),
          explanation = VALUES(explanation),
          difficulty = VALUES(difficulty),
          active = VALUES(active),
          updated_at = CURRENT_TIMESTAMP");
    $imported = 0;
    $skipped = 0;
    foreach ($items as $item) {
        try {
            $q = normalizeQuestion($item);
            $stmt->execute([
                $q['category'], $q['question'], json_encode($q['options'], JSON_UNESCAPED_UNICODE), $q['answer'],
                $q['explanation'], $q['difficulty'], $q['active'], $q['source_hash']
            ]);
            $imported++;
        } catch (Throwable $e) {
            $skipped++;
        }
    }
    respond(['message' => 'Import terminé', 'imported' => $imported, 'skipped' => $skipped]);
}

if ($action === 'seed_defaults' && $method === 'POST') {
    requireQuizAdmin();
    $seedPath = __DIR__ . '/quiz_seed.json';
    if (!is_file($seedPath)) respond(['message' => 'Fichier quiz_seed.json introuvable'], 404);
    $data = json_decode(file_get_contents($seedPath), true);
    if (!is_array($data)) respond(['message' => 'Fichier seed invalide'], 500);
    $items = [];
    $hiddenCategories = ['actu', 'enigmes', 'complot'];
    foreach ($data as $category => $questions) {
        if (in_array($category, $hiddenCategories, true)) continue;
        if (!is_array($questions)) continue;
        foreach ($questions as $q) {
            $q['category'] = $category;
            $q['active'] = 1;
            $items[] = $q;
        }
    }
    $body['questions'] = $items;
    $_GET['action'] = 'bulk';
    $stmt = $pdo->prepare("INSERT INTO quiz_questions
        (category, question, options, answer, explanation, difficulty, active, source_hash)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
          options = VALUES(options),
          explanation = VALUES(explanation),
          difficulty = VALUES(difficulty),
          active = VALUES(active),
          updated_at = CURRENT_TIMESTAMP");
    $imported = 0;
    $skipped = 0;
    foreach ($items as $item) {
        try {
            $q = normalizeQuestion($item);
            $stmt->execute([
                $q['category'], $q['question'], json_encode($q['options'], JSON_UNESCAPED_UNICODE), $q['answer'],
                $q['explanation'], $q['difficulty'], $q['active'], $q['source_hash']
            ]);
            $imported++;
        } catch (Throwable $e) {
            $skipped++;
        }
    }
    respond(['message' => 'Questions actuelles importées', 'imported' => $imported, 'skipped' => $skipped]);
}

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

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

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