<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

include 'config.php';

// Retrieve email from the request
$email = $_GET['email'];

// Check if the user exists and get their category
$query = "SELECT user_id, category_id FROM users WHERE email = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    die(json_encode(['error' => 'User not found']));
}

$user_id = $user['user_id'];
$category_id = $user['category_id'];

// Fetch the latest topic in the user's category
$query = "SELECT MAX(topic_id) FROM topics WHERE category_id = ? ORDER BY created_at DESC LIMIT 1";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $category_id);
$stmt->execute();
$result = $stmt->get_result();
$topic = $result->fetch_assoc();

if (!$topic) {
    die(json_encode(['error' => 'No topics found for this category']));
}

$topic_id = $topic['topic_id'];

// Check if the user has already attempted the quiz
$query = "SELECT score FROM attempts WHERE user_id = ? AND topic_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("ii", $user_id, $topic_id);
$stmt->execute();
$result = $stmt->get_result();
$attempt = $result->fetch_assoc();

if ($attempt) {
    die(json_encode(['error' => 'You have already attempted this quiz', 'score' => $attempt['score']]));
}

// Fetch questions and options for the latest topic in the user's category
$query = "SELECT q.question_id, q.question_text, o.option_id, o.option_text, o.is_correct 
          FROM questions q
          JOIN options o ON q.question_id = o.question_id
          WHERE q.topic_id = ?
          ORDER BY q.question_id, o.option_id";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $topic_id);
$stmt->execute();
$result = $stmt->get_result();
$results = $result->fetch_all(MYSQLI_ASSOC);

// Prepare the data in structured format
$questions = [];
$current_question_id = -1;
foreach ($results as $row) {
    if ($current_question_id != $row['question_id']) {
        $current_question_id = $row['question_id'];
        $questions[$current_question_id] = [
            'question_id' => $row['question_id'],
            'question_text' => $row['question_text'],
            'options' => []
        ];
    }
    $questions[$current_question_id]['options'][] = [
        'option_id' => $row['option_id'],
        'option_text' => $row['option_text'],
        'is_correct' => $row['is_correct']
    ];
}

// Fetch previous scores
$query = "SELECT t.topic_name, a.score, a.attempt_date 
          FROM attempts a
          JOIN topics t ON a.topic_id = t.topic_id
          WHERE a.user_id = ? 
          ORDER BY a.attempt_date DESC";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$previous_scores = $result->fetch_all(MYSQLI_ASSOC);

// Output the data as JSON
header('Content-Type: application/json');
echo json_encode(['questions' => array_values($questions), 'previous_scores' => $previous_scores]);
?>
