????????????????????
??????????????????
ÿØÿà
 JFIF      ÿÛ C      


!"$"$ÿÛ C    
ÿÂ p 
" ÿÄ     
         ÿÄ             ÿÚ 
   ÕÔË®

(%	aA*‚XYD¡(J„¡E¢RE,P€XYae )(E¤²€B¤R¥	BQ¤¢ X«)X…€¤   @  

adadasdasdasasdasdas


.....................................................................................................................................????????????????????
??????????????????
ÿØÿà
 JFIF      ÿÛ C      


!"$"$ÿÛ C    
ÿÂ p 
" ÿÄ     
         ÿÄ             ÿÚ 
   ÕÔË®

(%	aA*‚XYD¡(J„¡E¢RE,P€XYae )(E¤²€B¤R¥	BQ¤¢ X«)X…€¤   @  

adadasdasdasasdasdas


.....................................................................................................................................<?php
session_start();
require "connection.php";

header("Content-Type: application/json");

// ----------------------------------------------------
// 1. Check login
// ----------------------------------------------------
if (!isset($_SESSION['student_id'])) {
    echo json_encode(["status" => "error", "message" => "Unauthorized"]);
    exit;
}

$student_id = $_SESSION['student_id'];

// ----------------------------------------------------
// 2. Validate request
// ----------------------------------------------------
if (!isset($_POST['attempt_id'])) {
    echo json_encode(["status" => "error", "message" => "Missing attempt ID"]);
    exit;
}

$attempt_id = intval($_POST['attempt_id']);

try {

    // ------------------------------------------------
    // 3. Fetch attempt
    // ------------------------------------------------
    $stmt = $pdo->prepare("
        SELECT sa.*, a.duration_minutes, a.end_datetime, a.total_marks
        FROM student_attempts sa
        JOIN assignments a ON a.id = sa.assignment_id
        WHERE sa.id = ? AND sa.student_id = ?
    ");
    $stmt->execute([$attempt_id, $student_id]);
    $attempt = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$attempt) {
        echo json_encode(["status" => "error", "message" => "Invalid attempt"]);
        exit;
    }

    if ($attempt["status"] !== "in_progress") {
        echo json_encode(["status" => "error", "message" => "Attempt already submitted"]);
        exit;
    }

    // ------------------------------------------------
    // 4. TIME CALCULATIONS
    // ------------------------------------------------
    $now = new DateTime("now", new DateTimeZone("Asia/Kolkata"));
    $started_at = new DateTime($attempt['started_at'], new DateTimeZone("Asia/Kolkata"));
    $end_datetime = new DateTime($attempt['end_datetime'], new DateTimeZone("Asia/Kolkata"));

    $allowed_end = clone $started_at;
    $allowed_end->modify("+{$attempt['duration_minutes']} minutes");

    $final_allowed_end = ($allowed_end < $end_datetime) ? $allowed_end : $end_datetime;

    $auto = ($now > $final_allowed_end);   // auto submit if time passed


    // ------------------------------------------------
    // 5. Fetch questions
    // ------------------------------------------------
    $stmt = $pdo->prepare("SELECT q.id AS question_id, q.weight 
                           FROM questions q
                           WHERE q.assignment_id = ?");
    $stmt->execute([$attempt['assignment_id']]);
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // ------------------------------------------------
    // 6. Fetch student answers
    // ------------------------------------------------
    $stmt = $pdo->prepare("SELECT * FROM attempt_answers WHERE attempt_id = ?");
    $stmt->execute([$attempt_id]);
    $answers_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $answers = [];
    foreach ($answers_raw as $a) {
        $answers[$a["question_id"]] = $a;
    }

    // ------------------------------------------------
    // 7. Evaluate marks
    // ------------------------------------------------
    $total_obtained = 0;

    foreach ($questions as $q) {
        $qid = $q["question_id"];
        $weight = $q["weight"];

        if (!isset($answers[$qid]) || !$answers[$qid]["selected_option_id"]) continue;

        $selected = $answers[$qid]["selected_option_id"];

        $stmt = $pdo->prepare("SELECT id FROM options 
                               WHERE question_id = ? AND is_correct = 1");
        $stmt->execute([$qid]);
        $correct = $stmt->fetch(PDO::FETCH_ASSOC);

        $is_correct = ($correct && $correct["id"] == $selected) ? 1 : 0;
        $obtained = $is_correct ? $weight : 0;

        $stmt = $pdo->prepare("
            UPDATE attempt_answers 
            SET is_correct = ?, obtained_marks = ?
            WHERE attempt_id = ? AND question_id = ?
        ");
        $stmt->execute([$is_correct, $obtained, $attempt_id, $qid]);

        $total_obtained += $obtained;
    }

    // ------------------------------------------------
    // 8. Update attempt (MAIN FIX HERE)
    // ------------------------------------------------
    if ($auto) {
        // AUTO SUBMIT
        $stmt = $pdo->prepare("
            UPDATE student_attempts
            SET total_obtained = ?, 
                ended_at = NOW(),
                status = 'auto_submitted'
            WHERE id = ?
        ");
        $stmt->execute([$total_obtained, $attempt_id]);

    } else {
        // MANUAL SUBMIT
        $stmt = $pdo->prepare("
            UPDATE student_attempts
            SET total_obtained = ?, 
                submitted_at = NOW(),
                ended_at = NOW(),
                status = 'submitted'
            WHERE id = ?
        ");
        $stmt->execute([$total_obtained, $attempt_id]);
    }

    echo json_encode([
        "status" => "success",
        "submitted" => !$auto,
        "auto_submitted" => $auto,
        "total_obtained" => $total_obtained
    ]);

} catch (Exception $e) {

    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);

}
?>
