<?php
session_start();

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

if(!isset($_SESSION['id'])){
    die("Session expired");
}

$user_id = (int)$_SESSION['id'];

/* =====================================================
   GET TICKETS
===================================================== */

$stmt = $conn->prepare("
SELECT 
    e.*,
    o.club_name,
    r.token,
    r.status,
    r.registered_at,

    p.full_name,
    p.matric_no,
    p.staff_no,
    p.phone

FROM event_registrations r

JOIN events e
    ON r.event_id = e.id

LEFT JOIN organizers o
    ON e.organizer_id = o.id

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

WHERE r.user_id = ?

ORDER BY e.event_date ASC
");

$stmt->bind_param("i",$user_id);
$stmt->execute();

$result = $stmt->get_result();
?>

<link
rel="stylesheet"
href="/SEAT/assets/css/participant/myTicket.css">

<?php
include("../../templates/header.php");
include("../../templates/sidebar.php");
?>

<div class="main">

    <h2>My Tickets</h2>

    <p class="sub">
        View and manage your event tickets
    </p>

    <!-- =========================
         TABS
    ========================== -->

    <div class="tabs">

        <button
        class="tab active"
        onclick="filterTab(event,'upcoming')">

            Upcoming

        </button>

        <button
        class="tab"
        onclick="filterTab(event,'completed')">

            Completed

        </button>

        <button
        class="tab"
        onclick="filterTab(event,'cancelled')">

            Cancelled

        </button>

    </div>

    <!-- =========================
         GRID
    ========================== -->

    <div class="grid">

        <?php while($t = $result->fetch_assoc()):

            $today = date("Y-m-d");

            if($t['status'] == 'cancelled'){

                $ui_status = "cancelled";

            }else if($t['status'] == 'attended'){

                $ui_status = "completed";

            }else{

                $ui_status =
                ($t['event_date'] >= $today)
                ? "upcoming"
                : "completed";
            }

            $ticketJSON =
            htmlspecialchars(
                json_encode(
                    $t,
                    JSON_HEX_TAG
                    | JSON_HEX_APOS
                    | JSON_HEX_QUOT
                ),
                ENT_QUOTES,
                'UTF-8'
            );
        ?>

        <div
        class="ticketCard"

        data-status="<?= $ui_status ?>"

        data-ticket='<?= $ticketJSON ?>'>

            <!-- TOP -->
            <div class="cardTop">

                <div>

                    <h3>
                        <?= htmlspecialchars($t['title']) ?>
                    </h3>

                    <p class="club">

                        <?= htmlspecialchars(
                            $t['club_name'] ?? 'N/A'
                        ) ?>

                    </p>

                </div>

                <div class="badgeWrap">

                    <span class="badge <?= $ui_status ?>">

                        <?= ucfirst($ui_status) ?>

                    </span>

                    <!-- MESSAGE BUTTON -->
                    <button
                    class="msgIcon"

                    onclick="
                    openMessageModal(
                    <?= $t['id'] ?>
                    )
                    ">

                        <i class="fa fa-envelope"></i>

                    </button>

                </div>

            </div>

            <!-- INFO -->
            <div class="cardInfo">

                <p class="infoItem">

                    <span class="icon">
                        <i class="fa fa-calendar"></i>
                    </span>
                
                    <?= date(
                        "M d, Y (h:i A)",
                        strtotime($t['event_date'] . ' ' . $t['start_time'])
                    ) ?>
                
                </p>

                <p class="infoItem">

                    <span class="icon">
                        <i class="fa fa-map-marker"></i>
                    </span>

                    <?= htmlspecialchars(
                        $t['venue']
                        ?: $t['mode']
                        ?: 'TBA'
                    ) ?>

                </p>

                <p class="infoItem">

                    <span class="icon">
                        <i class="fa fa-ticket"></i>
                    </span>

                    <?=
                    $t['fee_type']=="Free"

                    ? "Free Entry"

                    : "RM "
                    . number_format(
                        $t['fee_amount'],
                        2
                    )
                    ?>

                </p>

                <p class="registered">

                    <i class="fa fa-clock"></i>

                    Registered

                    <?= date(
                        "M d, Y",
                        strtotime($t['registered_at'])
                    ) ?>

                </p>

            </div>

            <!-- BUTTON -->
            <button
            class="btn"

            onclick="
            handleTicket(
            this,
            '<?= $t['mode'] ?>'
            )
            ">

                <i class="fa fa-qrcode"></i>

                <?=
                $t['mode']=="online"

                ? "Get Meeting Link"

                : "View QR Ticket"
                ?>

            </button>

        </div>

        <?php endwhile; ?>

    </div>

</div>

<!-- =========================
     MAIN MODAL
========================= -->

<div
id="modal"
class="modal"

style="display:none;"></div>

<script>

/* =========================
   ESCAPE HTML
========================= */

function escapeHTML(str){

    return String(str ?? '')

    .replace(/&/g,"&amp;")
    .replace(/</g,"&lt;")
    .replace(/>/g,"&gt;")
    .replace(/"/g,"&quot;")
    .replace(/'/g,"&#039;");
}

/* =========================
   FILTER TAB
========================= */

function filterTab(e,status){

    document
    .querySelectorAll(".tab")
    .forEach(t => t.classList.remove("active"));

    if(e && e.target){
        e.target.classList.add("active");
    }

    document
    .querySelectorAll(".ticketCard")
    .forEach(card => {

        card.style.display =

        (card.dataset.status === status)

        ? "block"

        : "none";
    });
}

/* DEFAULT TAB */
document.addEventListener(
"DOMContentLoaded",
()=>{

    let active =
    document.querySelector(".tab.active");

    if(active){

        filterTab(
            {target:active},
            "upcoming"
        );
    }
});

/* =========================
   HANDLE TICKET
========================= */

function handleTicket(el,mode){

    let t = JSON.parse(
        el.closest('.ticketCard')
        .dataset.ticket
    );

    if(mode === "online"){

        openOnlineTicket(t);

    }else{

        openQR(t);
    }
}

/* =========================
   QR TICKET
========================= */

function openQR(t){

    let modal =
    document.getElementById("modal");

    modal.innerHTML = `

    <div class="modalBox">

        <span
        class="close"
        onclick="closeModal()">

            &times;

        </span>

        <p class="centerText">
            Present this QR code at the event entrance
        </p>

        <img
        src="
        https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=
        ${escapeHTML(t.token)}
        ">

        <div class="ticketID">

            ${escapeHTML(t.token)}

        </div>

        <div class="section">

            <b>Event</b>

            <div class="row">
                <span>Title</span>
                <span>${escapeHTML(t.title)}</span>
            </div>

            <div class="row">
                <span>Organizer</span>
                <span>${escapeHTML(t.club_name)}</span>
            </div>

            <div class="row">
                <span>Date</span>
                <span>${escapeHTML(t.event_date)}</span>
            </div>

            <div class="row">
                <span>Time</span>
                <span>${escapeHTML(t.start_time)}</span>
            </div>

            <div class="row">
                <span>Venue</span>
                <span>${escapeHTML(t.venue ?? t.mode)}</span>
            </div>

        </div>

        <div class="section">

            <b>Participant</b>

            <div class="row">
                <span>Name</span>
                <span>${escapeHTML(t.full_name)}</span>
            </div>

            <div class="row">
                <span>Matric</span>
                <span>${escapeHTML(t.matric)}</span>
            </div>

        </div>

        <p class="note">
            Please present this QR during check-in
        </p>

    </div>
    `;

    modal.style.display = "flex";
}

/* =========================
   ONLINE TICKET
========================= */

function openOnlineTicket(t){

    let modal =
    document.getElementById("modal");

    let link =
    t.meeting_link
    ?? "https://zoom.us";

    modal.innerHTML = `

    <div class="modalBox">

        <span
        class="close"
        onclick="closeModal()">

            &times;

        </span>

        <p class="centerText">
            Use this link to join
        </p>

        <div class="linkBox">

            ${escapeHTML(link)}

        </div>

        <button
        class="btn"

        onclick="
        copyLink(
        '${link}'
        )
        ">

            Copy Link

        </button>

        <div class="section">

            <b>Event</b>

            <div class="row">
                <span>Title</span>
                <span>${escapeHTML(t.title)}</span>
            </div>

            <div class="row">
                <span>Organizer</span>
                <span>${escapeHTML(t.club_name)}</span>
            </div>

            <div class="row">
                <span>Date</span>
                <span>${escapeHTML(t.event_date)}</span>
            </div>

            <div class="row">
                <span>Time</span>
                <span>${escapeHTML(t.start_time)}</span>
            </div>

        </div>

    </div>
    `;

    modal.style.display = "flex";
}

/* =========================
   COPY LINK
========================= */

function copyLink(link){

    navigator.clipboard.writeText(link);

    alert("Copied");
}

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

function closeModal(){

    let modal =
    document.getElementById("modal");

    modal.style.display = "none";

    modal.innerHTML = "";
}

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

function openMessageModal(eventId){

    let modal =
    document.getElementById("modal");

    modal.style.display = "flex";

    modal.innerHTML = `

    <div class="loadingBox">
        Loading messages...
    </div>

    `;

fetch(
"/SEAT/modules/Notification/event_message.php?event_id="
+ eventId
)

.then(res => res.text())

.then(html => {

    modal.innerHTML = html;

    /* =========================
       EXECUTE SCRIPTS
    ========================== */
    const scripts =
    modal.querySelectorAll("script");

    scripts.forEach(oldScript => {

        const newScript =
        document.createElement("script");

        if(oldScript.src){

            newScript.src =
            oldScript.src;

        }else{

            newScript.textContent =
            oldScript.textContent;
        }

        document.body
        .appendChild(newScript);

        oldScript.remove();
    });

})

.catch(() => {

    modal.innerHTML = `

    <div class="modalBox messageModal">

        <span
        class="closeX"
        onclick="closeModal()">

            &times;

        </span>

        <div class="emptyState">

            Failed to load messages

        </div>

    </div>

        `;
    });
}

</script>