<?php
session_start();
require_once 'db/config.php';

if (!isset($_SESSION['user_id'])) {
    die("Please login first.");
}

$user_id = $_SESSION['user_id'];
$db = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    $msg = trim($_POST['message']);
    if ($msg !== '') {
        $stmt = $db->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', ?)");
        $stmt->execute([$user_id, $msg]);
        echo json_encode(['success' => true]);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { margin: 0; padding: 0; font-family: 'Inter', sans-serif; background: #161a1e; color: white; height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
        #chat-box { flex: 1; overflow-y: auto; padding: 15px; display: flex; flex-direction: column; gap: 12px; scroll-behavior: smooth; }
        .msg { max-width: 80%; padding: 10px 14px; border-radius: 12px; font-size: 14px; line-height: 1.4; }
        .msg.user { align-self: flex-end; background: #4facfe; color: white; border-bottom-right-radius: 2px; }
        .msg.admin { align-self: flex-start; background: #2b3139; color: #EAECEF; border-bottom-left-radius: 2px; }
        .msg-time { font-size: 10px; opacity: 0.5; margin-top: 4px; display: block; }
        .chat-input-area { padding: 12px; background: #1e2329; border-top: 1px solid #2b3139; display: flex; gap: 10px; }
        input { flex: 1; background: #0b0e11; border: 1px solid #2b3139; border-radius: 8px; padding: 10px 12px; color: white; outline: none; }
        button { background: #4facfe; border: none; width: 40px; height: 40px; border-radius: 8px; color: white; cursor: pointer; display: flex; align-items: center; justify-content: center; }
    </style>
</head>
<body>

<div id="chat-box"></div>

<form id="chat-form" class="chat-input-area">
    <input type="text" id="msg-input" placeholder="Type a message..." autocomplete="off">
    <button type="submit"><i class="fas fa-paper-plane"></i></button>
</form>

<script>
    const chatBox = document.getElementById('chat-box');
    const msgInput = document.getElementById('msg-input');
    
    async function loadMessages() {
        try {
            const resp = await fetch('api/get_messages.php');
            const res = await resp.json();
            if (res.success) {
                let html = '';
                res.data.forEach(m => {
                    html += `
                        <div class="msg ${m.sender}">
                            ${m.message.replace(/\n/g, '<br>')}
                            <span class="msg-time">${new Date(m.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
                        </div>
                    `;
                });
                const isAtBottom = chatBox.scrollHeight - chatBox.scrollTop <= chatBox.clientHeight + 50;
                chatBox.innerHTML = html;
                if (isAtBottom) chatBox.scrollTop = chatBox.scrollHeight;
            }
        } catch (e) {}
    }

    document.getElementById('chat-form').onsubmit = async (e) => {
        e.preventDefault();
        const msg = msgInput.value.trim();
        if (!msg) return;
        msgInput.value = '';
        const formData = new FormData();
        formData.append('message', msg);
        await fetch('chat_iframe.php', { method: 'POST', body: formData });
        loadMessages();
    };

    loadMessages();
    setInterval(loadMessages, 2000);
</script>
</body>
</html>