<?php
// ajax/load_students.php
header('Content-Type: application/json');
require_once '../config.php';
session_start();

// Accept JSON body
$input = json_decode(file_get_contents('php://input'), true);

$session_id = $input['session'] ?? null;
$term_id = $input['term'] ?? null;
$class_id = $input['class_id'] ?? null;
$subject_id = $input['subject'] ?? null;
$teacher_id = $input['teacher_id'] ?? null;

if (!$session_id || !$term_id || !$class_id || !$subject_id || !$teacher_id) {
    http_response_code(400);
    echo json_encode(['message'=>'Missing parameters']);
    exit;
}

try {
    // get students in class
    $stmt = $dbh->prepare("SELECT id, class_id, Admission_num, name FROM students WHERE class_id = :class_id AND status = 'active' ORDER BY name");
    $stmt->execute([':class_id' => $class_id]);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // load existing mid_term_test for this teacher + selection
    $stmt2 = $dbh->prepare("SELECT Admission_no, wk_test, mid_test, total, comment, date FROM mid_term_test
        WHERE classes = :class_id AND session = :session_id AND term = :term_id AND Subject = :subject_id AND Teacher = :teacher_id");
    $stmt2->execute([
        ':class_id' => $class_id,
        ':session_id' => $session_id,
        ':term_id' => $term_id,
        ':subject_id' => $subject_id,
        ':teacher_id' => $teacher_id
    ]);
    $existingRows = $stmt2->fetchAll(PDO::FETCH_ASSOC);
    $existingMap = [];
    foreach ($existingRows as $r) {
        $existingMap[$r['Admission_no']] = $r; // keyed by Admission_no
    }

    // also fetch meta names
    $sessionName = $dbh->prepare("SELECT session_year FROM sessions WHERE id = :id LIMIT 1");
    $sessionName->execute([':id'=>$session_id]); $sN = $sessionName->fetchColumn();

    $termName = $dbh->prepare("SELECT term_name FROM terms WHERE id = :id LIMIT 1");
    $termName->execute([':id'=>$term_id]); $tN = $termName->fetchColumn();

    $className = $dbh->prepare("SELECT name FROM classes WHERE id = :id LIMIT 1");
    $className->execute([':id'=>$class_id]); $cN = $className->fetchColumn();

    $subjectName = $dbh->prepare("SELECT name FROM Subjects WHERE id = :id LIMIT 1");
    $subjectName->execute([':id'=>$subject_id]); $suN = $subjectName->fetchColumn();

    echo json_encode([
        'students' => $students,
        'existing' => $existingMap,
        'session_year' => $sN,
        'term_name' => $tN,
        'class_name' => $cN,
        'subject_name' => $suN,
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['message' => 'Server error: ' . $e->getMessage()]);
}
