<?php

/* ================= REQUIRED VARIABLES ================= */

if(!isset($conn)){
    die("Database connection missing");
}

if(!isset($event_id)){
    die("Event ID missing");
}

if(!isset($tab)){
    $tab = "participants";
}

if(!isset($event)){
    die("Event data missing");
}

/* ================= AUTO REFUND TAB ================= */

if(
    $event['status']=="cancelled" &&
    $event['fee_type']=="Paid"
){
    $tab = "refund";
}

/* ================= DEFAULT ================= */

$query = false;
$title = "";
$sub = "";
$icon = "👤";
$showNotice = false;

/* ================= PARTICIPANT LIST ================= */

if($tab=="participants"){

    $query = mysqli_query($conn,"
    SELECT
        r.id AS registration_id,
        p.full_name,
        p.matric_no,
        p.staff_no,
        p.faculty,
        u.email,
        r.payment_status,
        r.registered_at,
        a.id AS attendance_id

    FROM event_registrations r

    INNER JOIN participants p
    ON p.id = r.participant_id

    INNER JOIN users u
    ON u.id = p.user_id

    LEFT JOIN attendances a
    ON a.registration_id = r.id

    WHERE r.event_id='$event_id'

    ORDER BY r.registered_at DESC
    ");

    $title = "Participant List";

    $icon = "👤";
}

/* ================= ATTENDANCE LIST ================= */

elseif($tab=="attendance"){

    $query = mysqli_query($conn,"
    SELECT
        p.full_name,
        p.matric_no,
        p.staff_no,
        a.checked_in_at

    FROM attendances a

    INNER JOIN event_registrations r
    ON r.id = a.registration_id

    INNER JOIN participants p
    ON p.id = r.participant_id

    WHERE r.event_id='$event_id'

    ORDER BY a.checked_in_at DESC
    ");

    $title = "Attendance List";

    $icon = "✓";
}

/* ================= REFUND LIST ================= */

elseif($tab=="refund"){

    $query = mysqli_query($conn,"
    SELECT
        p.full_name,
        p.matric_no,
        p.staff_no,
        p.phone,
        u.email

    FROM event_registrations r

    INNER JOIN participants p
    ON p.id = r.participant_id

    INNER JOIN users u
    ON u.id = p.user_id

    WHERE r.event_id='$event_id'
    AND r.payment_status='Paid'

    ORDER BY p.full_name ASC
    ");

    $title = "Refund List";

    $icon = "R";

    $showNotice = true;
}

if($query === false){

    echo mysqli_error($conn);

    return;
}

$count = mysqli_num_rows($query);

$sub = $count . " records found";

?>

<link rel="stylesheet" href="/SEAT/assets/css/organizer/list.css">
<div class="listCard">

    <!-- HEADER -->

    <div class="listHeader">

        <div>

            <h3>
                <?= $title ?>
            </h3>

            <div class="sub">
                <?= $sub ?>
            </div>

        </div>

        <!-- RIGHT ACTIONS -->

        <div class="listHeaderActions">

            <!-- EXPORT -->

            <div class="tableExportDropdown">

                <button
                class="tableExportBtn"
                onclick="toggleTableExport(event)">

                    Export Report ▾

                </button>

                <div
                id="tableExportMenu"
                class="tableExportMenu">

                    <a
                    href="attendance_report.php?event_id=<?= $event_id ?>&type=pdf&tab=<?= $tab ?>"
                    target="_blank">

                        Download PDF

                    </a>

                    <a
                    href="attendance_report.php?event_id=<?= $event_id ?>&type=csv&tab=<?= $tab ?>">

                        Download CSV

                    </a>

                </div>

            </div>

            <!-- EDIT ATTENDANCE -->

            <?php if($tab=="participants"): ?>

            <button
            class="editAttendanceBtn"
            onclick="openAttendanceModal()">

                Edit Attendance

            </button>

            <?php endif; ?>

        </div>

    </div>

    <!-- REFUND NOTICE -->

    <?php if($showNotice): ?>

    <div class="refundNotice">

        All participants listed below are eligible for refund
        because this event has been cancelled.

    </div>

    <?php endif; ?>

    <!-- MODAL -->

    <?php if($tab=="participants"): ?>

    <div
    id="attendanceModal"
    class="attendanceModal">

        <div class="attendanceModalContent">

            <div class="attendanceModalHeader">

                <h3>
                    Edit Attendance
                </h3>

                <button
                type="button"
                class="closeModalBtn"
                onclick="closeAttendanceModal()">

                    ×

                </button>

            </div>

            <form id="attendanceForm">

                <div class="attendanceModalBody">

                    <?php
                    mysqli_data_seek($query,0);
                    ?>

                    <?php while($bulk=mysqli_fetch_assoc($query)): ?>

                    <?php

                    $bulkPresent =
                    !empty($bulk['attendance_id']);

                    ?>

                    <div class="attendanceEditRow">

                        <div>

                            <div class="editName">

                                <?= htmlspecialchars(
                                    $bulk['full_name']
                                ) ?>

                            </div>

                            <div class="editMatric">

                                <?= htmlspecialchars(
                                    $bulk['matric_no']
                                    ?: $bulk['staff_no']
                                ) ?>

                            </div>

                        </div>

                        <select
                        name="attendance[<?= $bulk['registration_id'] ?>]"
                        class="attendanceSelect">

                            <option
                            value="present"
                            <?= $bulkPresent ? 'selected' : '' ?>>

                                Present

                            </option>

                            <option
                            value="absent"
                            <?= !$bulkPresent ? 'selected' : '' ?>>

                                Absent

                            </option>

                        </select>

                    </div>

                    <?php endwhile; ?>

                </div>

                <div class="attendanceModalFooter">

                    <button
                    type="button"
                    class="cancelAttendanceBtn"
                    onclick="closeAttendanceModal()">

                        Cancel

                    </button>

                    <button
                    type="submit"
                    class="saveAttendanceBtn">

                        Save Attendance

                    </button>

                </div>

            </form>

        </div>

    </div>

    <?php endif; ?>

    <!-- RESET POINTER -->

    <?php
    mysqli_data_seek($query,0);
    ?>

    <!-- EMPTY -->

    <?php if($count==0): ?>

    <div class="emptyState">

        No data available

    </div>

    <?php endif; ?>

    <!-- LOOP -->

    <?php while($r=mysqli_fetch_assoc($query)): ?>

    <div class="participantRow">

        <!-- LEFT -->

        <div class="participantLeft">

            <div class="avatar">

                <?= $icon ?>

            </div>

            <div>

                <div class="participantName">

                    Name :
                    <?= htmlspecialchars(
                        $r['full_name']
                    ) ?>

                </div>

                <div class="participantMeta">

                    ID :
                    <?= htmlspecialchars(
                        $r['matric_no']
                        ?: $r['staff_no']
                    ) ?>

                </div>

            </div>

        </div>

        <!-- RIGHT -->

        <div class="participantRight">

            <?php if($tab=="attendance"): ?>
            
                  <div class="attendanceSubtext">

                    Checked in at

                </div>

                <div class="attendanceTime">

                    <?= date(
                        "g:i A",
                        strtotime(
                            $r['checked_in_at']
                        )
                    ) ?>

                </div>

          

            <?php elseif($tab=="refund"): ?>

                <div class="refundText">

                    Refund Eligible

                </div>

                <div class="refundAmount">

                    RM <?= number_format(
                        $event['fee_amount'],
                        2
                    ) ?>

                </div>

                <div class="refundPhone">

                    <?= htmlspecialchars(
                        $r['phone']
                    ) ?>

                </div>

                <div class="refundEmail">

                    <?= htmlspecialchars(
                        $r['email']
                    ) ?>

                </div>

            <?php else: ?>

                <div class="participantEmail">

                    <?= htmlspecialchars(
                        $r['email']
                    ) ?>

                </div>

            <?php endif; ?>

        </div>

    </div>

    <?php endwhile; ?>

</div>

<script>

/* ================= MODAL ================= */

function openAttendanceModal(){

    document
    .getElementById("attendanceModal")
    .style.display = "flex";
}

function closeAttendanceModal(){

    document
    .getElementById("attendanceModal")
    .style.display = "none";
}

/* ================= CLOSE OUTSIDE ================= */

window.onclick = function(event){

    const modal =
    document.getElementById(
        "attendanceModal"
    );

    if(
        modal &&
        event.target == modal
    ){

        modal.style.display = "none";
    }
}


/* ================= AJAX SAVE ================= */

function initAttendanceAjax(){

    const attendanceForm =
    document.getElementById(
        "attendanceForm"
    );

    if(!attendanceForm){
        return;
    }

    /* PREVENT DUPLICATE EVENT */

    if(attendanceForm.dataset.loaded == "1"){
        return;
    }

    attendanceForm.dataset.loaded = "1";

    attendanceForm.addEventListener(
    "submit",
    function(e){

        e.preventDefault();

        if(
            !confirm(
                "Are you sure you want to update attendance records?"
            )
        ){
            return;
        }

        const formData =
        new FormData(attendanceForm);

        const submitBtn =
        attendanceForm.querySelector(
            ".saveAttendanceBtn"
        );

        if(submitBtn){

            submitBtn.disabled = true;

            submitBtn.innerHTML =
            "Saving...";
        }

        fetch("updateAttendance.php",{

            method:"POST",

            body:formData

        })

        .then(response => response.json())

        .then(data => {

            console.log(data);

            if(!data.success){

                alert(
                    data.message ||
                    "Update failed"
                );

                return;
            }

            closeAttendanceModal();

            alert(
                "Attendance updated successfully!"
            );

            location.reload();

        })

        .catch(error => {

            console.log(error);

            alert(
                "Failed to update attendance."
            );

        })

        .finally(() => {

            if(submitBtn){

                submitBtn.disabled = false;

                submitBtn.innerHTML =
                "Save Attendance";
            }

        });

    });

}

/* INIT */

document.addEventListener(
"DOMContentLoaded",
function(){

    initAttendanceAjax();

});




/* ================= EXPORT DROPDOWN ================= */

function toggleTableExport(e){

    e.stopPropagation();

    document
    .getElementById("tableExportMenu")
    .classList
    .toggle("show");
}

document.addEventListener("click", function(){

    const menu =
    document.getElementById(
        "tableExportMenu"
    );

    if(menu){

        menu.classList.remove("show");
    }

});

</script>