<?php
session_start();
require_once 'config.php'; // Adjust path as needed

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['exam_id']) && isset($_POST['class_id']) && isset($_POST['subject_id']) && isset($_POST['marks'])) {
    $exam_id = intval($_POST['exam_id']);
    $class_id = intval($_POST['class_id']);
    $subject_id = intval($_POST['subject_id']);
    $paper_id = isset($_POST['paper_id']) ? intval($_POST['paper_id']) : null; // Can be null
    $marks_data = $_POST['marks']; // Array of student_id => score
    $recorded_by_teacher_id = $_SESSION['id'] ?? null; // Assuming admin can record marks, or change to teacher_id if applicable

    if (!isset($conn) || !$conn instanceof mysqli) {
        header("Location: exam_management.php?message=" . urlencode("Error: Database connection not established."));
        exit;
    }

    $conn->begin_transaction();
    try {
        foreach ($marks_data as $student_id => $score) {
            $student_id = intval($student_id);
            $score = floatval($score);

            // Check if mark already exists for this exam, student, subject, and paper
            $sql_check = "SELECT id FROM marks WHERE exam_id = ? AND student_id = ? AND subject_id = ? AND (paper_id = ? OR (paper_id IS NULL AND ? IS NULL))";
            if ($stmt_check = $conn->prepare($sql_check)) {
                $stmt_check->bind_param("iiiis", $exam_id, $student_id, $subject_id, $paper_id, $paper_id);
                $stmt_check->execute();
                $stmt_check->store_result();

                if ($stmt_check->num_rows > 0) {
                    // Update existing mark
                    $sql_insert_update = "UPDATE marks SET score = ?, recorded_by_teacher_id = ?, recorded_at = NOW() WHERE exam_id = ? AND student_id = ? AND subject_id = ? AND (paper_id = ? OR (paper_id IS NULL AND ? IS NULL))";
                } else {
                    // Insert new mark
                    $sql_insert_update = "INSERT INTO marks (score, recorded_by_teacher_id, exam_id, student_id, subject_id, paper_id, recorded_at) VALUES (?, ?, ?, ?, ?, ?, NOW())";
                }
                $stmt_check->close();

                if ($stmt_insert_update = $conn->prepare($sql_insert_update)) {
                    if ($stmt_check->num_rows > 0) {
                         // For UPDATE
                        $stmt_insert_update->bind_param("diiisis", $score, $recorded_by_teacher_id, $exam_id, $student_id, $subject_id, $paper_id, $paper_id);
                    } else {
                        // For INSERT
                        $stmt_insert_update->bind_param("diiiis", $score, $recorded_by_teacher_id, $exam_id, $student_id, $subject_id, $paper_id);
                    }
                    $stmt_insert_update->execute();
                    $stmt_insert_update->close();
                } else {
                    throw new Exception("Failed to prepare mark insert/update statement: " . $conn->error);
                }
            } else {
                throw new Exception("Failed to prepare mark check statement: " . $conn->error);
            }
        }
        $conn->commit();
        header("Location: exam_management.php?message=" . urlencode("Marks saved successfully!"));
        exit;
    } catch (Exception $e) {
        $conn->rollback();
        header("Location: exam_management.php?message=" . urlencode("Error saving marks: " . $e->getMessage()));
        exit;
    } finally {
        $conn->close();
    }
} else {
    header("Location: exam_management.php?message=" . urlencode("Invalid request for saving marks."));
    exit;
}
?>