<?php
// ajax/save_midterm.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();

    // We'll prepare statements for select, insert and update.
    $selectStmt = $dbh->prepare("SELECT id FROM mid_term_test 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 mid_term_test SET wk_test = :wk, mid_test = :mid, total = :total, comment = :comment, date = :date WHERE id = :id");
    $insertStmt = $dbh->prepare("INSERT INTO mid_term_test (Teacher, Admission_no, classes, session, term, subject, wk_test, mid_test, total, comment, date) VALUES (:teacher, :adm, :class, :session, :term, :subject, :wk, :mid, :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;

        // normalise numbers or null
        $wk = isset($rec['wk_test']) && $rec['wk_test'] !== null && $rec['wk_test'] !== '' ? (int)$rec['wk_test'] : null;
        $mid = isset($rec['mid_test']) && $rec['mid_test'] !== null && $rec['mid_test'] !== '' ? (int)$rec['mid_test'] : null;
        $total = ($wk === null && $mid === null) ? null : (($wk ?? 0) + ($mid ?? 0));
        $comment = isset($rec['comment']) ? trim($rec['comment']) : null;

        // check existing
        $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'])) {
            // update
            $updateStmt->execute([
                ':wk' => $wk,
                ':mid' => $mid,
                ':total' => $total,
                ':comment' => $comment,
                ':date' => $now,
                ':id' => $found['id'],
            ]);
        } else {
            // insert
            $insertStmt->execute([
                ':teacher' => $teacher_id,
                ':adm' => $adm,
                ':class' => $class_id,
                ':session' => $session_id,
                ':term' => $term_id,
                ':subject' => $subject_id,
                ':wk' => $wk,
                ':mid' => $mid,
                ':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()]);
}
