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

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

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

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

try {
    $dbh->beginTransaction();

    $selectStmt = $dbh->prepare("SELECT id FROM end_term_report WHERE Teacher = :teacher AND Admission_no = :adm AND classes = :class AND session = :session AND term = :term AND subject = :subject LIMIT 1");

    $updateStmt = $dbh->prepare("UPDATE end_term_report SET ca_test = :ca, exam_score = :exam, total = :total, comment = :comment, date = :date WHERE id = :id");
    $insertStmt = $dbh->prepare("INSERT INTO end_term_report (Teacher, Admission_no, classes, session, term, subject, ca_test, exam_score, total, comment, date) VALUES (:teacher, :adm, :class, :session, :term, :subject, :ca, :exam, :total, :comment, :date)");

    $now = date('Y-m-d H:i:s');
    $updated_map = [];

    foreach ($records as $rec) {
        $adm = $rec['admission_no'] ?? null;
        if (!$adm) continue;

        // normalize
        $ca = isset($rec['ca_test']) && $rec['ca_test'] !== null && $rec['ca_test'] !== '' ? (int)$rec['ca_test'] : null;
        $exam = isset($rec['exam_score']) && $rec['exam_score'] !== null && $rec['exam_score'] !== '' ? (int)$rec['exam_score'] : null;

        // Validate ranges server-side (example 0-100). Adjust as your policy.
        if ($ca !== null && ($ca < 0 || $ca > 100)) {
            throw new Exception("Invalid CA score for {$adm}");
        }
        if ($exam !== null && ($exam < 0 || $exam > 100)) {
            throw new Exception("Invalid Exam score for {$adm}");
        }

        $total = ($ca === null && $exam === null) ? null : (($ca ?? 0) + ($exam ?? 0));
        $comment = isset($rec['comment']) ? trim($rec['comment']) : null;

        $selectStmt->execute([
            ':teacher' => $teacher_id,
            ':adm' => $adm,
            ':class' => $class_id,
            ':session' => $session_id,
            ':term' => $term_id,
            ':subject' => $subject_id
        ]);
        $found = $selectStmt->fetch(PDO::FETCH_ASSOC);

        if ($found && !empty($found['id'])) {
            $updateStmt->execute([
                ':ca' => $ca,
                ':exam' => $exam,
                ':total' => $total,
                ':comment' => $comment,
                ':date' => $now,
                ':id' => $found['id']
            ]);
        } else {
            $insertStmt->execute([
                ':teacher' => $teacher_id,
                ':adm' => $adm,
                ':class' => $class_id,
                ':session' => $session_id,
                ':term' => $term_id,
                ':subject' => $subject_id,
                ':ca' => $ca,
                ':exam' => $exam,
                ':total' => $total,
                ':comment' => $comment,
                ':date' => $now
            ]);
        }
        $updated_map[$adm] = $now;
    }

    $dbh->commit();
    echo json_encode(['message' => 'Saved successfully', 'updated_map' => $updated_map]);

} catch (Exception $e) {
    if ($dbh->inTransaction()) $dbh->rollBack();
    http_response_code(500);
    echo json_encode(['message' => 'Save failed: ' . $e->getMessage()]);
}
