<?php
// Include the database configuration file
include("includes/db.php");

// Initialize error tracking
$errors = [];
$success = true;

// Check if marksData, examId, classId, and subjectId are set and not empty
if (isset($_POST['marksData']) && !empty($_POST['marksData']) &&
    isset($_POST['examId']) && !empty($_POST['examId']) &&
    isset($_POST['classId']) && !empty($_POST['classId']) &&
    isset($_POST['subjectId']) && !empty($_POST['subjectId'])) {
    
    // Retrieve marks data, exam ID, class ID, and subject ID from the POST request
    $marksData = $_POST['marksData'];
    $examId = $conn->real_escape_string($_POST['examId']);
    $classId = $conn->real_escape_string($_POST['classId']);
    $subjectId = $conn->real_escape_string($_POST['subjectId']);

    // Iterate through each student's marks data
    foreach ($marksData as $studentId => $marks) {
        // Sanitize input
        $studentId = $conn->real_escape_string($studentId);
        $marks = $conn->real_escape_string($marks);

        // Use INSERT ... ON DUPLICATE KEY UPDATE to insert or update marks
        $upsertQuery = "INSERT INTO marks (student_id, exam_type, class_id, subject_id, marks) 
                        VALUES ('$studentId', '$examId', '$classId', '$subjectId', '$marks')
                        ON DUPLICATE KEY UPDATE 
                        marks = '$marks'";
        $result = $conn->query($upsertQuery);

        // Check if the query was successful
        if (!$result) {
            // Store error message
            $errors[] = "Error updating/inserting marks for student ID: $studentId - " . $conn->error;
            $success = false;
        }
    }

    // Close the database connection
    $conn->close();
} else {
    // Missing required parameters
    $errors[] = "Missing required parameters (marksData, examId, classId, or subjectId).";
    $success = false;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Marks Update Status</title>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>

<?php if ($success): ?>
    <!-- SweetAlert for Success -->
    <script>
        Swal.fire({
            icon: 'success',
            title: 'Success',
            text: 'Marks updated/inserted successfully!'
        }).then(() => {
            window.location.href = 'edit_marksth.php'; // Redirect as needed
        });
    </script>
<?php else: ?>
    <!-- SweetAlert for Error -->
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Error',
            html: '<?php echo implode("<br>", $errors); ?>'
        }).then(() => {
            window.location.href = 'edit_marksth.php'; // Redirect as needed
        });
    </script>
<?php endif; ?>

</body>
</html>
