<?php
session_start();

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

if(!isset($_SESSION['id'])){
    exit("No access");
}

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

/* =========================
   SECURITY CHECK
========================= */

$stmt = $conn->prepare("
SELECT 1
FROM event_registrations
WHERE user_id = ?
AND event_id = ?
LIMIT 1
");

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

if($stmt->get_result()->num_rows === 0){

    exit("
    <div class='messageModal error'>

        <div class='msgHeader'>
            <div class='iconBox'>⚠️</div>
            <div>
                <h3>Access Denied</h3>
                <small>Unauthorized Access</small>
            </div>
        </div>

        <div class='msgBody'>
            <div class='emptyState'>
                <p>You are not registered for this event.</p>
            </div>
        </div>

    </div>
    ");
}

/* =========================
   FETCH MESSAGES
========================= */

$stmt = $conn->prepare("
SELECT
    m.*,
    o.club_name,
    e.title

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
");

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

$res = $stmt->get_result();

$messages = [];
$title = "Event Messages";

while($row = $res->fetch_assoc()){
    $messages[] = $row;
}

if(!empty($messages)){

    $title = $messages[0]['title'];

}else{

    $ev = $conn->prepare("
    SELECT title
    FROM events
    WHERE id = ?
    ");

    $ev->bind_param("i",$event_id);
    $ev->execute();

    $title =
    $ev->get_result()->fetch_assoc()['title']
    ?? "Event Messages";
}
?>

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

<div class="messageModal">

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

    <div class="msgHeader">

        <div class="iconBox">📢</div>

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

            <small>
                Official Event Updates
            </small>
        </div>

        <button
        class="closeBtn"
        onclick="closeModal()">

            &times;

        </button>

    </div>

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

    <div class="msgBody">

        <?php if(empty($messages)): ?>

            <div class="emptyState">
                <p>No updates yet</p>
            </div>

        <?php else: ?>

            <?php foreach($messages as $m): ?>

                <div class="msgItem">

                    <div class="dot"></div>

                    <div class="msgCard">

                        <!-- META -->
                        <div class="meta">

                            <span class="sender">

                                <?= htmlspecialchars(
                                    $m['club_name']
                                    ?: 'Organizer'
                                ) ?>

                            </span>

                            <span class="time">

                                <?= date(
                                    "d M Y • h:i A",
                                    strtotime($m['created_at'])
                                ) ?>

                            </span>

                        </div>

                        <!-- MESSAGE -->
                        <?php if(!empty($m['message'])): ?>

                            <div class="text">

                                <?= nl2br(
                                    htmlspecialchars($m['message'])
                                ) ?>

                            </div>

                        <?php endif; ?>

                        <!-- ATTACHMENT -->
                        <?php
                        if(!empty($m['attachment'])):

                            $url =
                            "/SEAT/uploads/event_messages/"
                            . rawurlencode($m['attachment']);

                            $ext =
                            strtolower($m['file_type']);

                            $isImage =
                            in_array($ext,[
                                'jpg',
                                'jpeg',
                                'png',
                                'webp',
                                'gif'
                            ]);
                        ?>

                        <div class="attach">

                            <?php if($isImage): ?>

                                <div
                                class="thumbWrap"

                                onclick="
                                openImage(
                                '<?= htmlspecialchars($url,ENT_QUOTES) ?>'
                                )
                                ">

                                    <img
                                    src="<?= htmlspecialchars($url) ?>"

                                    class="thumb"

                                    alt="Attachment"

                                    loading="lazy">

                                </div>

                            <?php else: ?>

                                <a
                                href="<?= htmlspecialchars($url) ?>"

                                target="_blank"

                                class="file">

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

                                    Download File

                                </a>

                            <?php endif; ?>

                        </div>

                        <?php endif; ?>

                    </div>

                </div>

            <?php endforeach; ?>

        <?php endif; ?>

    </div>

</div>
<div
id="imgModal"
class="imgModal">

    <div
    class="imgOverlay"
    onclick="closeImage()"></div>

    <div class="imgBox">

        <button
        class="imgClose"
        onclick="closeImage()">

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

        </button>

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

    </div>

</div>

<script>

/* =========================
   OPEN IMAGE
========================= */

function openImage(src){

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

    const preview =
    document.getElementById("imgPreview");

    preview.src = src;

    modal.classList.add("show");

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

/* =========================
   CLOSE IMAGE
========================= */

function closeImage(){

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

    const preview =
    document.getElementById("imgPreview");

    modal.classList.remove("show");

    preview.src = "";

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


/* =========================
   ESC KEY SUPPORT
========================= */

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

    if(e.key === "Escape"){

        closeImage();
    }

});

</script>