<?php
session_start();
include "connection.php";
include "validation.php";

header("Content-Type: application/json");
$response = ["status" => false, "message" => ""];

try {
    $json = file_get_contents("php://input");
    $data = json_decode($json, true);

    if (!isset($_SESSION["user"]["id"])) {
        throw new Exception("Unauthorized. Please login.");
    }
    $student_id = $_SESSION["user"]["id"];

    $answers = $data["answers"] ?? [];
    if (!is_array($answers) || count($answers) == 0) {
        throw new Exception("No answers received.");
    }

    // Build map: question_id => selected_option
    $answerMap = [];
    foreach ($answers as $entry) {
        $qid = intval($entry["question_id"]);
        $sel = $entry["selected_option"] ?? null;
        $answerMap[$qid] = $sel !== null ? strtoupper(trim($sel)) : null;
    }

    $total_questions = count($answerMap);
    $correct_count = 0;
    $review = [];
    $idx = 0;

    foreach ($answerMap as $qid => $selectedLetter) {
        $mcqRs = Database::search("SELECT `correct_option`,`option_a`,`option_b`,`option_c`,`option_d`,`question`,`lesson_id` FROM `mcq` WHERE `id` = '" . $qid . "' LIMIT 1");
        if ($mcqRs->num_rows == 0) continue;
        $mcq = $mcqRs->fetch_assoc();

        $dbCo = trim($mcq["correct_option"]);
        $correctLetter = strlen($dbCo) === 1 ? strtoupper($dbCo) : "";

        $is_correct = ($selectedLetter !== null && $selectedLetter === $correctLetter);
        if ($is_correct) $correct_count++;

        $review[] = [
            "question_no" => $idx + 1,
            "id" => $qid,
            "question" => $mcq["question"],
            "option_a" => $mcq["option_a"],
            "option_b" => $mcq["option_b"],
            "option_c" => $mcq["option_c"],
            "option_d" => $mcq["option_d"],
            "correct_option" => strtolower($correctLetter ?: ""),
            "selected_option" => strtolower($selectedLetter ?: ""),
            "is_correct" => $is_correct
        ];

        $lesson_id = $mcq["lesson_id"]; // save lesson_id for subject lookup
        $idx++;
    }

    // Determine subject_id for lesson
    $srs = Database::search("SELECT subject_id FROM `lesson` WHERE `id` = '" . $lesson_id . "' LIMIT 1");
    $srow = $srs->fetch_assoc();
    $subject_id = $srow["subject_id"] ?? 0;

    // Insert/update results
    $nowStr = (new DateTime("now", new DateTimeZone("Asia/Colombo")))->format("Y-m-d H:i:s");
    $check = Database::search("SELECT * FROM `student_subject_results` WHERE `student_id` = '" . $student_id . "' AND `subject_id` = '" . $subject_id . "' AND `lesson_id` = '" . $lesson_id . "' LIMIT 1");
    if ($check->num_rows > 0) {
        Database::iud("UPDATE `student_subject_results` SET `marks` = '$correct_count', `total_questions` = '$total_questions', `submitted_date` = '$nowStr', `status` = 'Completed' WHERE `student_id` = '$student_id' AND `subject_id` = '$subject_id' AND `lesson_id` = '$lesson_id'");
    } else {
        Database::iud("INSERT INTO `student_subject_results` (`student_id`,`subject_id`,`lesson_id`,`marks`,`total_questions`,`submitted_date`,`status`) VALUES ('$student_id','$subject_id','$lesson_id','$correct_count','$total_questions','$nowStr','Completed')");
    }

    $_SESSION["exam_result"] = [
        "total" => $total_questions,
        "correct" => $correct_count,
        "percentage" => ($total_questions > 0) ? round(($correct_count / $total_questions) * 100, 2) : 0,
        "review" => $review,
        "finished_at" => $nowStr
    ];

    $response["status"] = true;
    $response["message"] = "Exam submitted successfully.";
    $response["data"] = $_SESSION["exam_result"];

} catch (mysqli_sql_exception $e) {
    $response["message"] = "SQL Error: " . $e->getMessage();
} catch (Exception $e) {
    $response["message"] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;
?>
