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

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

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

// Handle message sending via AJAX
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;
}

// Fetch messages for initial load
$stmt = $db->prepare("SELECT * FROM messages WHERE user_id = ? ORDER BY created_at ASC");
$stmt->execute([$user_id]);
$messages = $stmt->fetchAll();
?>
<!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; }
        #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; position: relative; }
        .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; transition: 0.2s; }
        button:hover { background: #00f2fe; }
    </style>
</head>
<body>

<div id="chat-box">
    <?php foreach ($messages as $m): ?>
        <div class="msg <?php echo $m['sender']; ?>">
            <?php echo nl2br(htmlspecialchars($m['message'])); ?>
            <span class="msg-time"><?php echo date('H:i', strtotime($m['created_at'])); ?></span>
        </div>
    <?php endforeach; ?>
</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 chatForm = document.getElementById('chat-form');
    const msgInput = document.getElementById('msg-input');
    
    chatBox.scrollTop = chatBox.scrollHeight;

    chatForm.onsubmit = async (e) => {
        e.preventDefault();
        const msg = msgInput.value.trim();
        if (!msg) return;

        // Optimistic UI update
        const msgDiv = document.createElement('div');
        msgDiv.className = 'msg user';
        msgDiv.innerHTML = msg.replace(/\n/g, '<br>') + '<span class="msg-time">' + new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}) + '</span>';
        chatBox.appendChild(msgDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
        msgInput.value = '';

        const formData = new FormData();
        formData.append('message', msg);
        await fetch('chat_iframe.php', { method: 'POST', body: formData });
    };

    // Auto refresh for new messages from admin
    let lastMsgCount = <?php echo count($messages); ?>;
    setInterval(async () => {
        const res = await fetch('api/get_messages.php');
        const data = await res.json();
        if (data.count > lastMsgCount) {
            location.reload();
        }
    }, 3000);
</script>

</body>
</html>
