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

    // Validate and sanitize data
    $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"];

    // Prepare SQL statement with placeholders
    $query = "INSERT INTO marks (class_id, subject_id, exam_type, student_id, marks) VALUES (?, ?, ?, ?, ?)";

    // Prepare the statement
    $stmt = $conn->prepare($query);

    // Check if the statement is prepared successfully
    if ($stmt) {
        // Bind parameters
        $stmt->bind_param("ssiss", $classId, $subjectId, $examtypeId, $studentId, $mark);

        // 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);

            // Execute the statement
            $stmt->execute();
        }

        // Close the statement
        $stmt->close();

        // Close the database connection
        $conn->close();

        // Set success message for alert
        $alertMessage = 'Data inserted successfully!';
    } else {
        // Log the error instead of displaying it
        error_log("Error preparing SQL statement: " . $conn->error);

        // Set error message for alert
        $alertMessage = 'Error inserting data!';
    }
} else {
    // Set error message for alert
    $alertMessage = 'Error inserting data!';
}

// Display alert using JavaScript
echo "<script>
        window.onload = function() {
            alert('$alertMessage');
            window.location.href = 'enter_marks.php'; // Redirect regardless of success or error
        };
      </script>";
?>
