<?php
require_once('../includes/functions.php');
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') exit('Unauthorized');

$messages = [];
if (file_exists(__DIR__ . '/../data/simple_chat.log')) {
    $lines = file(__DIR__ . '/../data/simple_chat.log', FILE_IGNORE_NEW_LINES);
    $messages = array_reverse(array_slice(array_reverse($lines), -50));
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Simple Chat</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body style="font-family: monospace; max-width:800px; margin:20px auto; padding:0 20px;">
    <h2>Admin Chat (Simple)</h2>
    <div id="chat" style="height:400px; overflow-y:auto; border:1px solid #ccc; padding:10px; background:#faf3e8;">
        <?php foreach($messages as $line): list($ts, $name, $msg) = explode('|', $line, 3); ?>
            <p><strong><?= htmlspecialchars($name) ?>:</strong> <?= htmlspecialchars($msg) ?> <small><?= $ts ?></small></p>
        <?php endforeach; ?>
    </div>
    <form id="messageForm">
        <input type="text" id="message" placeholder="Type message..." style="width:80%; padding:8px;" autocomplete="off">
        <button type="submit">Send</button>
    </form>
    <p><a href="dashboard.php">Back</a></p>
    <script>
        const chatDiv = document.getElementById('chat');
        const messageInput = document.getElementById('message');
        const messageForm = document.getElementById('messageForm');

        function fetchMessages() {
            fetch('../simple_chat_api.php?action=fetch')
                .then(res => res.json())
                .then(data => {
                    if (data.messages) {
                        chatDiv.innerHTML = data.messages.map(msg => {
                            const [ts, name, text] = msg.split('|');
                            return `<p><strong>${escapeHtml(name)}:</strong> ${escapeHtml(text)} <small>${ts}</small></p>`;
                        }).join('');
                        chatDiv.scrollTop = chatDiv.scrollHeight;
                    }
                });
        }

        messageForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const message = messageInput.value.trim();
            if (!message) return;
            fetch('../simple_chat_api.php?action=send', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `message=${encodeURIComponent(message)}`
            }).then(() => {
                messageInput.value = '';
                fetchMessages();
            });
        });

        function escapeHtml(str) {
            return str.replace(/[&<>]/g, function(m) {
                if (m === '&') return '&amp;';
                if (m === '<') return '&lt;';
                if (m === '>') return '&gt;';
                return m;
            });
        }

        setInterval(fetchMessages, 3000);
        fetchMessages();
    </script>
</body>
</html>