<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

/* =========================
   SESSION CHECK
========================= */
if(!isset($_SESSION['id'])){
    die("Session expired");
}

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

/* =========================
   EVENT ID
========================= */
$event_id = filter_input(INPUT_GET, 'event_id', FILTER_VALIDATE_INT);

if(!$event_id){
    die("Invalid event");
}

/* =========================
   GET EVENT
========================= */
$stmt = $conn->prepare("SELECT * FROM events WHERE id=?");
$stmt->bind_param("i", $event_id);
$stmt->execute();
$event = $stmt->get_result()->fetch_assoc();

if(!$event){
    die("Event not found");
}

/* =========================
   CHECK REGISTRATION
========================= */
$check = $conn->prepare("
SELECT id 
FROM event_registrations 
WHERE event_id=? AND user_id=? AND status='registered'
LIMIT 1
");

if(!$check){
    die("SQL ERROR: " . $conn->error);
}

$check->bind_param("ii", $event_id, $user_id);
$check->execute();
$res = $check->get_result();

if($res->num_rows == 0){
    die("You are not registered for this event");
}

/* =========================
   DISCUSSION RULE
========================= */
$can_reply = ($event['status'] == 'upcoming' || $event['status'] == 'ongoing');

/* =========================
   SEND MESSAGE
========================= */
if(isset($_POST['send'])){

    if(!$can_reply){
        die("Discussion closed");
    }

    $message = trim($_POST['message']);
    if($message == ""){
        die("Message required");
    }

    $insert = $conn->prepare("
        INSERT INTO event_messages(event_id, sender_id, type, message)
        VALUES(?,?, 'question', ?)
    ");

    if(!$insert){
        die("SQL ERROR: " . $conn->error);
    }

    $insert->bind_param("iis", $event_id, $user_id, $message);
    $insert->execute();

    header("Location: ?event_id=".$event_id);
    exit;
}

/* =========================
   GET MESSAGES
========================= */
$msg = $conn->prepare("
SELECT 
    m.*, 
    COALESCE(u.full_name, u.email) AS name
FROM event_messages m
LEFT JOIN users u ON m.sender_id = u.id
WHERE m.event_id=? AND m.is_deleted=0
ORDER BY m.created_at ASC
");

if(!$msg){
    die("SQL ERROR: " . $conn->error);
}

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


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Event Chat</title>

<style>
body{
    margin:0;
    font-family:Arial;
    background:#eef2f7;
}

/* HEADER */
.header{
    background:#1f2937;
    color:white;
    padding:15px;
    text-align:center;
}

/* WRAPPER */
.chat-container{
    max-width:800px;
    margin:20px auto;
    background:white;
    border-radius:10px;
    overflow:hidden;
    display:flex;
    flex-direction:column;
    height:80vh;
}

/* MESSAGES */
.messages{
    flex:1;
    padding:15px;
    overflow-y:auto;
    background:#f9fafb;
}

/* BUBBLE */
.msg{
    margin-bottom:12px;
    display:flex;
}

.msg .bubble{
    padding:10px 14px;
    border-radius:15px;
    max-width:70%;
    font-size:14px;
}

.me{
    justify-content:flex-end;
}

.me .bubble{
    background:#2563eb;
    color:white;
    border-bottom-right-radius:0;
}

.other .bubble{
    background:#e5e7eb;
    border-bottom-left-radius:0;
}

/* NAME */
.name{
    font-size:11px;
    opacity:0.7;
    margin-bottom:3px;
}

/* ROLE BADGE */
.badge{
    font-size:10px;
    padding:2px 6px;
    border-radius:10px;
    margin-left:5px;
    color:white;
}

.student{background:#3b82f6;}
.organizer{background:#10b981;}
.admin{background:#ef4444;}

/* INPUT */
.input-box{
    display:flex;
    padding:10px;
    border-top:1px solid #ddd;
    background:white;
}

textarea{
    flex:1;
    padding:10px;
    border-radius:8px;
    border:1px solid #ccc;
    resize:none;
    height:50px;
}

button{
    margin-left:10px;
    padding:10px 15px;
    background:#2563eb;
    color:white;
    border:none;
    border-radius:8px;
    cursor:pointer;
}

button:hover{
    background:#1d4ed8;
}

/* LOCKED */
.locked{
    text-align:center;
    padding:20px;
    color:#b91c1c;
    font-weight:bold;
}
</style>
</head>

<body>

<div class="header">
    <h2><?= htmlspecialchars($event['title']) ?></h2>
    <small><?= $event['status'] ?></small>
</div>

<div class="chat-container">

<!-- MESSAGES -->
<div class="messages" id="chatBox">

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

<div class="msg <?= ($m['sender_id']==$user_id)?'me':'other' ?>">

<div class="bubble">

<div class="name">
<?= htmlspecialchars($m['name']) ?>
<span class="badge <?= $m['role'] ?? 'student' ?>">
<?= $m['role'] ?? 'student' ?>
</span>
</div>

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

</div>

</div>

<?php endwhile; ?>

</div>

<!-- INPUT -->
<?php if($can_reply): ?>

<form method="POST" class="input-box">
    <textarea name="message" placeholder="Type message..." required></textarea>
    <button name="send">Send</button>
</form>

<?php else: ?>

<div class="locked">
    🔒 Chat is closed for this event
</div>

<?php endif; ?>

</div>

<script>
/* AUTO SCROLL TO BOTTOM */
let chat = document.getElementById("chatBox");
chat.scrollTop = chat.scrollHeight;
</script>

</body>
</html>