<?php
/**
 * Admin Chat Page
 * Allows admins to participate in booking chats.
 */

require_once 'includes/branding.php';
require_once 'includes/config.php';

if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header('Location: login.php');
    exit;
}

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

$pdo = getDBConnection();
$admin_id = $_SESSION['admin_id'];
$admin_name = $_SESSION['admin_name'] ?? 'Administrator';

// Fetch booking info for context
$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
    LEFT JOIN users u ON b.user_id = u.id
    LEFT JOIN drivers d ON b.driver_id = d.id
    WHERE b.id = ?
");
$stmt->execute([$booking_id]);
$booking = $stmt->fetch();

if (!$booking) {
    header('Location: bookings.php');
    exit;
}
?>
<!DOCTYPE html>
<html class="dark" lang="en">
<head>
    <meta charset="utf-8"/>
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <title>Admin 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="includes/tailwind_config.js"></script>
    <link rel="stylesheet" href="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-4xl mx-auto flex items-center justify-between gap-4">
            <div class="flex items-center gap-4">
                <a href="booking_details.php?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-rose-500/10 flex items-center justify-center text-rose-500 border border-rose-500/20">
                    <span class="material-symbols-outlined">admin_panel_settings</span>
                </div>
                <div>
                    <h1 class="font-bold text-clamp-sm">Admin Chat: <?= $booking['reference_number'] ?></h1>
                    <p class="text-[10px] text-slate-500">Client: <?= htmlspecialchars($booking['client_name']) ?> • Driver: <?= htmlspecialchars($booking['driver_name'] ?: 'Not Assigned') ?></p>
                </div>
            </div>
            <div class="hidden sm:block">
                <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-4xl 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-4xl mx-auto flex gap-2">
            <input type="text" id="messageInput" placeholder="Type a message as Administrator..." 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-rose-600 text-white size-12 rounded-xl flex items-center justify-center shadow-lg shadow-rose-600/30 active:scale-95 transition-transform">
                <span class="material-symbols-outlined">send</span>
            </button>
        </form>
    </footer>

    <script src="includes/chat_helper.js"></script>

    <script>
        const bookingId = <?= json_encode($booking_id) ?>;
        const adminId = <?= json_encode($admin_id) ?>;
        const adminName = <?= json_encode($admin_name) ?>;
        const userType = "admin";

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

        // Initialize Chat immediately in database mode (bypassing Firebase)
        if (window.ChatHelper) {
            window.ChatHelper.init({
                bookingId,
                userId: adminId,
                userName: adminName,
                userType,
                chatMessages,
                chatForm,
                messageInput,
                loading,
                appendMessage,
                scrollToBottom,
                useFallback: true, // Bypass Firebase entirely
                onSendNotification: (message) => {
                    fetch('../api/send_chat_notification.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            booking_id: bookingId,
                            message: message,
                            sender_name: adminName,
                            sender_type: userType
                        })
                    }).catch(err => console.error("Notification Error:", err));
                }
            });
        }

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

            // Strict check for "isMe": Must be an admin AND must match the current admin's ID
            const isMe = msg.sender_type === 'admin' && msg.sender_id == adminId;

            const div = document.createElement('div');
            div.className = `flex flex-col ${isMe ? 'items-end' : 'items-start'} group relative`;
            div.id = `msg-${msg.id || Math.random().toString(36).substr(2, 9)}`;

            let badgeColor = "bg-gray-500";
            let bubbleColor = isMe ? 'bg-rose-600 text-white' : 'bg-blue-600 text-white';

            if (msg.sender_type === 'admin') {
                badgeColor = "bg-rose-500";
            } else if (msg.sender_type === 'customer' || msg.sender_type === 'user') {
                badgeColor = "bg-blue-500";
                bubbleColor = isMe ? 'bg-rose-600 text-white' : 'bg-blue-600 text-white';
            } else if (msg.sender_type === 'driver') {
                badgeColor = "bg-emerald-500";
                bubbleColor = isMe ? 'bg-rose-600 text-white' : 'bg-emerald-600 text-white';
            }

            // If it's not me and not a special type, use gray
            if (!isMe && msg.sender_type !== 'customer' && msg.sender_type !== 'user' && msg.sender_type !== 'driver' && msg.sender_type !== 'admin') {
                bubbleColor = 'bg-gray-200 dark:bg-gray-800 text-gray-900 dark:text-white';
            }

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

            let actionMenu = '';
            if (isMe && msg.id) {
                actionMenu = `
                    <div class="flex gap-2 mt-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button onclick="editMessage(${msg.id}, '${escapeHtml(messageText.replace(/'/g, "\\'"))}')" class="text-[10px] text-blue-500 hover:underline flex items-center gap-0.5">
                            <span class="material-symbols-outlined text-[12px]">edit</span> Edit
                        </button>
                        <button onclick="deleteMessage(${msg.id})" class="text-[10px] text-red-500 hover:underline flex items-center gap-0.5">
                            <span class="material-symbols-outlined text-[12px]">delete</span> Delete
                        </button>
                    </div>
                `;
            }

            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="relative max-w-[85%] ${bubbleColor} p-3 rounded-2xl ${isMe ? 'rounded-tr-none' : 'rounded-tl-none'} shadow-sm">
                    <p class="text-sm message-content">${escapeHtml(messageText)}</p>
                    <p class="text-[8px] mt-1 opacity-70 text-right">${formatTime(timestamp)}</p>
                </div>
                ${actionMenu}
            `;
            chatMessages.appendChild(div);
        }

        async function editMessage(id, oldText) {
            const newText = prompt("Edit message:", oldText);
            if (newText === null || newText.trim() === "" || newText === oldText) return;

            try {
                const response = await fetch('../api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'edit_message',
                        message_id: id,
                        message: newText,
                        user_id: adminId,
                        sender_type: 'admin'
                    })
                });
                const data = await response.json();
                if (data.success) {
                    location.reload();
                } else {
                    alert("Error editing message: " + data.error);
                }
            } catch (err) {
                console.error(err);
                alert("Failed to edit message");
            }
        }

        async function deleteMessage(id) {
            if (!confirm("Are you sure you want to delete this message?")) return;

            try {
                const response = await fetch('../api/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'delete_message',
                        message_id: id,
                        user_id: adminId,
                        sender_type: 'admin'
                    })
                });
                const data = await response.json();
                if (data.success) {
                    const el = document.getElementById(`msg-${id}`);
                    if (el) el.remove();
                } else {
                    alert("Error deleting message: " + data.error);
                }
            } catch (err) {
                console.error(err);
                alert("Failed to delete message");
            }
        }

        function scrollToBottom() {
            chatMessages.scrollTop = chatMessages.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 'includes/floating_chat_include.php'; ?>
</body>
</html>
