<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
?>


<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

chdir('../');
session_start();
require_once('public/connection.php');

if (!isset($_SESSION['student_id']) || !isset($_POST['exam_id'])) {
    header("Location: ../index.php");
    exit;
}

$student_id = $_SESSION['student_id'];
$exam_id = (int)$_POST['exam_id'];
$answers = $_POST['answers'] ?? [];
$Qtype = $_POST['Qtype'];

// Fetch exam info
$exam = $conn->query("SELECT * FROM exams WHERE id = $exam_id")->fetch_assoc();
if (!$exam) {
    die("<div class='alert alert-danger'>Invalid Exam</div>");
}

$exam_group_id = $exam['exam_group_id'];
$exam_type = strtolower(trim($exam['exam_type']));
$class = $exam['class'];
$term = $exam['term'];
$session_yr = $exam['session'];
$subject_id = $exam['subject_id'];

// Validate exam type
$valid_exam_types = ['ca1', 'ca2', 'exam'];
if (!in_array($exam_type, $valid_exam_types)) {
    die("<div class='alert alert-danger'>Invalid Exam Type</div>");
}

// Fetch subject name
$subject_row = $conn->query("SELECT subjects FROM school_subjects WHERE id = $subject_id")->fetch_assoc();
$subject = $subject_row ? $subject_row['subjects'] : '';

// Fetch questions
$stmt = $conn->prepare("SELECT * FROM questions WHERE exam_id = ? AND question_type = ?");
$stmt->bind_param("is", $exam_id, $Qtype);
$stmt->execute();
$questions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Track answers
$mcq_score = 0;
$theory_answers = [];
$has_mcq = false;
$has_theory = false;

foreach ($questions as $q) {
    $qid = $q['id'];
    $submitted = trim($answers[$qid] ?? '');
    $marks = (float)$q['marks'];

    if ($q['question_type'] === 'mcq') {
        $has_mcq = true;
        if (strtolower($submitted) === strtolower($q['correct_answer'])) {
            $mcq_score += $marks;
        }
    } elseif ($q['question_type'] === 'theory') {
        $has_theory = true;
        $theory_answers[$qid] = $submitted;
    }
}

$submitted_at = date("Y-m-d H:i:s");
$started_at = $_SESSION['exam_started_at'] ?? null;

// Handle exam_group_results
$existingResult = $conn->prepare("SELECT * FROM exam_group_results WHERE student_id = ? AND exam_group_id = ?");
$existingResult->bind_param("ii", $student_id, $exam_group_id);
$existingResult->execute();
$resultData = $existingResult->get_result()->fetch_assoc();

// Determine status and remarks based on question types
$status = ($has_theory) ? 'pending' : 'graded';
$remarks = ($has_theory && $has_mcq) ? 'Mixed exam submitted; theory for review' : 
           ($has_theory ? 'Theory exam submitted for review' : 'Auto-graded MCQ exam');
$total = ($has_mcq && !$has_theory) ? $mcq_score : null;



if ($resultData) {
    $existing_id = $resultData['id'];

    // === For Multiple Choice ===
    if ($Qtype === 'mcq' && is_null($resultData['mcq_score'])) {
        $update = $conn->prepare("
            UPDATE exam_group_results 
            SET mcq_score = ?, total = ?, status = ?, remarks = ?, exam_type = ? 
            WHERE id = ?
        ");
        $update->bind_param("ddsssi", $mcq_score, $total, $status, $remarks, $exam_type, $existing_id);
    }

    // === For Theory ===
    elseif ($Qtype === 'theory' && is_null($resultData['theory_score'])) {
        $update = $conn->prepare("
            UPDATE exam_group_results 
            SET theory_score = ?, total = ?, status = ?, remarks = ?, exam_type = ? 
            WHERE id = ?
        ");
        $update->bind_param("ddsssi", $theory_score, $total, $status, $remarks, $exam_type, $existing_id);
    }

    // === Execute Update if Prepared ===
    if (isset($update)) {
        if (!$update->execute()) {
            die("Update error: " . $update->error);
        }
        $update->close();
    }

} else {
    // === Insert New Record ===
    $insert = $conn->prepare("
        INSERT INTO exam_group_results 
        (student_id, class, term, session, subject, exam_group_id, mcq_score, theory_score, total, status, remarks, exam_type) 
        VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?)
    ");
    $insert->bind_param("isssssddsss", $student_id, $class, $term, $session_yr, $subject, $exam_group_id, $mcq_score, $total, $status, $remarks, $exam_type);

    if (!$insert->execute()) {
        die("Insert error: " . $insert->error);
    }

    $existing_id = $insert->insert_id;
    $insert->close();
}

// Save theory answers
if (!empty($theory_answers)) {
    foreach ($theory_answers as $qid => $answer) {
        $stmt = $conn->prepare("INSERT INTO exam_answers (student_id, exam_group_result_id, question_id, answer_text) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("iiis", $student_id, $existing_id, $qid, $answer);
        $stmt->execute();
    }
}

// Record exam attempt
$stmt = $conn->prepare("INSERT INTO student_exam_attempts (exam_id, qtype, student_id, started_at, submitted_at, score, remarks) VALUES (?, ?, ?, ?, ?, ?, ?)");
$score = ($has_mcq && !$has_theory) ? $mcq_score : null;
$stmt->bind_param("isissds", $exam_id, $Qtype, $student_id, $started_at, $submitted_at, $score, $remarks);
$stmt->execute();

// delete exam session

 $deleteQuery = "DELETE FROM student_exam_sessions WHERE exam_id = ? AND qtype = ?";
    $delstmt = $conn->prepare($deleteQuery);
    

    if ($delstmt) {
        $delstmt->bind_param("is", $exam_id, $Qtype); // "i" for integer examid, "s" for string subject (change if both are integers)
        $delstmt->execute();
    } 
    

// Cleanup
echo "<script>localStorage.removeItem('malpracticeCount_{$student_id}_{$exam_id}');</script>";

$_SESSION['last_mcq_score'] = $mcq_score;
$_SESSION['msg'] = ($has_mcq && !$has_theory) 
    ? "Exam submitted successfully. Your Objective score is {$mcq_score}."
    : "Exam submitted successfully" . ($has_theory ? " and will be reviewed." : ".");
$_SESSION['type'] = "success";

header("Location: dashboard.php");
exit;
?>