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

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

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

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

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

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

$user_display_name = $booking['driver_name'] . ' ' . $booking['driver_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>Driver 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="index.php" 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" onsubmit="return false;" action="javascript:void(0);">
            <input type="hidden" name="booking_id" value="<?= htmlspecialchars($booking_id) ?>">
            <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" id="sendButton" 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 src="../admin/includes/chat_helper.js"></script>

    <script>
        // Global variables
        const bookingId = "<?= $booking_id ?>";
        const userId = "<?= $user_id ?>";
        const userName = "<?= htmlspecialchars($user_display_name) ?>";
        const userType = "driver";
        let chatMessages, chatForm, messageInput, loading;

        document.addEventListener('DOMContentLoaded', function() {
            chatMessages = document.getElementById('chatMessages');
            chatForm = document.getElementById('chatForm');
            messageInput = document.getElementById('messageInput');
            loading = document.getElementById('loading');

            console.log("[Chat Page] Driver chat initializing for booking:", bookingId);

            if (typeof ChatHelper === 'undefined') {
                console.error("[Chat Page] ChatHelper not loaded!");
                if (loading) {
                    loading.innerHTML = `
                        <div class="text-center p-6 bg-red-50 border border-red-200 rounded-xl">
                            <p class="text-red-700 font-bold">Chat Error</p>
                            <p class="text-red-600 text-sm mt-1">Chat helper failed to load. Check console.</p>
                        </div>
                    `;
                }
            } else {
                ChatHelper.init({
                    bookingId, userId, userName, userType,
                    chatMessages, chatForm, messageInput, loading,
                    appendMessage, scrollToBottom
                });
            }
        });

        function appendMessage(msg) {
            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";

            div.innerHTML = `
                <div class="flex items-center gap-2 mb-1 px-1">
                    <span class="text-[9px] font-bold text-gray-500 uppercase">${escapeHtml(msg.sender_name)}</span>
                    <span class="${badgeColor} text-white text-[8px] px-1.5 py-0.5 rounded-full font-bold uppercase">${msg.sender_type}</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(msg.message)}</p>
                    <p class="text-[8px] mt-1 opacity-70 text-right">${formatTime(msg.timestamp)}</p>
                </div>
            `;
            if (chatMessages) chatMessages.appendChild(div);
        }

        function scrollToBottom() {
            if (chatMessages) {
                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>
</body>
</html>
