<?php
session_start();
include "db.php";

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

if(!isset($_SESSION['user_id'])){
    echo json_encode(['success'=>false,'msg'=>'Not logged in']); exit;
}

$user_id = $_SESSION['user_id'];
$module_id = isset($_GET['module_id']) ? intval($_GET['module_id']) : 0;

if(!$module_id){
    echo json_encode(['success'=>false,'msg'=>'Invalid module']); exit;
}

// Fetch quiz for this module
$stmt = $conn->prepare("SELECT * FROM quizzes WHERE module_id=?");
$stmt->bind_param("i", $module_id);
$stmt->execute();
$quizRes = $stmt->get_result();

if($quizRes->num_rows==0){
    echo json_encode(['success'=>false,'msg'=>'No quiz found']); exit;
}

$quiz = $quizRes->fetch_assoc();
$quiz_id = $quiz['id'];
$duration = $quiz['duration_minutes'];

// Fetch questions & options
$qStmt = $conn->prepare("SELECT * FROM quiz_questions WHERE quiz_id=?");
$qStmt->bind_param("i",$quiz_id);
$qStmt->execute();
$qRes = $qStmt->get_result();

$questions=[];
while($q = $qRes->fetch_assoc()){
    $optStmt = $conn->prepare("SELECT id,option_text FROM quiz_options WHERE question_id=?");
    $optStmt->bind_param("i",$q['id']);
    $optStmt->execute();
    $optRes = $optStmt->get_result();
    $options=[];
    while($o = $optRes->fetch_assoc()){
        $options[] = $o;
    }
    $questions[]=[
        'id'=>$q['id'],
        'question'=>$q['question'],
        'options'=>$options
    ];
}

echo json_encode([
    'success'=>true,
    'duration'=>$duration,
    'questions'=>$questions
]);
