<?php

session_start();

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

ob_start();

include($_SERVER['DOCUMENT_ROOT'] . "/SEAT/config/db.php");

header('Content-Type: application/json');

/* =========================================================
CLEAR OUTPUT BUFFER
========================================================= */

while(ob_get_level()){

    ob_end_clean();
}

/* =========================================================
AUTH
========================================================= */

if(
    !isset($_SESSION['role']) ||
    $_SESSION['role'] !== "organizer"
){

    echo json_encode([
        "success" => false,
        "message" => "No access"
    ]);

    exit;
}

/* =========================================================
VALIDATE REQUEST
========================================================= */

if(
    $_SERVER['REQUEST_METHOD'] !== "POST"
){

    echo json_encode([
        "success" => false,
        "message" => "Invalid request method"
    ]);

    exit;
}

if(
    !isset($_POST['attendance']) ||
    !is_array($_POST['attendance'])
){

    echo json_encode([
        "success" => false,
        "message" => "Attendance data missing"
    ]);

    exit;
}

/* =========================================================
START TRANSACTION
========================================================= */

mysqli_begin_transaction($conn);

try{

    $updated = 0;

    foreach($_POST['attendance'] as $registration_id => $status){

        /* =========================================================
        SANITIZE
        ========================================================= */

        $registration_id =
        intval($registration_id);

        $status =
        strtolower(
            trim($status)
        );

        if($registration_id <= 0){
            continue;
        }

        if(
            $status !== "present" &&
            $status !== "absent"
        ){
            continue;
        }

        /* =========================================================
        GET EVENT ID
        ========================================================= */

        $eventQuery = mysqli_query($conn,"
        SELECT event_id
        FROM event_registrations
        WHERE id = $registration_id
        LIMIT 1
        ");

        if(!$eventQuery){

            throw new Exception(
                mysqli_error($conn)
            );
        }

        $eventData =
        mysqli_fetch_assoc($eventQuery);

        if(!$eventData){
            continue;
        }

        $eventID =
        intval($eventData['event_id']);

        /* =========================================================
        PRESENT
        ========================================================= */

        if($status === "present"){

            /* DELETE DUPLICATES FIRST */

            $cleanup = mysqli_query($conn,"
            DELETE a1 FROM attendances a1
            INNER JOIN attendances a2
            WHERE
                a1.id > a2.id
                AND a1.registration_id = a2.registration_id
                AND a1.registration_id = $registration_id
            ");

            if(!$cleanup){

                throw new Exception(
                    mysqli_error($conn)
                );
            }

            /* CHECK EXISTING */

            $checkQuery = mysqli_query($conn,"
            SELECT id
            FROM attendances
            WHERE registration_id = $registration_id
            LIMIT 1
            ");

            if(!$checkQuery){

                throw new Exception(
                    mysqli_error($conn)
                );
            }

            /* INSERT ONLY IF NOT EXISTS */

            if(mysqli_num_rows($checkQuery) == 0){

                $insertQuery = mysqli_query($conn,"
                INSERT INTO attendances (
                    registration_id,
                    event_id,
                    checked_in_at
                )
                VALUES (
                    $registration_id,
                    $eventID,
                    NOW()
                )
                ");

                if(!$insertQuery){

                    throw new Exception(
                        mysqli_error($conn)
                    );
                }
            }

            $updated++;
        }

        /* =========================================================
        ABSENT
        ========================================================= */

        if($status === "absent"){

            $deleteQuery = mysqli_query($conn,"
            DELETE FROM attendances
            WHERE registration_id = $registration_id
            ");

            if(!$deleteQuery){

                throw new Exception(
                    mysqli_error($conn)
                );
            }

            $updated++;
        }
    }

    /* =========================================================
    COMMIT
    ========================================================= */

    mysqli_commit($conn);

    echo json_encode([
        "success" => true,
        "message" => "Attendance updated successfully",
        "updated" => $updated
    ]);

    exit;

}catch(Exception $e){

    mysqli_rollback($conn);

    echo json_encode([
        "success" => false,
        "message" => $e->getMessage()
    ]);

    exit;
}
?>

