<?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"];

    // Initialize an array to store duplicate entries
    $duplicates = array();

    // Iterate through the marks array and check for duplicate entries
    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 check for duplicate entry
        $checkQuery = "SELECT * FROM int_marks WHERE class_id = '$classId' AND subject_id = '$subjectId' AND exam_type = '$examtypeId' AND student_id = '$studentId'";

        // Execute the query
        $result = $conn->query($checkQuery);

        // Check if any rows are returned (duplicate entry exists)
        if ($result->num_rows > 0) {
            // Add student ID to duplicates array
            $duplicates[] = $studentId;
        }
    }

    // If duplicates array is not empty, display error message and exit
    if (!empty($duplicates)) {
        $duplicateIds = implode(', ', $duplicates);
        echo "Error: Duplicate entry found for student IDs: $duplicateIds";
        exit();
    }

    // If no duplicates found, proceed with inserting 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 int_marks (class_id, subject_id, exam_type, student_id, internal_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();

    // Set success message for alert
    $alertMessage = "Data inserted successfully!";

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

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

?>
