<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PBM DATA HUB - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }

        .dark .card {
            background-color: #1f2937;
        }

        .sidebar {
            transition: transform 0.3s ease-in-out;
        }

        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .sidebar.sidebar-visible {
                transform: translateX(0);
            }
        }
    </style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100">
    <!-- Navbar -->
    <nav class="bg-white dark:bg-gray-800 shadow-md fixed w-full z-10">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex items-center justify-between h-16">
                <div class="flex items-center">
                    <button id="sidebar-toggle" class="text-gray-500 hover:text-gray-600 focus:outline-none focus:text-gray-600 dark:text-gray-400 dark:hover:text-gray-300">
                        <span class="material-icons">menu</span>
                    </button>
                    <h1 class="ml-4 text-xl font-bold"></h1>
                </div>
                <div class="flex items-center space-x-4">
                    <span id="user-count" class="bg-blue-100 text-blue-800 text-xs font-medium px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">Users: 0</span>
                    <span id="order-count" class="bg-green-100 text-green-800 text-xs font-medium px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">Orders: 0</span>
                    <span id="message-count" class="bg-yellow-100 text-yellow-800 text-xs font-medium px-2.5 py-0.5 rounded dark:bg-yellow-900 dark:text-yellow-300">MSG: 0</span>
                    <button id="dark-mode-toggle" class="text-gray-500 hover:text-gray-600 focus:outline-none focus:text-gray-600 dark:text-gray-400 dark:hover:text-gray-300">
                        <span class="material-icons">dark_mode</span>
                    </button>
                    <button id="logout-btn" class="text-gray-500 hover:text-gray-600 focus:outline-none focus:text-gray-600 dark:text-gray-400 dark:hover:text-gray-300">
                        <span class="material-icons">logout</span>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="flex pt-16">
        <!-- Sidebar -->
        <aside id="sidebar" class="bg-white dark:bg-gray-800 w-64 min-h-screen fixed left-0 top-16 z-20 sidebar">
            <nav class="mt-6">
                <ul>
                    <li>
                        <button id="dashboard-btn" class="w-full text-left px-4 py-2 flex items-center text-gray-700 hover:bg-gray-200 dark:text-gray-300 dark:hover:bg-gray-700">
                            <span class="material-icons mr-3">dashboard</span>
                            Dashboard
                        </button>
                    </li>
                    <li>
                        <button id="users-btn" class="w-full text-left px-4 py-2 flex items-center text-gray-700 hover:bg-gray-200 dark:text-gray-300 dark:hover:bg-gray-700">
                            <span class="material-icons mr-3">people</span>
                            Users
                        </button>
                    </li>
                    <li>
                        <button id="orders-btn" class="w-full text-left px-4 py-2 flex items-center text-gray-700 hover:bg-gray-200 dark:text-gray-300 dark:hover:bg-gray-700">
                            <span class="material-icons mr-3">receipt</span>
                            Orders
                        </button>
                    </li>
                    <li>
                        <button id="messages-btn" class="w-full text-left px-4 py-2 flex items-center text-gray-700 hover:bg-gray-200 dark:text-gray-300 dark:hover:bg-gray-700">
                            <span class="material-icons mr-3">message</span>
                            Messages
                        </button>
                    </li>
                </ul>
            </nav>
        </aside>

        <!-- Main Content -->
        <main id="main-content" class="flex-1 p-4 sm:ml-64">
            <!-- Content will be dynamically loaded here -->
        </main>
    </div>

    <!-- Login Modal -->
    <div id="login-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white dark:bg-gray-800 p-8 rounded-lg shadow-xl w-full max-w-md">
            <h2 class="text-2xl font-bold mb-6 text-gray-900 dark:text-white">Admin Login</h2>
            <form id="login-form">
                <div class="mb-4">
                    <label for="email" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Email</label>
                    <input type="email" id="email" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                </div>
                <div class="mb-6">
                    <label for="password" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Password</label>
                    <input type="password" id="password" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                </div>
                <button type="submit" class="w-full bg-indigo-600 text-white font-bold py-2 px-4 rounded hover:bg-indigo-700 focus:outline-none focus:shadow-outline">Login</button>
            </form>
        </div>
    </div>

    <!-- Edit Modal -->
    <div id="edit-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white dark:bg-gray-800 p-8 rounded-lg shadow-xl w-full max-w-md">
            <h2 id="modal-title" class="text-2xl font-bold mb-6 text-gray-900 dark:text-white"></h2>
            <div id="modal-content"></div>
            <div class="flex justify-end mt-6">
                <button id="modal-cancel" class="bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded hover:bg-gray-400 mr-2">Cancel</button>
                <button id="modal-save" class="bg-indigo-600 text-white font-bold py-2 px-4 rounded hover:bg-indigo-700">Save</button>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.js"></script>
    <script type="module">
        // Import the functions you need from the SDKs you need
        import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.1/firebase-app.js";
        import { getAuth, signInWithEmailAndPassword, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/9.22.1/firebase-auth.js";
        import { getDatabase, ref, get, query, orderByChild, update, remove } from "https://www.gstatic.com/firebasejs/9.22.1/firebase-database.js";

        // Your web app's Firebase configuration
        const firebaseConfig = {
            apiKey: "AIzaSyCf1FHMBVFptV9avPDjpP8C8U5bRe0qSEU",
    authDomain: "pbmdatahub.firebaseapp.com",
    projectId: "pbmdatahub",
    storageBucket: "pbmdatahub.firebasestorage.app",
    messagingSenderId: "159205015057",
    appId: "1:159205015057:web:a973a7887f35bef9697bb0"
        };

        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
        const auth = getAuth(app);
        const database = getDatabase(app);

        // Initialize Notyf
        const notyf = new Notyf({
            duration: 3000,
            position: {x: 'right', y: 'top'},
            types: [
                {
                    type: 'success',
                    background: '#10B981',
                    icon: {
                        className: 'material-icons',
                        tagName: 'span',
                        text: 'check_circle'
                    }
                },
                {
                    type: 'error',
                    background: '#EF4444',
                    icon: {
                        className: 'material-icons',
                        tagName: 'span',
                        text: 'error'
                    }
                }
            ]
        });

        // DOM Elements
        const loginModal = document.getElementById('login-modal');
        const loginForm = document.getElementById('login-form');
        const logoutBtn = document.getElementById('logout-btn');
        const sidebarToggle = document.getElementById('sidebar-toggle');
        const sidebar = document.getElementById('sidebar');
        const mainContent = document.getElementById('main-content');
        const modal = document.getElementById('edit-modal');
        const modalTitle = document.getElementById('modal-title');
        const modalContent = document.getElementById('modal-content');
        const modalCancel = document.getElementById('modal-cancel');
        const modalSave = document.getElementById('modal-save');
        const darkModeToggle = document.getElementById('dark-mode-toggle');

        // Navbar stat elements
        const userCount = document.getElementById('user-count');
        const orderCount = document.getElementById('order-count');
        const messageCount = document.getElementById('message-count');

        // Dark mode functionality
        let isDarkMode = localStorage.getItem('darkMode') === 'true';
        updateDarkMode();

        darkModeToggle.addEventListener('click', () => {
            isDarkMode = !isDarkMode;
            localStorage.setItem('darkMode', isDarkMode);
            updateDarkMode();
        });

        function updateDarkMode() {
            if (isDarkMode) {
                document.documentElement.classList.add('dark');
                darkModeToggle.innerHTML = '<span class="material-icons">light_mode</span>';
            } else {
                document.documentElement.classList.remove('dark');
                darkModeToggle.innerHTML = '<span class="material-icons">dark_mode</span>';
            }
        }

        // Sidebar toggle functionality
        sidebarToggle.addEventListener('click', () => {
            sidebar.classList.toggle('sidebar-visible');
        });

        // Authentication state observer
        onAuthStateChanged(auth, (user) => {
            if (user) {
                loginModal.classList.add('hidden');
                sidebar.classList.remove('hidden');
                loadDashboard();
                updateNavbarStats();
            } else {
                loginModal.classList.remove('hidden');
                sidebar.classList.add('hidden');
                mainContent.innerHTML = '';
            }
        });

        // Login form submission
        loginForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;
            signInWithEmailAndPassword(auth, email, password)
                .then(() => {
                    notyf.success('Logged in successfully');
                })
                .catch((error) => {
                    notyf.error('Login failed: ' + error.message);
                });
        });

        // Logout functionality
        logoutBtn.addEventListener('click', () => {
            signOut(auth).then(() => {
                notyf.success('Logged out successfully');
            }).catch((error) => {
                notyf.error('Logout failed: ' + error.message);
            });
        });

        // Navigation functionality
        document.getElementById('dashboard-btn').addEventListener('click', loadDashboard);
        document.getElementById('users-btn').addEventListener('click', loadUsers);
        document.getElementById('orders-btn').addEventListener('click', loadOrders);
        document.getElementById('messages-btn').addEventListener('click', loadMessages);

        // Modal functionality
        modalCancel.addEventListener('click', () => {
            modal.classList.add('hidden');
        });

        function showLoading(elementId) {
            const element = document.getElementById(elementId);
            element.innerHTML = '<div class="flex justify-center items-center h-64"><div class="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div></div>';
        }

        function updateNavbarStats() {
            Promise.all([
                get(ref(database, 'users')),
                get(ref(database, 'orders')),
                get(ref(database, 'support_messages'))
            ]).then(([usersSnapshot, ordersSnapshot, messagesSnapshot]) => {
                userCount.textContent = `Users: ${usersSnapshot.size}`;
                orderCount.textContent = `Orders: ${ordersSnapshot.size}`;
                messageCount.textContent = `Messages: ${messagesSnapshot.size}`;
            }).catch(error => {
                console.error('Error updating navbar stats:', error);
            });
        }

        function loadDashboard() {
            showLoading('main-content');

            Promise.all([
                get(ref(database, 'users')),
                get(ref(database, 'orders')),
                get(ref(database, 'support_messages'))
            ]).then(([usersSnapshot, ordersSnapshot, messagesSnapshot]) => {
                const totalUsers = usersSnapshot.size;
                const totalOrders = ordersSnapshot.size;
                const totalRevenue = Object.values(ordersSnapshot.val() || {}).reduce((sum, order) => sum + order.price, 0);
                const totalMessages = messagesSnapshot.size;

                const dashboardHtml = `
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
                        <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">Total Users</h3>
                            <p class="text-3xl font-bold text-blue-600 dark:text-blue-400">${totalUsers}</p>
                        </div>
                        <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">Total Orders</h3>
                            <p class="text-3xl font-bold text-green-600 dark:text-green-400">${totalOrders}</p>
                        </div>
                        <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">Total Revenue</h3>
                            <p class="text-3xl font-bold text-yellow-600 dark:text-yellow-400">GHS ${totalRevenue.toFixed(2)}</p>
                        </div>
                        <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">Total Messages</h3>
                            <p class="text-3xl font-bold text-purple-600 dark:text-purple-400">${totalMessages}</p>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                        <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Recent Orders</h3>
                            <canvas id="ordersChart"></canvas>
                        </div>
                        <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">User Growth</h3>
                            <canvas id="userGrowthChart"></canvas>
                        </div>
                    </div>
                `;

                mainContent.innerHTML = dashboardHtml;

                // Create charts
                createOrdersChart(ordersSnapshot.val());
                createUserGrowthChart(usersSnapshot.val());

                updateNavbarStats();
            }).catch((error) => {
                console.error('Error fetching dashboard data:', error);
                notyf.error('Error loading dashboard data');
            });
        }

        function createOrdersChart(orders) {
            const ctx = document.getElementById('ordersChart').getContext('2d');
            const orderDates = Object.values(orders || {}).map(order => new Date(order.timestamp).toLocaleDateString());
            const orderCounts = {};
            orderDates.forEach(date => {
                orderCounts[date] = (orderCounts[date] || 0) + 1;
            });

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: Object.keys(orderCounts),
                    datasets: [{
                        label: 'Orders',
                        data: Object.values(orderCounts),
                        borderColor: 'rgb(75, 192, 192)',
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1
                            }
                        }
                    }
                }
            });
        }

        function createUserGrowthChart(users) {
            const ctx = document.getElementById('userGrowthChart').getContext('2d');
            const userDates = Object.values(users || {}).map(user => new Date(user.createdAt).toLocaleDateString());
            const userCounts = {};
            userDates.forEach(date => {
                userCounts[date] = (userCounts[date] || 0) + 1;
            });

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: Object.keys(userCounts),
                    datasets: [{
                        label: 'New Users',
                        data: Object.values(userCounts),
                        borderColor: 'rgb(153, 102, 255)',
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1
                            }
                        }
                    }
                }
            });
        }

        function loadUsers() {
            showLoading('main-content');

            get(ref(database, 'users')).then((snapshot) => {
                let usersHtml = `
                    <div class="mb-4 flex flex-col sm:flex-row justify-between items-center">
                        <input type="text" id="user-search" placeholder="Search users..." class="w-full sm:w-64 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white mb-2 sm:mb-0">
                        <select id="user-sort" class="w-full sm:w-48 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            <option value="name">Sort by Name</option>
                            <option value="email">Sort by Email</option>
                            <option value="createdAt">Sort by Date Joined</option>
                        </select>
                    </div>
                    <div id="users-container" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                `;
                
                if (snapshot.exists()) {
                    snapshot.forEach((childSnapshot) => {
                        const user = childSnapshot.val();
                        const userId = childSnapshot.key;
                        usersHtml += `
                            <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md user-card" data-name="${user.name.toLowerCase()}" data-email="${user.email.toLowerCase()}">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">${user.name}</h3>
                                <p class="text-gray-600 dark:text-gray-400 mb-1">Email: ${user.email}</p>
                                <p class="text-gray-600 dark:text-gray-400 mb-1">Phone: ${user.phone}</p>
                                <p class="text-gray-600 dark:text-gray-400 mb-2">Agent Status: ${user.agentPortalActive ? 'Active' : 'Inactive'}</p>
                                <div class="flex justify-end">
                                    <button onclick="editUser('${userId}')" class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600 mr-2">Edit</button>
                                    <button onclick="deleteUser('${userId}')" class="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600">Delete</button>
                                </div>
                            </div>
                        `;
                    });
                } else {
                    usersHtml += '<p class="text-gray-600 dark:text-gray-400">No users found.</p>';
                }
                usersHtml += '</div>';
                mainContent.innerHTML = usersHtml;

                // Add event listeners for search and sort
                document.getElementById('user-search').addEventListener('input', filterUsers);
                document.getElementById('user-sort').addEventListener('change', sortUsers);

                updateNavbarStats();
            }).catch((error) => {
                console.error('Error fetching users:', error);
                notyf.error('Error loading users');
            });
        }

        function filterUsers() {
            const searchTerm = document.getElementById('user-search').value.toLowerCase();
            const userCards = document.querySelectorAll('.user-card');

            userCards.forEach(card => {
                const name = card.dataset.name;
                const email = card.dataset.email;
                if (name.includes(searchTerm) || email.includes(searchTerm)) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        }

        function sortUsers() {
            const sortBy = document.getElementById('user-sort').value;
            const usersContainer = document.getElementById('users-container');
            const userCards = Array.from(usersContainer.children);

            userCards.sort((a, b) => {
                const aValue = a.querySelector(`[data-${sortBy}]`).dataset[sortBy];
                const bValue = b.querySelector(`[data-${sortBy}]`).dataset[sortBy];
                return aValue.localeCompare(bValue);
            });

            userCards.forEach(card => usersContainer.appendChild(card));
        }

        function loadOrders() {
            showLoading('main-content');

            get(ref(database, 'orders')).then((snapshot) => {
                let ordersHtml = `
                    <div class="mb-4 flex flex-col sm:flex-row justify-between items-center">
                        <input type="text" id="order-search" placeholder="Search orders..." class="w-full sm:w-64 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white mb-2 sm:mb-0">
                        <select id="order-sort" class="w-full sm:w-48 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            <option value="timestamp">Sort by Date</option>
                            <option value="price">Sort by Price</option>
                            <option value="status">Sort by Status</option>
                        </select>
                    </div>
                    <div id="orders-container" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                `;
                
                if (snapshot.exists()) {
                    snapshot.forEach((childSnapshot) => {
                        const order = childSnapshot.val();
                        const orderId = childSnapshot.key;
                        ordersHtml += `
                            <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md order-card" data-timestamp="${order.timestamp}" data-price="${order.price}" data-status="${order.status || 'Pending'}">
                                <p class="text-gray-600 dark:text-gray-400 mb-1">Date: ${new Date(order.timestamp).toLocaleString()}</p>
                                <p class="text-gray-600 dark:text-gray-400 mb-1">Network: ${order.network}</p>
                                <p class="text-gray-600 dark:text-gray-400 mb-1">Bundle: ${order.bundleVolume}</p>
                                <p class="text-gray-600 dark:text-gray-400 mb-1">Phone: ${order.phoneNumber}</p>
                                <p class="text-gray-600 dark:text-gray-400 mb-1">Price: GHS ${order.price.toFixed(2)}</p>
                                <p class="text-gray-600 dark:text-gray-400 mb-2">Status: ${order.status || 'Pending'}</p>
                                <div class="flex justify-end">
                                    <button onclick="editOrder('${orderId}')" class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600 mr-2">Edit</button>
                                    <button onclick="deleteOrder('${orderId}')" class="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600">Delete</button>
                                </div>
                            </div>
                        `;
                    });
                } else {
                    ordersHtml += '<p class="text-gray-600 dark:text-gray-400">No orders found.</p>';
                }
                ordersHtml += '</div>';
                mainContent.innerHTML = ordersHtml;

                // Add event listeners for search and sort
                document.getElementById('order-search').addEventListener('input', filterOrders);
                document.getElementById('order-sort').addEventListener('change', sortOrders);

                updateNavbarStats();
            }).catch((error) => {
                console.error('Error fetching orders:', error);
                notyf.error('Error loading orders');
            });
        }

        function filterOrders() {
            const searchTerm = document.getElementById('order-search').value.toLowerCase();
            const orderCards = document.querySelectorAll('.order-card');

            orderCards.forEach(card => {
                const cardContent = card.textContent.toLowerCase();
                if (cardContent.includes(searchTerm)) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        }

        function sortOrders() {
            const sortBy = document.getElementById('order-sort').value;
            const ordersContainer = document.getElementById('orders-container');
            const orderCards = Array.from(ordersContainer.children);

            orderCards.sort((a, b) => {
                const aValue = a.dataset[sortBy];
                const bValue = b.dataset[sortBy];
                if (sortBy === 'price') {
                    return parseFloat(bValue) - parseFloat(aValue);
                }
                return bValue.localeCompare(aValue);
            });

            orderCards.forEach(card => ordersContainer.appendChild(card));
        }

        function loadMessages() {
            showLoading('main-content');

            get(ref(database, 'support_messages')).then((snapshot) => {
                let messagesHtml = `
                    <div class="mb-4 flex flex-col sm:flex-row justify-between items-center">
                        <input type="text" id="message-search" placeholder="Search messages..." class="w-full sm:w-64 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white mb-2 sm:mb-0">
                        <select id="message-sort" class="w-full sm:w-48 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            <option value="timestamp">Sort by Date</option>
                            <option value="name">Sort by Name</option>
                        </select>
                    </div>
                    <div id="messages-container" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                `;
                
                if (snapshot.exists()) {
                    snapshot.forEach((childSnapshot) => {
                        const message = childSnapshot.val();
                        const messageId = childSnapshot.key;
                        messagesHtml += `
                            <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md message-card" data-timestamp="${message.timestamp}" data-name="${message.name.toLowerCase()}">
                                <p class="text-gray-600 dark:text-gray-400 mb-1">From: ${message.name}</p>
                                <p class="text-gray-600 dark:text-gray-400 mb-1">Email: ${message.email}</p>
                                <p class="text-gray-600 dark:text-gray-400 mb-1">Date: ${new Date(message.timestamp).toLocaleString()}</p>
                                <p class="text-gray-600 dark:text-gray-400 mb-2">Message: ${message.message}</p>
                                <div class="flex justify-end">
                                    <button onclick="deleteMessage('${messageId}')" class="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600">Delete</button>
                                </div>
                            </div>
                        `;
                    });
                } else {
                    messagesHtml += '<p class="text-gray-600 dark:text-gray-400">No messages found.</p>';
                }
                messagesHtml += '</div>';
                mainContent.innerHTML = messagesHtml;

                // Add event listeners for search and sort
                document.getElementById('message-search').addEventListener('input', filterMessages);
                document.getElementById('message-sort').addEventListener('change', sortMessages);

                updateNavbarStats();
            }).catch((error) => {
                console.error('Error fetching messages:', error);
                notyf.error('Error loading messages');
            });
        }

        function filterMessages() {
            const searchTerm = document.getElementById('message-search').value.toLowerCase();
            const messageCards = document.querySelectorAll('.message-card');

            messageCards.forEach(card => {
                const cardContent = card.textContent.toLowerCase();
                if (cardContent.includes(searchTerm)) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        }

        function sortMessages() {
            const sortBy = document.getElementById('message-sort').value;
            const messagesContainer = document.getElementById('messages-container');
            const messageCards = Array.from(messagesContainer.children);

            messageCards.sort((a, b) => {
                const aValue = a.dataset[sortBy];
                const bValue = b.dataset[sortBy];
                return bValue.localeCompare(aValue);
            });

            messageCards.forEach(card => messagesContainer.appendChild(card));
        }

        // Edit user function
        window.editUser = function(userId) {
            get(ref(database, `users/${userId}`)).then((snapshot) => {
                const user = snapshot.val();
                modalTitle.textContent = 'Edit User';
                modalContent.innerHTML = `
                    <div class="mb-4">
                        <label for="edit-name" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Name</label>
                        <input id="edit-name" type="text" value="${user.name}" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                    </div>
                    <div class="mb-4">
                        <label for="edit-email" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Email</label>
                        <input id="edit-email" type="email" value="${user.email}" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                    </div>
                    <div class="mb-4">
                        <label for="edit-phone" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Phone</label>
                        <input id="edit-phone" type="tel" value="${user.phone}" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                    </div>
                    <div class="mb-4">
                        <label for="edit-agent-status" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Agent Status</label>
                        <select id="edit-agent-status" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            <option value="true" ${user.agentPortalActive ? 'selected' : ''}>Active</option>
                            <option value="false" ${!user.agentPortalActive ? 'selected' : ''}>Inactive</option>
                        </select>
                    </div>
                `;
                modalSave.onclick = () => saveUserChanges(userId);
                modal.classList.remove('hidden');
            }).catch((error) => {
                console.error('Error fetching user:', error);
                notyf.error('Error fetching user data');
            });
        }

        // Save user changes
        function saveUserChanges(userId) {
            const updatedUser = {
                name: document.getElementById('edit-name').value,
                email: document.getElementById('edit-email').value,
                phone: document.getElementById('edit-phone').value,
                agentPortalActive: document.getElementById('edit-agent-status').value === 'true'
            };

            update(ref(database, `users/${userId}`), updatedUser)
                .then(() => {
                    notyf.success('User updated successfully');
                    modal.classList.add('hidden');
                    loadUsers();
                })
                .catch((error) => {
                    console.error('Error updating user:', error);
                    notyf.error('Error updating user');
                });
        }

        // Delete user function
        window.deleteUser = function(userId) {
            if (confirm('Are you sure you want to delete this user?')) {
                remove(ref(database, `users/${userId}`))
                    .then(() => {
                        notyf.success('User deleted successfully');
                        loadUsers();
                    })
                    .catch((error) => {
                        console.error('Error deleting user:', error);
                        notyf.error('Error deleting user');
                    });
            }
        }

        // Edit order function
        window.editOrder = function(orderId) {
            get(ref(database, `orders/${orderId}`)).then((snapshot) => {
                const order = snapshot.val();
                modalTitle.textContent = 'Edit Order';
                modalContent.innerHTML = `
                    <div class="mb-4">
                        <label for="edit-network" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Network</label>
                        <input id="edit-network" type="text" value="${order.network}" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                    </div>
                    <div class="mb-4">
                        <label for="edit-bundle" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Bundle</label>
                        <input id="edit-bundle" type="text" value="${order.bundleVolume}" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                    </div>
                    <div class="mb-4">
                        <label for="edit-phone" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Phone</label>
                        <input id="edit-phone" type="tel" value="${order.phoneNumber}" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                    </div>
                    <div class="mb-4">
                        <label for="edit-price" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Price</label>
                        <input id="edit-price" type="number" step="0.01" value="${order.price}" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                    </div>
                    <div class="mb-4">
                        <label for="edit-status" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Status</label>
                        <select id="edit-status" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            <option value="Pending" ${order.status === 'Pending' ? 'selected' : ''}>Pending</option>
                            <option value="Completed" ${order.status === 'Completed' ? 'selected' : ''}>Completed</option>
                            <option value="Cancelled" ${order.status === 'Cancelled' ? 'selected' : ''}>Cancelled</option>
                        </select>
                    </div>
                `;
                modalSave.onclick = () => saveOrderChanges(orderId);
                modal.classList.remove('hidden');
            }).catch((error) => {
                console.error('Error fetching order:', error);
                notyf.error('Error fetching order data');
            });
        }

        // Save order changes
        function saveOrderChanges(orderId) {
            const updatedOrder = {
                network: document.getElementById('edit-network').value,
                bundleVolume: document.getElementById('edit-bundle').value,
                phoneNumber: document.getElementById('edit-phone').value,
                price: parseFloat(document.getElementById('edit-price').value),
                status: document.getElementById('edit-status').value
            };

            update(ref(database, `orders/${orderId}`), updatedOrder)
                .then(() => {
                    notyf.success('Order updated successfully');
                    modal.classList.add('hidden');
                    loadOrders();
                    updateNavbarStats();
                })
                .catch((error) => {
                    console.error('Error updating order:', error);
                    notyf.error('Error updating order');
                });
        }

        // Delete order function
        window.deleteOrder = function(orderId) {
            if (confirm('Are you sure you want to delete this order?')) {
                remove(ref(database, `orders/${orderId}`))
                    .then(() => {
                        notyf.success('Order deleted successfully');
                        loadOrders();
                        updateNavbarStats();
                    })
                    .catch((error) => {
                        console.error('Error deleting order:', error);
                        notyf.error('Error deleting order');
                    });
            }
        }

        // Delete message function
        window.deleteMessage = function(messageId) {
            if (confirm('Are you sure you want to delete this message?')) {
                remove(ref(database, `support_messages/${messageId}`))
                    .then(() => {
                        notyf.success('Message deleted successfully');
                        loadMessages();
                        updateNavbarStats();
                    })
                    .catch((error) => {
                        console.error('Error deleting message:', error);
                        notyf.error('Error deleting message');
                    });
            }
        }
    </script>
</body>
</html>

