<?php
// process_attendance.php

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include session validation and database connection
include('session_validator.php');

// Include the PDO database connection
include('includes/db_pdo.php');

// Check if form data is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Check if 'exam_type' and 'attendance' data are set and not empty
    if (isset($_POST['exam_type']) && !empty($_POST['exam_type']) && isset($_POST['attendance']) && !empty($_POST['attendance'])) {

        $examType = $_POST['exam_type'];
        $attendance = $_POST['attendance'];

        // Validate and process attendance data for each student
        try {
            // Begin a transaction to ensure data integrity
            $conn->beginTransaction();

            // Prepare the statement to check if the attendance already exists
            $checkAttendanceQuery = "SELECT id FROM attendance WHERE std_id = :student_id AND exam_type = :exam_type AND atten_day = :atten_day LIMIT 1";
            $stmtCheck = $conn->prepare($checkAttendanceQuery);

            // Prepare the statement to insert attendance records
            $attendanceInsertQuery = "INSERT INTO attendance (std_id, exam_type, atten_day) VALUES (:student_id, :exam_type, :atten_day)";
            $stmtInsert = $conn->prepare($attendanceInsertQuery);

            // Prepare the statement to update attendance records
            $attendanceUpdateQuery = "UPDATE attendance SET atten_day = :atten_day WHERE std_id = :student_id AND exam_type = :exam_type";
            $stmtUpdate = $conn->prepare($attendanceUpdateQuery);

            // Iterate through each student's attendance data
            foreach ($attendance as $studentId => $data) {
                if (!isset($data['atten_day']) || empty($data['atten_day'])) {
                    // If attendance day is not provided, skip this student
                    continue;
                }

                // Get the student's attendance day
                $attenDay = $data['atten_day'];

                // First, check if the attendance already exists
                $stmtCheck->bindValue(':student_id', $studentId, PDO::PARAM_INT);
                $stmtCheck->bindValue(':exam_type', $examType, PDO::PARAM_INT);
                $stmtCheck->bindValue(':atten_day', $attenDay, PDO::PARAM_INT);
                $stmtCheck->execute();

                if ($stmtCheck->rowCount() > 0) {
                    // If a record exists, update the attendance
                    $stmtUpdate->bindValue(':student_id', $studentId, PDO::PARAM_INT);
                    $stmtUpdate->bindValue(':exam_type', $examType, PDO::PARAM_INT);
                    $stmtUpdate->bindValue(':atten_day', $attenDay, PDO::PARAM_INT);
                    $stmtUpdate->execute();
                } else {
                    // If no record exists, insert a new attendance record
                    $stmtInsert->bindValue(':student_id', $studentId, PDO::PARAM_INT);
                    $stmtInsert->bindValue(':exam_type', $examType, PDO::PARAM_INT);
                    $stmtInsert->bindValue(':atten_day', $attenDay, PDO::PARAM_INT);
                    $stmtInsert->execute();
                }
            }

            // Commit the transaction
            $conn->commit();

            // Return success response
            echo json_encode(["status" => "success", "message" => "Attendance successfully recorded."]);

        } catch (Exception $e) {
            // Rollback the transaction if any error occurs
            $conn->rollBack();

            // Return error response
            echo json_encode(["status" => "error", "message" => "An error occurred while saving attendance. Please try again."]);
        }
    } else {
        // If 'exam_type' or 'attendance' data is missing or empty
        echo json_encode(["status" => "error", "message" => "Required fields are missing."]);
    }
} else {
    // If not a POST request, return an error message
    echo json_encode(["status" => "error", "message" => "Invalid request method."]);
}

// Close the database connection
$conn = null;
?>
