<?php
session_start();
require_once 'inc/connect.php';


$student_id = $_SESSION['student_id'];
$token_id = $_SESSION['token'];
$exam_id = $_SESSION['exam_id'];

$data = json_decode(file_get_contents("php://input"), true);
$question_id = $data['question_id'] ?? '';

$out = ['question' => '', 'options' => [], 'timer1' => [], 'attempted' => '0', 'answered' => '0'];

$q = $mysqli->prepare("SELECT content FROM question_bank WHERE question_id = ? AND content_role = 'question' LIMIT 1");
$q->bind_param("s", $question_id);
$q->execute();
$res = $q->get_result();
if ($row = $res->fetch_assoc()) $out['question'] = $row['content'];

$q2 = $mysqli->prepare("SELECT serial, content FROM question_bank WHERE question_id = ? AND content_role IN ('correct', 'wrong')");
$q2->bind_param("s", $question_id);
$q2->execute();
$r2 = $q2->get_result();
while ($opt = $r2->fetch_assoc()) {
    $out['options'][] = $opt;
}

$q3 = $mysqli->prepare("SELECT COUNT(*) AS total FROM `student_attempt_log` WHERE question_id = ? AND token_id = ?");
$q3->bind_param("ss", $question_id, $token_id);
$q3->execute();
$q3->bind_result($total);
$q3->fetch();
$q3->close();




$out['attempted'] = $total. ' **(Please just log out when you are done.)**';



$q3 = $mysqli->prepare("SELECT COUNT(DISTINCT question_id) AS total FROM student_attempt_log WHERE token_id = ?");
$q3->bind_param("s", $token_id);
$q3->execute();
$q3->bind_result($total);
$q3->fetch();
$q3->close();




$out['answered'] = $total;




// Fetch exam + token details
$stmt = $mysqli->prepare("SELECT 
    t.login_time, 
    e.total_allowed_time, 
    e.examination_title 
    FROM token_management t 
    JOIN examination_table e ON t.examination_id = e.examination_id 
    WHERE t.token_id = ? AND t.student_id = ? AND t.examination_id = ?");
$stmt->bind_param("sis", $token_id, $student_id, $exam_id);
$stmt->execute();
$res = $stmt->get_result();
$data = $res->fetch_assoc();


$login_time = strtotime($data['login_time']);


$total_seconds = intval($data['total_allowed_time']) * 60;
$current_time = time();

$out['timer1']['total_seconds'] = $total_seconds;
$TIMEDIFF =  $current_time - $login_time;
$out['timer1']['total_seconds_left'] =   $total_seconds - $TIMEDIFF;
$out['timer1']['total_seconds_left1'] =   $data['login_time'];
$out['timer1']['total_seconds_left2'] =   date('Y-m-d H:i:s');;



// Step 3: Close any previous submissions for this question_set_ref and token_id
$closebb = $mysqli->prepare("UPDATE token_management 
                           SET last_activity = NOW() 
                           WHERE  token_id = ?");
$closebb->bind_param("s",  $token_id);
$closebb->execute();


echo json_encode($out);
