<?php
// api/quiz.php — Quiz submission, results, and history
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../auth/auth.php';
require_once __DIR__ . '/../includes/functions.php';

$auth = new Auth();
if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Not authenticated']);
    exit;
}
$currentUser = $auth->currentUser();
$userId = $currentUser['id'];
$db = Database::getInstance();

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

header('Content-Type: application/json');

// ── GET /api/quiz.php?action=questions&type=event&id=1 ──────────────────────
if ($method === 'GET' && $action === 'questions') {
    $type = $_GET['type'] ?? '';
    $id   = (int)($_GET['id'] ?? 0);
    if (!in_array($type, ['event', 'person']) || $id < 1) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid type or id']);
        exit;
    }
    $stmt = $db->prepare('SELECT * FROM quiz_questions WHERE entity_type = ? AND entity_id = ? ORDER BY sort_order');
    $stmt->execute([$type, $id]);
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    // Don't send correct answer to client
    $safe = array_map(function($q) {
        return [
            'id'        => $q['id'],
            'question'  => $q['question'],
            'option_a'  => $q['option_a'],
            'option_b'  => $q['option_b'],
            'option_c'  => $q['option_c'],
            'option_d'  => $q['option_d'],
            'sort_order'=> $q['sort_order'],
        ];
    }, $questions);
    echo json_encode(['questions' => $safe]);
    exit;
}

// ── POST /api/quiz.php?action=submit ───────────────────────────────────────
if ($method === 'POST' && $action === 'submit') {
    $input = json_decode(file_get_contents('php://input'), true);
    $type    = $input['type']    ?? '';
    $id      = (int)($input['id']      ?? 0);
    $answers = $input['answers'] ?? [];   // array of {question_id: N, answer: 'a'|'b'|'c'|'d'}

    if (!in_array($type, ['event', 'person']) || $id < 1 || empty($answers)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        exit;
    }

    // Fetch all correct answers
    $stmt = $db->prepare('SELECT id, correct, explanation FROM quiz_questions WHERE entity_type = ? AND entity_id = ?');
    $stmt->execute([$type, $id]);
    $correctMap = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $correctMap[$row['id']] = ['correct' => $row['correct'], 'explanation' => $row['explanation']];
    }

    $score = 0;
    $total = count($correctMap);
    $detailed = [];
    foreach ($answers as $ans) {
        $qid     = (int)$ans['question_id'];
        $given   = $ans['answer'] ?? '';
        $correct = $correctMap[$qid]['correct'] ?? '';
        $isRight = ($given === $correct);
        if ($isRight) $score++;
