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

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

// Check if user is logged in and is a teacher
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 2 || !isset($_SESSION["school_id"])) {
    echo json_encode(["success" => false, "message" => "Unauthorized access."]);
    exit;
}

$user_id = $_SESSION["id"];
$current_user_school_id = $_SESSION["school_id"];

// Get parameters from the AJAX request
$exam_id = filter_input(INPUT_POST, 'exam_id', FILTER_VALIDATE_INT);
$subject_id = filter_input(INPUT_POST, 'subject_id', FILTER_VALIDATE_INT);
$stream_id = filter_input(INPUT_POST, 'stream_id', FILTER_VALIDATE_INT);
$academic_year = filter_input(INPUT_POST, 'academic_year', FILTER_SANITIZE_STRING);
$term = filter_input(INPUT_POST, 'term', FILTER_SANITIZE_STRING);

// Basic validation for required parameters
if (!$exam_id || !$subject_id || !$stream_id || !$academic_year || !$term) {
    echo json_encode(["success" => false, "message" => "Missing required parameters."]);
    exit;
}

$students_marks = [];

if (isset($conn) && $conn instanceof mysqli) {
    $sql = "
        SELECT
            u.id AS student_id,
            u.username AS student_name,
            s.ADM AS student_adm,  /* Added ADM here */
            m.mark
        FROM students s
        JOIN users u ON s.user_id = u.id
        JOIN streams stm ON s.stream = stm.stream_name
        LEFT JOIN marks m ON m.student_id = u.id
            AND m.exam_id = ?
            AND m.subject_id = ?
            AND m.academic_year = ?
            AND m.term = ?
        WHERE stm.stream_id = ?
            AND s.school_id = ?
        ORDER BY u.username;
    ";

    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("iisssi", $exam_id, $subject_id, $academic_year, $term, $stream_id, $current_user_school_id);
        if ($stmt->execute()) {
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $students_marks[] = $row;
            }
            echo json_encode(["success" => true, "students" => $students_marks]);
        } else {
            echo json_encode(["success" => false, "message" => "Database query failed."]);
        }
        $stmt->close();
    } else {
        echo json_encode(["success" => false, "message" => "Database preparation failed."]);
    }
    $conn->close();
} else {
    echo json_encode(["success" => false, "message" => "Database connection error."]);
}
?>