﻿﻿??????????????
﻿﻿??????????????
<?php
require_once "session-st.php";
require_once "connection.php";

// Force correct timezone
date_default_timezone_set("Asia/Kolkata");

if (!isset($_GET['assignment_id'])) {
    die("Invalid request.");
}

$assignment_id = (int)$_GET['assignment_id'];
$student_id = (int)$_SESSION['student_id'];

try {

    // ----------------------------------
    // 1) Fetch student course
    // ----------------------------------
    $stu = $pdo->prepare("SELECT course FROM students WHERE id = ?");
    $stu->execute([$student_id]);
    $student = $stu->fetch(PDO::FETCH_ASSOC);

    if (!$student) {
        die("Student not found.");
    }

    $studentCourse = trim($student['course']);

    // ----------------------------------
    // 2) Fetch Assignment
    // ----------------------------------
    $stmt = $pdo->prepare("SELECT * FROM assignments WHERE id = ?");
    $stmt->execute([$assignment_id]);
    $assignment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$assignment) {
        die("Assignment not found.");
    }

    // ----------------------------------
// 3) MATCH STUDENT COURSE NAME -> COURSE ID
// ----------------------------------

// Student course name (example: "Computer Science")
$studentCourseName = trim($student['course']);

// Find its ID from course table
$courseQuery = $pdo->prepare("SELECT id FROM course WHERE course = ?");
$courseQuery->execute([$studentCourseName]);
$courseRow = $courseQuery->fetch(PDO::FETCH_ASSOC);

if (!$courseRow) {
    die("Student course not found in course table.");
}

$studentCourseID = (int)$courseRow['id'];

// Assignment course
$assignmentCourseID = (int)$assignment['course_id'];

// Compare
if ($studentCourseID !== $assignmentCourseID) {
    die("You are not allowed to access this test.");
}


    // ----------------------------------
    // 4) Time window check
    // ----------------------------------
    $now = new DateTime("now", new DateTimeZone("Asia/Kolkata"));
    $start = new DateTime($assignment['start_datetime'], new DateTimeZone("Asia/Kolkata"));
    $end = new DateTime($assignment['end_datetime'], new DateTimeZone("Asia/Kolkata"));

    // DEBUG — Remove after testing
    /*
    echo "NOW: " . $now->format("Y-m-d H:i:s") . "<br>";
    echo "START: " . $start->format("Y-m-d H:i:s") . "<br>";
    echo "END: " . $end->format("Y-m-d H:i:s") . "<br>";
    exit;
    */

    if ($now < $start) {
        die("Test has not started yet.");
    }

    if ($now > $end) {
        die("Test has already ended.");
    }

    // ----------------------------------
    // 5) Prevent race condition
    // ----------------------------------
    $pdo->beginTransaction();

    $lock = $pdo->prepare("
        SELECT *
        FROM student_attempts
        WHERE student_id = ? AND assignment_id = ?
        FOR UPDATE
    ");
    $lock->execute([$student_id, $assignment_id]);

    $existing = $lock->fetch(PDO::FETCH_ASSOC);

    // If attempt exists
    if ($existing) {

        if ($existing['status'] === 'in_progress') {
            $attempt_id = $existing['id'];
            $pdo->commit();
            header("Location: test_page.php?attempt_id=$attempt_id");
            exit;
        }

        $pdo->rollBack();
        die("You have already completed this test.");
    }

    // ----------------------------------
    // 6) Create new attempt
    // ----------------------------------
    $insert = $pdo->prepare("
        INSERT INTO student_attempts 
        (assignment_id, student_id, started_at, status, total_possible)
        VALUES (?, ?, NOW(), 'in_progress', ?)
    ");

    $insert->execute([
        $assignment_id,
        $student_id,
        $assignment['total_marks'] ?? 0
    ]);

    $attempt_id = $pdo->lastInsertId();
    $pdo->commit();

    header("Location: test_page.php?attempt_id=$attempt_id");
    exit;

} catch (Exception $e) {

    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    die("Error: " . $e->getMessage());
}
?>
