<?php
// process_attendance.php

// Include the database connection file
include("includes/db.php");

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    // Validate and sanitize input
    $examType = mysqli_real_escape_string($conn, $_POST['exam_type']);
    $classId = mysqli_real_escape_string($conn, $_POST['class_id']);
    $attendanceData = $_POST['attendance'];

    // Check if attendance data is not empty
    if (!empty($attendanceData)) {
        // Start a transaction to ensure data consistency
        mysqli_begin_transaction($conn);

        try {
            // Insert or update attendance data in the 'attendance' table
            $insertAttendanceQuery = "INSERT INTO attendance (std_id, exam_type, atten_day) VALUES (?, ?, ?)
                                      ON DUPLICATE KEY UPDATE atten_day = VALUES(atten_day)";
            $stmt = $conn->prepare($insertAttendanceQuery);

            foreach ($attendanceData as $studentId => $attendanceDetails) {
                $attenDay = $attendanceDetails['atten_day'];
                $stmt->bind_param('iss', $studentId, $examType, $attenDay);
                $stmt->execute();
            }

            // Commit the transaction
            mysqli_commit($conn);

            // Display JavaScript alert upon successful insertion
            echo '<script>alert("Attendance has been successfully recorded!");</script>';

            // Redirect to attendance.php upon successful insertion
            header("Location: attendance.php");
            exit(); // Make sure to stop the script execution after redirection
        } catch (Exception $e) {
            // Rollback the transaction on error
            mysqli_rollback($conn);
            echo "Error recording attendance: " . $e->getMessage();
        } finally {
            // Close the prepared statement
            $stmt->close();
        }
    } else {
        echo "No attendance data received.";
    }
} else {
    echo "Invalid request!";
}

// Close the database connection
mysqli_close($conn);
?>
