<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["submit"])) {
    // Include the database configuration file
    include("includes/db.php");

    // Collect data from the form
    $examtypeId = $conn->real_escape_string($_POST["exam_id1"]);
    $classId = $conn->real_escape_string($_POST["class_id"]);
    $subjectId = $conn->real_escape_string($_POST["subject_id"]);
    $marks = $_POST["marks"];

    // Iterate through the marks array and insert marks into the database
    foreach ($marks as $studentId => $mark) {
        // Validate and sanitize data if necessary
        $studentId = $conn->real_escape_string($studentId);
        $mark = $conn->real_escape_string($mark);

        // SQL query to insert marks into the 'marks' table
        $query = "INSERT INTO marks (class_id, subject_id, exam_type, student_id, marks)
                        VALUES ('$classId', '$subjectId', $examtypeId, '$studentId', '$mark')";

        // Execute the query
        if ($conn->query($query) !== TRUE) {
            // Handle error if insertion fails
            echo "Error: " . $query . "<br>" . $conn->error;
        }
    }

    // Close the database connection
    $conn->close();
    header("Location: thank_you.php");
    // // Set success or error message for alert
    // $alertMessage = (isset($_GET['success']) && $_GET['success'] == 1) ? 'Data inserted successfully!' : 'Error inserting data!';

    // // Display alert using JavaScript
    // echo "<script>
    //         window.onload = function() {
    //             alert('$alertMessage');
    //         };
    //       </script>";

    // // Redirect back to the marks entry page

    exit();
} else {
    // Redirect back to the marks entry page with error message if form was not submitted properly
    header("Location: marksentry.php?error=1");
    exit();
}
?>
