<?php

session_start();

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

include("../../templates/header.php");
include("../../templates/sidebar.php");

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

if(
    !isset($_SESSION['role']) ||
    $_SESSION['role'] != "organizer"
){
    die("No access");
}

/* =========================================================
VALIDATE INPUT
========================================================= */

$event_id =
intval($_GET['event_id'] ?? 0);

$tab =
$_GET['tab'] ?? "participants";

if($event_id <= 0){

    die("Invalid event ID");
}

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

$eventQuery = mysqli_query($conn,"
SELECT *
FROM events
WHERE id = '$event_id'
LIMIT 1
");

if(!$eventQuery){

    die(mysqli_error($conn));
}

$event =
mysqli_fetch_assoc($eventQuery);

if(!$event){

    die("Event not found");
}

/* =========================================================
SAFE EVENT DATE
========================================================= */

$eventDateText = "No event date";

if(
    !empty($event['event_date']) &&
    $event['event_date'] != "0000-00-00"
){

    $timestamp =
    strtotime($event['event_date']);

    if($timestamp){

        $eventDateText =
        date(
            "F d, Y",
            $timestamp
        );
    }
}

/* =========================================================
REFUND MODE
========================================================= */

$isRefundOnly = (
    $event['status'] == "cancelled" &&
    $event['fee_type'] == "Paid"
);

if($isRefundOnly){

    $tab = "refund";
}

/* =========================================================
TOTAL REGISTRATION
========================================================= */

$totalQuery = mysqli_query($conn,"
SELECT COUNT(*) AS total
FROM event_registrations
WHERE event_id = '$event_id'
");

$totalRow =
mysqli_fetch_assoc($totalQuery);

$total =
intval($totalRow['total'] ?? 0);

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

$attendanceQuery = mysqli_query($conn,"
SELECT COUNT(*) AS total
FROM attendances
WHERE event_id = '$event_id'
");

$attendanceRow =
mysqli_fetch_assoc($attendanceQuery);

$attendance =
intval($attendanceRow['total'] ?? 0);

$rate = 0;

if($total > 0){

    $rate =
    round(
        ($attendance / $total) * 100,
        1
    );
}

/* =========================================================
REVENUE
========================================================= */

$feeAmount =
floatval(
    $event['fee_amount'] ?? 0
);

$revenue =
$total * $feeAmount;

/* =========================================================
CAPACITY
========================================================= */

$capacity =
intval(
    $event['max_participant'] ?? 0
);

$capacityPercent = 0;

if($capacity > 0){

    $capacityPercent =
    round(
        ($total / $capacity) * 100,
        1
    );

    if($capacityPercent > 100){

        $capacityPercent = 100;
    }
}

?>

<link rel="stylesheet"
href="/SEAT/assets/css/organizer/viewReport.css">

<div class="reportWrapper">

    <div class="reportContainer">

        <div class="reportPage">

            <!-- =====================================================
                 HEADER
            ====================================================== -->

            <div class="eventHeaderInfo">

                <a href="analytics.php"
                class="backBtn">

                    ← Back to Overview

                </a>

                <div class="eventTitleWrap">

                    <h2>

                        <?= htmlspecialchars(
                            $event['title']
                        ) ?>

                    </h2>

                    <div class="eventDate">

                        <?= htmlspecialchars(
                            $eventDateText
                        ) ?>

                    </div>

                </div>

            </div>

            <!-- =====================================================
                 STATS
            ====================================================== -->

            <div class="statsGrid">

                <!-- TOTAL -->

                <div class="statCard">

                    <div class="cardTop">

                        <div>

                            <div class="statTitle">
                                Total Registrations
                            </div>

                            <div class="statValue">
                                <?= $total ?>
                            </div>

                            <div class="statSub">
                                <?= $capacityPercent ?>
                                % capacity used
                            </div>

                            <div class="progress">

                                <div style="
                                width:
                                <?= $capacityPercent ?>%;
                                ">
                                </div>

                            </div>

                        </div>

                        <div class="statIcon blue">
                            👥
                        </div>

                    </div>

                </div>

                <!-- ATTENDANCE -->

                <div class="statCard">

                    <div class="cardTop">

                        <div>

                            <div class="statTitle">
                                Attendance
                            </div>

                            <div class="statValue">
                                <?= $attendance ?>
                            </div>

                            <div class="statSub">
                                <?= $rate ?>
                                % attendance rate
                            </div>

                            <div class="progress">

                                <div style="
                                width:
                                <?= $rate ?>%;
                                ">
                                </div>

                            </div>

                        </div>

                        <div class="statIcon green">
                            ✓
                        </div>

                    </div>

                </div>

                <!-- REVENUE -->

                <div class="statCard">

                    <div class="cardTop">

                        <div>

                            <div class="statTitle">
                                Revenue
                            </div>

                            <?php if(
                                $event['fee_type'] == "Free"
                            ): ?>

                                <div class="statValue">
                                    FREE
                                </div>

                                <div class="statSub">
                                    No payment required
                                </div>

                            <?php else: ?>

                                <div class="statValue">

                                    RM <?= number_format(
                                        $revenue,
                                        2
                                    ) ?>

                                </div>

                                <div class="statSub">

                                    RM <?= number_format(
                                        $feeAmount,
                                        2
                                    ) ?>

                                    per ticket

                                </div>

                            <?php endif; ?>

                        </div>

                        <div class="statIcon orange">
                            $
                        </div>

                    </div>

                </div>

                <!-- STATUS -->

                <div class="statCard">

                    <div class="cardTop">

                        <div>

                            <div class="statTitle">
                                Status
                            </div>

                            <div class="statusBadge">

                                <?= ucfirst(
                                    htmlspecialchars(
                                        $event['status']
                                    )
                                ) ?>

                            </div>

                            <div class="statSub statusText">

                                Capacity:
                                <?= $capacity ?>
                                participants

                            </div>

                        </div>

                        <div class="statIcon gray">
                            📌
                        </div>

                    </div>

                </div>

            </div>

            <!-- =====================================================
                 CONTENT CARD
            ====================================================== -->

            <div class="contentCard">

                <!-- =====================================================
                     TAB BAR
                ====================================================== -->

                <div class="tabBar">

                    <?php if(!$isRefundOnly): ?>

                    <a
                    href="?event_id=<?= $event_id ?>&tab=participants"
                    data-tab="participants"
                    class="tabLink <?= $tab=='participants' ? 'active' : '' ?>">

                        Participant List

                    </a>

                    <a
                    href="?event_id=<?= $event_id ?>&tab=attendance"
                    data-tab="attendance"
                    class="tabLink <?= $tab=='attendance' ? 'active' : '' ?>">

                        Attendance List

                    </a>

                    <?php else: ?>

                    <a
                    href="?event_id=<?= $event_id ?>&tab=refund"
                    data-tab="refund"
                    class="tabLink active">

                        Refund List

                    </a>

                    <?php endif; ?>

                </div>

                <!-- =====================================================
                     CONTENT BODY
                ====================================================== -->

                <div
                id="contentBody"
                class="contentBody">

                    <?php include("list.php"); ?>

                </div>

            </div>

        </div>

    </div>

</div>

<script>

/* =========================================================
LOAD CONTENT
========================================================= */

function loadTabContent(url){

    const content =
    document.getElementById(
        "contentBody"
    );

    if(!content){
        return;
    }

    content.innerHTML = `
    <div class="tableLoader">
        Loading...
    </div>
    `;

    fetch(url)

    .then(response => response.text())

    .then(html => {

        const parser =
        new DOMParser();

        const doc =
        parser.parseFromString(
            html,
            "text/html"
        );

        const newContent =
        doc.querySelector(
            "#contentBody"
        );

        const newTabs =
        doc.querySelector(
            ".tabBar"
        );

        if(newContent){

            content.innerHTML =
            newContent.innerHTML;
        }

        if(newTabs){

            document.querySelector(
                ".tabBar"
            ).innerHTML =
            newTabs.innerHTML;
        }

        window.history.pushState(
            {},
            "",
            url
        );

        initAjaxTabs();
        initAttendanceAjax();

    })

    .catch(error => {

        console.log(error);

        content.innerHTML = `
        <div class="emptyState">
            Failed to load content
        </div>
        `;

    });

}

/* =========================================================
AJAX TAB SWITCH
========================================================= */

function initAjaxTabs(){

    document
    .querySelectorAll(".tabLink")
    .forEach(tab => {

        const newTab =
        tab.cloneNode(true);

        tab.parentNode.replaceChild(
            newTab,
            tab
        );

    });

    document
    .querySelectorAll(".tabLink")
    .forEach(tab => {

        tab.addEventListener(
        "click",
        function(e){

            e.preventDefault();

            const url =
            this.getAttribute("href");

            loadTabContent(url);

        });

    });

}

/* =========================================================
INIT
========================================================= */

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

    initAjaxTabs();
    initAttendanceAjax();

});

</script>

