<?php
// 1. Remove ANY print_r, echo, or var_dump before this
ob_start(); 
header('Content-Type: application/json');

require_once("../../includes/config.php");
require_once("../../includes/auth_check.php");

try {
    if (!$pdo->inTransaction()) $pdo->beginTransaction();

    // Capture IDs from POST (stream_id removed)
    $class_id   = (int)$_POST['class_id'];
    $medium_id  = (int)($_POST['medium_id'] ?? 0); 
    $subject_id = (int)$_POST['subject_id'];
    $term_id    = (int)$_POST['term_id'];
    $marks_data = $_POST['marks'] ?? []; 
    
    $year_id = APP_YEAR_ID; 
    $admin_id = $_SESSION['user_id']; 

    // Updated SQL: stream_id removed from COLUMNS, VALUES, and UPDATE logic
    $sql = "INSERT INTO marks_entry 
            (student_id, subject_id, medium_id, exam_term_id, class_id, academic_year_id, theory_marks, practical_marks, added_by) 
            VALUES (:sid, :sub, :med, :term, :class, :year, :theory, :prac, :uid)
            ON DUPLICATE KEY UPDATE 
            theory_marks = VALUES(theory_marks), 
            practical_marks = VALUES(practical_marks),
            added_by = VALUES(added_by),
            medium_id = VALUES(medium_id)";

    $stmt = $pdo->prepare($sql);

    foreach ($marks_data as $student_id => $m) {
        // Handle empty inputs as 0.00
        $theory = ($m['theory'] === '') ? 0.00 : floatval($m['theory']);
        $prac   = ($m['practical'] === '') ? 0.00 : floatval($m['practical']);

        $stmt->execute([
            ':sid'    => $student_id,
            ':sub'    => $subject_id,
            ':med'    => $medium_id,
            ':term'   => $term_id,
            ':class'  => $class_id,
            ':year'   => $year_id,
            ':theory' => $theory,
            ':prac'   => $prac,
            ':uid'    => $admin_id
        ]);
    }

    $pdo->commit();
    
    ob_clean(); 
    echo json_encode(['status' => 'success', 'message' => 'Marks saved successfully!']);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    ob_clean();
    echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
exit;?>