<?php
include('session_validator.php');
include('includes/db.php');

// Ensure response is in JSON format
header('Content-Type: application/json');

// Check if symbol data is provided
if (isset($_POST['symbolData'])) {
    $symbolData = $_POST['symbolData'];

    // Prepare the statement with ON DUPLICATE KEY UPDATE to replace symbol numbers
    $stmt = $conn->prepare("
        INSERT INTO symbolno_data (student_id, class_id, exam_id, symbol_no) 
        VALUES (?, ?, ?, ?) 
        ON DUPLICATE KEY UPDATE symbol_no = VALUES(symbol_no)
    ");

    foreach ($symbolData as $data) {
        $studentId = $data['studentId'];
        $classId = $data['classId'];
        $examId = $data['examId'];
        $symbolNumber = $data['symbolNumber'];

        // Bind and execute the query
        $stmt->bind_param("iiis", $studentId, $classId, $examId, $symbolNumber);
        if (!$stmt->execute()) {
            echo json_encode(["success" => false, "error" => "Failed to update symbol number for student ID $studentId"]);
            exit;
        }
    }

    // Return success if all insertions/updates are done
    echo json_encode(["success" => true]);
} else {
    echo json_encode(["success" => false, "error" => "No symbol data received"]);
}
?>
