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

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

if (!isset($_SESSION['student_id'], $_SESSION['token'], $_SESSION['exam_id'])) {
    echo json_encode(['error' => 'unauthorized']);
    exit;
}

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

$stmt = $mysqli->prepare("SELECT 
    t.login_time, 
    e.total_allowed_time 
    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();

if (!$data) {
    echo json_encode(['error' => 'not found']);
    exit;
}

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

echo json_encode(['remaining' => max(0, $remaining)]);
