<?php
session_start();
require_once 'config.php'; // Ensure this path is correct

// Define role constants
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 1);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 2);
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 4);
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 5);
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 6);

header('Content-Type: application/json');

$response = ['success' => false, 'message' => 'An unknown error occurred.'];

// Ensure user is logged in and is a teacher
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== ROLE_TEACHER || !isset($_SESSION["school_id"])) {
    $response['message'] = 'Unauthorized access.';
    echo json_encode($response);
    exit;
}

$current_user_school_id = $_SESSION["school_id"];
$teacher_user_id = $_SESSION["id"]; // The logged-in teacher's user_id

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $exam_id = filter_input(INPUT_POST, 'exam_id', FILTER_VALIDATE_INT);
    $subject_id = filter_input(INPUT_POST, 'subject_id', FILTER_VALIDATE_INT);
    $stream_id_param = filter_input(INPUT_POST, 'class_id', FILTER_VALIDATE_INT); // This is the stream_id
    $academic_year = filter_input(INPUT_POST, 'academic_year', FILTER_SANITIZE_STRING);
    $term = filter_input(INPUT_POST, 'term', FILTER_SANITIZE_STRING);
    $marks = $_POST['marks'] ?? []; // Array of student_user_id (INT) => mark

    // Basic validation
    if (!$exam_id || !$subject_id || !$stream_id_param || empty($academic_year) || empty($term) || !is_array($marks)) {
        $response['message'] = 'Missing or invalid required data.';
        echo json_encode($response);
        exit;
    }

    if (isset($conn) && $conn instanceof mysqli) {
        // --- NEW: Check Exam Status ---
        $sql_check_exam_status = "SELECT status FROM exams WHERE exam_id = ? AND school_id = ?";
        if ($stmt_check_status = $conn->prepare($sql_check_exam_status)) {
            $stmt_check_status->bind_param("ii", $exam_id, $current_user_school_id);
            $stmt_check_status->execute();
            $stmt_check_status->bind_result($exam_status);
            $stmt_check_status->fetch();
            $stmt_check_status->close();

            if ($exam_status === 'Published') {
                $response['message'] = 'Cannot enter marks: This exam has been published.';
                echo json_encode($response);
                exit;
            }
        } else {
            $response['message'] = 'Database error checking exam status.';
            echo json_encode($response);
            exit;
        }
        // --- END NEW CHECK ---

        $conn->begin_transaction(); // Start transaction for atomicity
        try {
            $success_count = 0;
            $error_count = 0;

            foreach ($marks as $student_user_id => $mark) {
                $student_user_id = (int)$student_user_id;

                $mark = filter_var($mark, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 100]]);

                if ($mark === false) { // Mark is not a valid integer or out of range
                    $error_count++;
                    continue; // Skip this mark and continue with others
                }

                // Check if the student (by user.id) belongs to this stream and school
                $sql_validate_student = "
                    SELECT u.id
                    FROM users u
                    JOIN students s ON u.id = s.user_id
                    JOIN streams stm ON s.stream = stm.stream_name
                    WHERE u.id = ?
                    AND stm.stream_id = ?
                    AND u.school_id = ?
                    AND u.role = ?
                ";
                if ($stmt_validate_student = $conn->prepare($sql_validate_student)) {
                    $student_role_code = ROLE_STUDENT;
                    $stmt_validate_student->bind_param("iiii", $student_user_id, $stream_id_param, $current_user_school_id, $student_role_code);
                    $stmt_validate_student->execute();
                    $stmt_validate_student->store_result();
                    if ($stmt_validate_student->num_rows === 0) {
                        $error_count++;
                        $stmt_validate_student->close();
                        continue; // Skip this student
                    }
                    $stmt_validate_student->close();
                } else {
                    $error_count++;
                    continue; // Skip this student
                }

                // Insert or Update the mark
                $sql_upsert_mark = "
                    INSERT INTO marks (exam_id, subject_id, student_id, stream_id, teacher_user_id, mark, academic_year, term, school_id, date_recorded)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
                    ON DUPLICATE KEY UPDATE mark = VALUES(mark), date_recorded = NOW()
                ";
                if ($stmt_upsert = $conn->prepare($sql_upsert_mark)) {
                    $stmt_upsert->bind_param("iiiiisssi", $exam_id, $subject_id, $student_user_id, $stream_id_param, $teacher_user_id, $mark, $academic_year, $term, $current_user_school_id);
                    if ($stmt_upsert->execute()) {
                        $success_count++;
                    } else {
                        $error_count++;
                    }
                    $stmt_upsert->close();
                } else {
                    $error_count++;
                }
            }

            if ($error_count === 0) {
                $conn->commit();
                $response['success'] = true;
                $response['message'] = "Marks saved successfully for {$success_count} students.";
            } else {
                $conn->rollback();
                $response['message'] = "Completed with errors. Successfully saved: {$success_count}, Failed: {$error_count}.";
                $response['success'] = false;
            }

        } catch (Exception $e) {
            $conn->rollback();
            $response['message'] = "Transaction failed: " . $e->getMessage();
            $response['success'] = false;
        } finally {
            $conn->close();
        }
    } else {
        $response['message'] = 'Database connection error.';
    }
} else {
    $response['message'] = 'Invalid request method.';
}

echo json_encode($response);
?>