<?php
session_start();

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

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

/* ================= AJAX: UNREAD COUNTS ================= */
if(isset($_GET['ajax']) && $_GET['ajax'] === "unread"){

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

    if(!isset($_SESSION['id'])){
        echo json_encode([]);
        exit;
    }

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

    $sql = "
        SELECT 
            r.event_id,
            COUNT(m.id) AS unread_count
        FROM event_registrations r
        JOIN event_messages m 
            ON r.event_id = m.event_id
        LEFT JOIN event_reads er 
            ON er.event_id = r.event_id 
            AND er.user_id = r.user_id
        WHERE r.user_id = ?
        AND (er.last_read_time IS NULL OR m.created_at > er.last_read_time)
        GROUP BY r.event_id
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();

    $data = [];

    while($row = $res->fetch_assoc()){
        $data[(int)$row['event_id']] = (int)$row['unread_count'];
    }

    echo json_encode($data);
    exit;
}

/* ================= NORMAL PAGE ================= */

include($_SERVER['DOCUMENT_ROOT']."/SEAT/templates/header.php");
include($_SERVER['DOCUMENT_ROOT']."/SEAT/templates/sidebar.php");

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

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

/* EVENTS */
$stmt = $conn->prepare("
SELECT e.id, e.title, e.event_date, o.club_name
FROM event_registrations r
JOIN events e ON r.event_id = e.id
LEFT JOIN organizers o ON e.organizer_id = o.id
WHERE r.user_id = ?
ORDER BY e.event_date DESC
");

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

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

if($event_id <= 0 && $events->num_rows > 0){
    $first = $events->fetch_assoc();
    $event_id = $first['id'];
    $events->data_seek(0);
}

/* SECURITY */
if($event_id > 0){
    $check = $conn->prepare("
        SELECT 1 
        FROM event_registrations 
        WHERE user_id=? AND event_id=?
    ");
    $check->bind_param("ii",$user_id,$event_id);
    $check->execute();

    if($check->get_result()->num_rows === 0){
        die("Unauthorized access");
    }
}

/* MESSAGES */
$messages = null;
$title = "Event Announcements";

if($event_id > 0){

    $msgStmt = $conn->prepare("
        SELECT m.*, e.title, o.club_name
        FROM event_messages m
        JOIN events e ON m.event_id = e.id
        LEFT JOIN organizers o ON e.organizer_id = o.id
        WHERE m.event_id = ?
        ORDER BY m.created_at DESC
    ");

    $msgStmt->bind_param("i",$event_id);
    $msgStmt->execute();
    $messages = $msgStmt->get_result();

    if($messages && $messages->num_rows > 0){
        $firstMsg = $messages->fetch_assoc();
        $title = $firstMsg['title'];
        $messages->data_seek(0);
    }
}

/* STATUS */
function getStatus($date){
    $today = date("Y-m-d");
    if($date > $today) return "upcoming";
    if($date == $today) return "ongoing";
    return "completed";
}
?>

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

<div class="main">
<div class="layout">

<!-- LEFT PANEL -->
<div class="leftPanel">

    <div class="panelHeader">
        <h2>My Events</h2>
        <p>Announcements & updates</p>

        <input type="text"
               id="searchInput"
               placeholder="Search events..."
               onkeyup="filterEvents()">
    </div>

    <div class="tabs">
        <button class="tab active" onclick="filterStatus('upcoming',this)">Upcoming</button>
        <button class="tab" onclick="filterStatus('ongoing',this)">Ongoing</button>
        <button class="tab" onclick="filterStatus('completed',this)">Completed</button>
        <button class="tab" onclick="filterStatus('all',this)">All</button>
    </div>

    <div id="eventList">

        <?php while($e = $events->fetch_assoc()): ?>
            <?php $status = getStatus($e['event_date']); ?>

            <a href="?event_id=<?= $e['id'] ?>"
               class="eventCard <?= $event_id==$e['id'] ? 'active' : '' ?>"
               data-title="<?= strtolower($e['title']) ?>"
               data-status="<?= $status ?>"
               data-event-id="<?= $e['id'] ?>">

                <!-- BLUE DOT -->
                

                <div class="eventContent">

                    <div class="titleRow">
                        <div class="title"><?= htmlspecialchars($e['title']) ?></div>
                        <span class="badge" style="display:none;"></span>
                    </div>

                    <div class="club"><?= htmlspecialchars($e['club_name']) ?></div>
                    <div class="date"><?= date("d M Y",strtotime($e['event_date'])) ?></div>

                </div>

            </a>

        <?php endwhile; ?>

    </div>

</div>

<!-- RIGHT PANEL -->
<div class="rightPanel">

    <div class="rightHeader">
        <h3><?= htmlspecialchars($title) ?></h3>
    </div>

    <div id="messageList">

        <?php if(!$messages || $messages->num_rows==0): ?>
            <div class="msgCard">No announcements available</div>
        <?php else: ?>

            <?php while($m = $messages->fetch_assoc()): ?>

            <div class="msgCard">

                <div class="meta">
                    <span><?= $m['club_name'] ?></span>
                    <span><?= date("d M H:i",strtotime($m['created_at'])) ?></span>
                </div>

                <div class="text">
                    <?= nl2br(htmlspecialchars($m['message'])) ?>
                </div>

                <?php if(!empty($m['attachment'])): ?>
                    <?php
                        $url="/SEAT/uploads/event_messages/".$m['attachment'];
                        $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
                        $img=in_array($ext,['jpg','jpeg','png','webp','gif']);
                    ?>

                    <?php if($img): ?>
                        <img src="<?= $url ?>" class="thumb"
                             onclick="openImage('<?= $url ?>')">
                    <?php else: ?>
                        <a href="<?= $url ?>" class="fileBtn" target="_blank">View File</a>
                    <?php endif; ?>

                <?php endif; ?>

            </div>

            <?php endwhile; ?>

        <?php endif; ?>

    </div>

</div>

</div>
</div>


<!-- IMAGE MODAL -->
<div class="imgModal" id="imgModal">
    <div class="imgBox" onclick="event.stopPropagation()">

        <button
            type="button"
            class="closeBtn"
            aria-label="Close"
            onclick="closeImage()">

            <i class="fas fa-xmark"></i>

        </button>

        <img id="imgPreview" src="" alt="Preview">

    </div>
</div>

<script>

/* SEARCH */
function filterEvents(){
    const input = document.getElementById("searchInput").value.toLowerCase();

    document.querySelectorAll(".eventCard").forEach(card=>{
        card.style.display = card.innerText.toLowerCase().includes(input)
            ? "flex"
            : "none";
    });
}

/* FILTER */
function filterStatus(status,btn){
    document.querySelectorAll(".tab").forEach(t=>t.classList.remove("active"));
    btn.classList.add("active");

    document.querySelectorAll(".eventCard").forEach(card=>{
        const match = status === "all" || card.dataset.status === status;
        card.style.display = match ? "flex" : "none";
    });
}

/* UNREAD AJAX */
function loadUnread(){

    const url = new URL(window.location.href);
    url.searchParams.set("ajax","unread");

    fetch(url.toString())
        .then(res => res.json())
        .then(data => {

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

                const id = card.dataset.eventId;
                const badge = card.querySelector(".badge");
                const count = data[id] || 0;

                if(!badge) return;

                if(count > 0){
                    badge.style.display = "inline-flex";
                    badge.textContent = count > 99 ? "99+" : count;
                } else {
                    badge.style.display = "none";
                }

            });

        })
        .catch(err => console.log("Unread error:", err));
}

document.addEventListener("DOMContentLoaded", function(){
    loadUnread();
    setInterval(loadUnread, 5000);
});


function openImage(src){

    if(!src) return;

    const modal = document.getElementById("imgModal");
    const img = document.getElementById("imgPreview");

    img.src = src;
    modal.classList.add("show");

    document.body.style.overflow = "hidden";
}

function closeImage(){

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

    modal.classList.remove("show");

    document.body.style.overflow = "";
}

document.getElementById("imgModal").addEventListener("click", closeImage);

document.addEventListener("keydown", function(e){

    if(e.key === "Escape"){
        closeImage();
    }

});

</script>