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

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

$user_id = (int)$_SESSION['id'];
$BASE = "/SEAT";

/* =====================================================
   GET EVENTS (FIXED REGISTERED LOGIC)
===================================================== */
$events = $conn->query("
SELECT 
    e.*, 
    o.club_name,

    EXISTS (
        SELECT 1 
        FROM event_registrations r
        JOIN participants p ON p.id = r.participant_id
        WHERE r.event_id = e.id
        AND p.user_id = $user_id
    ) AS registered

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

WHERE e.event_date >= CURDATE()

ORDER BY e.event_date ASC
");
?>

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

<link rel="stylesheet" href="<?= $BASE ?>/assets/css/participant/event.css">

<div class="main">

<h2>Browse Events</h2>
<p class="sub">Discover events from clubs</p>

<!-- ================= SEARCH ================= -->
<div class="searchBox">
    <input
        type="text"
        id="searchInput"
        placeholder="🔍 Search event, club, venue..."
        onkeyup="searchEvent()"
    >
</div>

<!-- ================= GRID ================= -->
<div class="grid" id="eventGrid">

<?php while($e = $events->fetch_assoc()) { 

$registered = (int)$e['registered'] === 1;

/* safe JSON */
$eventJSON = htmlspecialchars(
    json_encode($e, JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG),
    ENT_QUOTES,
    'UTF-8'
);

/* poster */
$poster = !empty($e['poster'])
    ? $BASE . "/uploads/event_posters/" . $e['poster']
    : null;

?>

<div class="card eventCard"

data-title="<?= strtolower(htmlspecialchars($e['title'])) ?>"
data-club="<?= strtolower(htmlspecialchars($e['club_name'] ?? '')) ?>"
data-venue="<?= strtolower(htmlspecialchars($e['venue'] ?? '')) ?>"
data-mode="<?= strtolower(htmlspecialchars($e['mode'] ?? '')) ?>"
data-date="<?= strtolower(htmlspecialchars($e['event_date'])) ?>">

<!-- TAG -->
<span class="tag <?= strtolower($e['mode']) ?>">
    <?= htmlspecialchars($e['mode']) ?>
</span>

<!-- POSTER -->
<div class="eventPosterWrap"
     <?php if($poster): ?>
        onclick="openPoster('<?= $poster ?>')"
     <?php endif; ?>
>

<?php if($poster): ?>
    <img src="<?= $poster ?>" class="eventPosterImg" alt="Event Poster">
<?php else: ?>
    <div class="eventThumbWrap noImage">
        No Poster Available
    </div>
<?php endif; ?>

</div>

<!-- TITLE -->
<h3><?= htmlspecialchars($e['title']) ?></h3>

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

<p>🏢 <?= htmlspecialchars($e['club_name'] ?? 'N/A') ?></p>

<p>📅 <?= date("d M Y", strtotime($e['event_date'])) ?></p>

<p>⏰ <?= date("h:i A", strtotime($e['start_time'])) ?></p>

<p>📍 <?= htmlspecialchars($e['venue'] ?: $e['mode'] ?: 'TBA') ?></p>

</div>

<!-- PRICE -->
<p class="eventPrice">
💰 <?= $e['fee_type']=="Free" ? "Free" : "RM ".number_format($e['fee_amount'],2) ?>
</p>

<!-- BUTTON -->
<?php if($registered){ ?>
    <button class="btn disabled" disabled>✔ Registered</button>
<?php } else { ?>
    <button class="btn"
        id="btn-<?= $e['id'] ?>"
        onclick='openEvent(<?= $eventJSON ?>)'>
        Register
    </button>
<?php } ?>

</div>

<?php } ?>

</div>

<!-- ================= NO RESULT ================= -->
<p id="noResult" class="noResult">No event found</p>

<!-- ================= MODALS ================= -->
<div id="modal" class="modal"></div>

<div id="imgModal" class="imageModal" onclick="closePoster()">
    <div class="imageModalBox">
        <div class="imageClose" onclick="closePoster(event)">×</div>
        <img id="imgModalContent">
    </div>
</div>

<script src="/SEAT/modules/Event/participant/register.js"></script>

<script>
const BASE = "<?= $BASE ?>";

/* ================= SEARCH ================= */
function searchEvent(){

let input = document.getElementById("searchInput").value.toLowerCase();
let cards = document.querySelectorAll(".eventCard");
let found = false;

cards.forEach(card=>{

let text =
card.dataset.title + " " +
card.dataset.club + " " +
card.dataset.venue + " " +
card.dataset.mode + " " +
card.dataset.date;

if(text.includes(input)){
card.style.display = "block";
found = true;
}else{
card.style.display = "none";
}

});

document.getElementById("noResult").style.display =
found ? "none" : "block";

}

/* ================= OPEN EVENT ================= */
function openEvent(e){
openRegisterModal(e.id);
}

/* ================= MODAL ================= */
function openRegisterModal(event_id){

const modal = document.getElementById("modal");
modal.style.display = "flex";
modal.innerHTML = `<div class="modalBox">Loading...</div>`;

fetch(BASE + "/modules/Event/participant/register.php?event_id=" + event_id)
.then(res => res.text())
.then(html => {
    modal.innerHTML = html;
})
.catch(() => {
    modal.innerHTML = `
        <div class="modalBox">
            <p style="color:red;">Failed to load.</p>
            <button class="btn" onclick="closeModal()">Close</button>
        </div>
    `;
});

}

/* ================= CLOSE ================= */
function closeModal(){
document.getElementById("modal").style.display = "none";
}

function openPoster(src){
document.getElementById("imgModalContent").src = src;
document.getElementById("imgModal").classList.add("show");
}

function closePoster(e){
if(e) e.stopPropagation();
document.getElementById("imgModal").classList.remove("show");
}

</script>