<?php
require_once '../admin/includes/branding.php';
require_once '../admin/includes/config.php';

if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in']) {
    header('Location: user_authentication.html');
    exit;
}

$booking_id = $_GET['booking_id'] ?? null;
if (!$booking_id) {
    header('Location: my_bookings.php');
    exit;
}

$pdo = getDBConnection();
$user_id = $_SESSION['user_id'];

// Verify user is part of this booking
$stmt = $pdo->prepare("
    SELECT b.*, d.first_name as driver_name, d.last_name as driver_last_name,
           u.first_name as client_name, u.last_name as client_last_name
    FROM bookings b
    LEFT JOIN drivers d ON b.driver_id = d.id
    LEFT JOIN users u ON b.user_id = u.id
    WHERE b.id = ? AND b.user_id = ?
");
$stmt->execute([$booking_id, $user_id]);
$booking = $stmt->fetch();

if (!$booking) {
    header('Location: my_bookings.php');
    exit;
}

$chat_partner_name = $booking['driver_name'] ? ($booking['driver_name'] . ' ' . $booking['driver_last_name']) : 'System Admin';
$user_display_name = $booking['client_name'] . ' ' . $booking['client_last_name'];
?>
<!DOCTYPE html>
<html class="dark" lang="en">
<head>
    <meta charset="utf-8"/>
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <title>Chat - <?= htmlspecialchars(getBrandName()) ?></title>
    <script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet"/>
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap" rel="stylesheet"/>
    <script src="../admin/includes/tailwind_config.js"></script>
    <link rel="stylesheet" href="../admin/includes/responsive.css">
    <style>
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
    </style>
</head>
<body class="bg-background-light dark:bg-background-dark text-gray-900 dark:text-white min-h-screen flex flex-col">
    <header class="bg-background-light/80 dark:bg-background-dark/80 backdrop-blur-md border-b border-gray-200 dark:border-gray-800 p-4 sticky top-0 z-10">
        <div class="max-w-3xl mx-auto flex items-center gap-4">
            <a href="booking_details.php?booking_id=<?= $booking_id ?>" class="text-gray-500 hover:text-primary transition-colors">
                <span class="material-symbols-outlined">arrow_back</span>
            </a>
            <div class="size-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                <span class="material-symbols-outlined">person</span>
            </div>
            <div>
                <h1 class="font-bold text-clamp-sm">Booking Chat (#<?= $booking['reference_number'] ?>)</h1>
                <p class="text-[10px] text-green-500 font-bold uppercase flex items-center gap-1">
                    <span class="size-1.5 rounded-full bg-green-500 animate-pulse"></span>
                    Real-time (Firebase)
                </p>
            </div>
        </div>
    </header>

    <main id="chatMessages" class="flex-1 overflow-y-auto p-4 space-y-4 max-w-3xl mx-auto w-full no-scrollbar pb-24">
        <!-- Messages will be loaded here -->
        <div id="loading" class="flex justify-center py-10">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        </div>
    </main>

    <footer class="p-4 bg-background-light dark:bg-background-dark border-t border-gray-200 dark:border-gray-800 fixed bottom-0 left-0 right-0 z-10">
        <form id="chatForm" class="max-w-3xl mx-auto flex gap-2">
            <input type="text" id="messageInput" placeholder="Type a message..." autocomplete="off" required class="flex-1 bg-gray-100 dark:bg-gray-800 border-none rounded-xl px-4 py-3 focus:ring-2 focus:ring-primary text-sm">
            <button type="submit" class="bg-primary text-white size-12 rounded-xl flex items-center justify-center shadow-lg shadow-primary/30 active:scale-95 transition-transform">
                <span class="material-symbols-outlined">send</span>
            </button>
        </form>
    </footer>

    <!-- Firebase SDK -->
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-database-compat.js"></script>
    <script src="../admin/includes/firebase_config.js"></script>

    <script>
        const bookingId = <?= json_encode($booking_id) ?>;
        const userId = <?= json_encode($user_id) ?>;
        const userName = <?= json_encode($user_display_name) ?>;
        const userType = "customer";

        const chatMessages = document.getElementById('chatMessages');
        const chatForm = document.getElementById('chatForm');
        const messageInput = document.getElementById('messageInput');
        const loading = document.getElementById('loading');

        // Initialize Firebase
        if (typeof firebase !== 'undefined' && firebase.apps.length > 0) {
            const database = firebase.database();
            const chatRef = database.ref('chats/' + bookingId);

            // Connection timeout handling
            const connectionTimeout = setTimeout(() => {
                if (document.getElementById('loading')) {
                    loading.innerHTML = `
                        <div class="text-center p-6 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl">
                            <span class="material-symbols-outlined text-amber-500 text-3xl mb-2">signal_wifi_off</span>
                            <p class="text-xs font-bold text-amber-700 dark:text-amber-400">Connection is taking longer than usual...</p>
                            <p class="text-[10px] text-amber-600 dark:text-amber-500 mt-1">Please check your internet or Firebase configuration.</p>
                            <button onclick="window.location.reload()" class="mt-3 px-4 py-1.5 bg-amber-500 text-white text-[10px] font-bold rounded-lg">Retry Connection</button>
                        </div>
                    `;
                }
            }, 10000); // 10 second timeout

            // Remove loading spinner and handle empty state
            chatRef.once('value').then((snapshot) => {
                clearTimeout(connectionTimeout);
                if (loading) loading.remove();
                if (!snapshot.exists()) {
                    chatMessages.innerHTML = '<div id="no-messages" class="flex flex-col items-center justify-center py-10 text-gray-500"><span class="material-symbols-outlined text-4xl mb-2">chat_bubble_outline</span><p class="text-xs">No messages yet. Start the conversation!</p></div>';
                }
            }).catch(err => {
                clearTimeout(connectionTimeout);
                console.error("Firebase Read Error:", err);
                if (loading) loading.innerHTML = '<div class="text-center text-rose-500 p-4 text-xs font-bold text-balance">Error connecting to Firebase. Please verify your Database URL and Security Rules.</div>';
            });

            // Listen for new messages
            chatRef.on('child_added', (snapshot) => {
                const noMsg = document.getElementById('no-messages');
                if (noMsg) noMsg.remove();
                if (loading) loading.remove();

                const msg = snapshot.val();
                if (msg) {
                    appendMessage(msg);
                    scrollToBottom();
                }
            }, (error) => {
                console.error("Firebase Subscription Error:", error);
            });

            chatForm.onsubmit = (e) => {
                e.preventDefault();
                const message = messageInput.value.trim();
                if (!message) return;

                const newMessage = {
                    sender_id: userId,
                    sender_name: userName,
                    sender_type: userType,
                    message: message,
                    timestamp: firebase.database.ServerValue.TIMESTAMP
                };

                chatRef.push(newMessage).then(() => {
                    messageInput.value = '';
                }).catch(err => {
                    console.error("Firebase Error:", err);
                    alert("Failed to send message. Please check your Firebase configuration.");
                });
            };
        } else {
            loading.innerHTML = '<div class="text-center text-rose-500 p-4 text-xs">Firebase not initialized. Please check your configuration in admin/includes/firebase_config.js</div>';
        }

        function appendMessage(msg) {
            if (!msg || !msg.message) return;

            const isMe = msg.sender_id == userId && msg.sender_type == userType;
            const div = document.createElement('div');
            div.className = `flex flex-col ${isMe ? 'items-end' : 'items-start'}`;

            let badgeColor = "bg-gray-500";
            if (msg.sender_type === 'admin') badgeColor = "bg-rose-500";
            if (msg.sender_type === 'driver') badgeColor = "bg-emerald-500";
            if (msg.sender_type === 'customer') badgeColor = "bg-primary";

            const senderName = msg.sender_name || 'Unknown';
            const messageText = msg.message || '';
            const timestamp = msg.timestamp || Date.now();

            div.innerHTML = `
                <div class="flex items-center gap-2 mb-1 px-1">
                    <span class="text-[9px] font-bold text-gray-500 uppercase">${escapeHtml(senderName)}</span>
                    <span class="${badgeColor} text-white text-[8px] px-1.5 py-0.5 rounded-full font-bold uppercase">${msg.sender_type || 'user'}</span>
                </div>
                <div class="max-w-[85%] ${isMe ? 'bg-primary text-white' : 'bg-gray-200 dark:bg-gray-800 text-gray-900 dark:text-white'} p-3 rounded-2xl ${isMe ? 'rounded-tr-none' : 'rounded-tl-none'} shadow-sm">
                    <p class="text-sm">${escapeHtml(messageText)}</p>
                    <p class="text-[8px] mt-1 opacity-70 text-right">${formatTime(timestamp)}</p>
                </div>
            `;
            chatMessages.appendChild(div);
        }

        function scrollToBottom() {
            chatMessages.scrollTop = chatMessages.scrollHeight;
            window.scrollTo(0, document.body.scrollHeight);
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function formatTime(timestamp) {
            const date = new Date(timestamp);
            return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        }
    </script>
    <?php include '../admin/includes/floating_chat_include.php'; ?>
</body>
</html>
