<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="row justify-content-center">
    <div class="col-lg-10">
        <div class="card border-0 shadow-sm" style="border-radius: 12px; overflow: hidden;">
            <!-- Chat Room Header -->
            <div class="card-header bg-white border-0 p-4 border-bottom border-light">
                <div class="d-flex align-items-center justify-content-between flex-wrap gap-3">
                    <div class="d-flex align-items-center gap-3">
                        <a href="/siswa/counseling" class="btn btn-light btn-sm text-secondary px-2" style="border-radius: 6px;">
                            <i class="bi bi-chevron-left"></i> Kembali
                        </a>
                        <div>
                            <div class="d-flex align-items-center gap-2 mb-1">
                                <h5 class="fw-bold text-dark mb-0"><?= esc($ticket['subject']) ?></h5>
                                <span class="badge bg-secondary bg-opacity-10 text-secondary" style="font-size: 0.7rem;"><?= esc(get_counseling_category_label($ticket['category'])) ?></span>
                            </div>
                            <small class="text-muted d-block">
                                <i class="bi bi-person-fill me-1"></i>Dengan Guru: <strong><?= esc($ticket['teacher_name']) ?></strong>
                                <span class="mx-2">•</span>
                                <i class="bi bi-shield-lock-fill me-1"></i>Sifat: <?= (int)$ticket['is_anonymous'] === 1 ? '<span class="text-danger">Anonim</span>' : '<span class="text-success">Terbuka</span>' ?>
                            </small>
                        </div>
                    </div>
                    <div>
                        <span class="badge px-3 py-2 rounded-pill <?= $ticket['status'] === 'open' ? 'bg-success bg-opacity-10 text-success' : 'bg-secondary bg-opacity-10 text-secondary' ?>" style="font-weight: 600;">
                            <i class="bi <?= $ticket['status'] === 'open' ? 'bi-chat-left-dots-fill' : 'bi-check-circle-fill' ?> me-1"></i>
                            <?= $ticket['status'] === 'open' ? 'Sesi Aktif' : 'Sesi Selesai' ?>
                        </span>
                    </div>
                </div>
            </div>

            <!-- Chat Messages Container -->
            <div class="card-body p-4 bg-light" id="chat-box" style="height: 480px; overflow-y: auto; display: flex; flex-direction: column; gap: 15px;">
                <?php if (empty($messages)): ?>
                    <div class="text-center my-auto py-5 text-muted">
                        <i class="bi bi-chat-left-quote fs-1 mb-2 opacity-50 text-primary"></i>
                        <p class="mb-0 small">Belum ada obrolan. Silakan kirim pesan di bawah.</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($messages as $msg): ?>
                        <div class="msg-bubble" data-id="<?= $msg['id'] ?>">
                            <?php 
                            $isSystem = (strpos($msg['message'], '[Sistem]') === 0 || strpos($msg['message'], '[Rujukan]') === 0);
                            $isSenderMe = ($msg['sender_role'] === 'student');
                            ?>
                            
                            <?php if ($isSystem): ?>
                                <!-- System/Notice Message -->
                                <div class="d-flex justify-content-center my-2">
                                    <span class="bg-warning bg-opacity-10 text-warning border border-warning border-opacity-10 px-3 py-1.5 rounded text-center small" style="max-width: 80%; font-weight: 500;">
                                        <i class="bi bi-info-circle-fill me-1"></i><?= esc(str_replace(['[Sistem]', '[Rujukan]'], '', $msg['message'])) ?>
                                    </span>
                                </div>
                            <?php elseif ($isSenderMe): ?>
                                <!-- My Message (Right) -->
                                <div class="d-flex justify-content-end align-items-end gap-2 mb-3">
                                    <div class="text-end" style="max-width: 70%;">
                                        <div class="p-3 text-white shadow-sm" style="background-color: #6c5ce7; border-radius: 16px 16px 4px 16px; text-align: left; font-size: 0.95rem; word-break: break-word;">
                                            <?= nl2br(esc($msg['message'])) ?>
                                        </div>
                                        <small class="text-muted" style="font-size: 0.68rem; margin-top: 4px; display: block;">
                                            <?= date('H:i', strtotime($msg['created_at'])) ?>
                                        </small>
                                    </div>
                                </div>
                            <?php else: ?>
                                <!-- Teacher Message (Left) -->
                                <div class="d-flex justify-content-start align-items-end gap-2 mb-3">
                                    <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center shadow-sm" style="width: 36px; height: 36px; min-width: 36px; font-weight: bold; font-size: 0.85rem; background: linear-gradient(135deg, #00b894 0%, #00cec9 100%);">
                                        G
                                    </div>
                                    <div style="max-width: 70%;">
                                        <div class="bg-white p-3 border border-light shadow-sm text-dark" style="border-radius: 16px 16px 16px 4px; font-size: 0.95rem; word-break: break-word;">
                                            <?= nl2br(esc($msg['message'])) ?>
                                        </div>
                                        <small class="text-muted" style="font-size: 0.68rem; margin-top: 4px; display: block; margin-left: 2px;">
                                            <?= date('H:i', strtotime($msg['created_at'])) ?>
                                        </small>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Message Input Area -->
            <div class="card-footer bg-white border-0 p-4 border-top border-light">
                <?php if ($ticket['status'] === 'closed'): ?>
                    <div class="alert alert-secondary border-0 text-center mb-0" style="border-radius: 8px;">
                        <i class="bi bi-lock-fill me-2"></i>Sesi bimbingan/pengaduan ini telah **SELESAI** dan ditutup oleh Guru. Jika ada keluhan baru, silakan buat tiket baru.
                    </div>
                <?php else: ?>
                    <form action="/siswa/counseling/send-message/<?= $ticket['id'] ?>" method="POST" class="d-flex gap-2 align-items-center">
                        <?= csrf_field() ?>
                        <input type="text" name="message" id="chat-input" class="form-control" placeholder="Tulis pesan bimbingan/tanggapan Anda di sini..." required style="border-radius: 8px; padding: 0.75rem 1rem;">
                        <button type="submit" class="btn btn-primary px-4 py-2.5 fw-bold" style="border-radius: 8px;">
                            <i class="bi bi-send-fill me-1"></i>Kirim
                        </button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        var chatBox = document.getElementById("chat-box");
        chatBox.scrollTop = chatBox.scrollHeight;

        // Polling variables
        var ticketId = <?= (int)$ticket['id'] ?>;
        var lastMessageId = 0;

        // Function to update last message ID from DOM
        function updateLastMessageId() {
            var bubbles = document.querySelectorAll(".msg-bubble");
            bubbles.forEach(function(b) {
                var id = parseInt(b.getAttribute("data-id"));
                if (id > lastMessageId) {
                    lastMessageId = id;
                }
            });
        }
        updateLastMessageId();

        // Polling function
        function pollMessages() {
            fetch("/siswa/counseling/get-new-messages/" + ticketId + "/" + lastMessageId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 1. Process new messages
                        if (data.messages && data.messages.length > 0) {
                            var emptyState = chatBox.querySelector(".my-auto");
                            if (emptyState) {
                                emptyState.remove();
                            }

                            data.messages.forEach(function(msg) {
                                // Double check to avoid duplication
                                if (document.querySelector('.msg-bubble[data-id="' + msg.id + '"]')) {
                                    return;
                                }

                                var html = '<div class="msg-bubble" data-id="' + msg.id + '">';
                                var isSystem = (msg.message.indexOf('[Sistem]') === 0 || msg.message.indexOf('[Rujukan]') === 0);
                                var isSenderMe = (msg.sender_role === 'student');

                                if (isSystem) {
                                    var cleanMsg = msg.message.replace('[Sistem]', '').replace('[Rujukan]', '');
                                    html += '  <div class="d-flex justify-content-center my-2">' +
                                            '    <span class="bg-warning bg-opacity-10 text-warning border border-warning border-opacity-10 px-3 py-1.5 rounded text-center small" style="max-width: 80%; font-weight: 500;">' +
                                            '      <i class="bi bi-info-circle-fill me-1"></i>' + cleanMsg +
                                            '    </span>' +
                                            '  </div>';
                                } else if (isSenderMe) {
                                    html += '  <div class="d-flex justify-content-end align-items-end gap-2 mb-3">' +
                                            '    <div class="text-end" style="max-width: 70%;">' +
                                            '      <div class="p-3 text-white shadow-sm" style="background-color: #6c5ce7; border-radius: 16px 16px 4px 16px; text-align: left; font-size: 0.95rem; word-break: break-word;">' +
                                            msg.message.replace(/\n/g, '<br>') +
                                            '      </div>' +
                                            '      <small class="text-muted" style="font-size: 0.68rem; margin-top: 4px; display: block;">' +
                                            new Date(msg.created_at).toLocaleTimeString('id-ID', {hour: '2-digit', minute:'2-digit'}) +
                                            '      </small>' +
                                            '    </div>' +
                                            '  </div>';
                                } else {
                                    html += '  <div class="d-flex justify-content-start align-items-end gap-2 mb-3">' +
                                            '    <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center shadow-sm" style="width: 36px; height: 36px; min-width: 36px; font-weight: bold; font-size: 0.85rem; background: linear-gradient(135deg, #00b894 0%, #00cec9 100%);">G</div>' +
                                            '    <div style="max-width: 70%;">' +
                                            '      <div class="bg-white p-3 border border-light shadow-sm text-dark" style="border-radius: 16px 16px 16px 4px; font-size: 0.95rem; word-break: break-word;">' +
                                            msg.message.replace(/\n/g, '<br>') +
                                            '      </div>' +
                                            '      <small class="text-muted" style="font-size: 0.68rem; margin-top: 4px; display: block; margin-left: 2px;">' +
                                            new Date(msg.created_at).toLocaleTimeString('id-ID', {hour: '2-digit', minute:'2-digit'}) +
                                            '      </small>' +
                                            '    </div>' +
                                            '  </div>';
                                }
                                html += '</div>';

                                chatBox.insertAdjacentHTML('beforeend', html);
                                lastMessageId = msg.id;
                            });

                            chatBox.scrollTop = chatBox.scrollHeight;
                        }

                        // 2. Handle session closure dynamically
                        if (data.status === 'closed') {
                            var form = document.querySelector(".card-footer form");
                            if (form) {
                                var alertHtml = '<div class="alert alert-secondary border-0 text-center mb-0" style="border-radius: 8px;">' +
                                                '  <i class="bi bi-lock-fill me-2"></i>Sesi bimbingan/pengaduan ini telah **SELESAI** dan ditutup oleh Guru. Jika ada keluhan baru, silakan buat tiket baru.' +
                                                '</div>';
                                form.parentNode.innerHTML = alertHtml;
                                
                                // Update header badge to "Closed"
                                var badge = document.querySelector(".badge.bg-success");
                                if (badge) {
                                    badge.className = "badge px-3 py-2 rounded-pill bg-secondary bg-opacity-10 text-secondary";
                                    badge.innerHTML = '<i class="bi bi-check-circle-fill me-1"></i>Sesi Selesai';
                                }
                            }
                        }
                    }
                })
                .catch(err => console.error("Error fetching messages:", err));
        }

        // Poll every 3 seconds
        setInterval(pollMessages, 3000);
    });
</script>

<?= $this->endSection() ?>
