class AdminManager {
    constructor(app) {
        this.app = app;
        this.currentSort = {
            by: 'created_at',
            dir: 'desc'
        };
    }

    async loadStats() {
        try {
            const response = await fetch('api/admin/stats.php');
            const data = await response.json();

            if (data.success && data.stats) {
                document.getElementById('total-users').textContent = data.stats.total_users || 0;
                document.getElementById('total-deliveries').textContent = data.stats.total_deliveries || 0;
                document.getElementById('total-shops').textContent = data.stats.total_shops || 0;
                document.getElementById('total-revenue').textContent = '$' + (data.stats.total_revenue || 0);
            }
        } catch (error) {
            console.error('Error loading admin stats:', error);
        }
    }

    _renderPage(title, content) {
        const mainContent = document.getElementById('main-content');
        mainContent.innerHTML = `
            <div class="management-page">${content}</div>
        `;
    }

    async updateUserRole(userId, role) {
        try {
            const response = await fetch('api/admin/update_user.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    user_id: userId,
                    role: role
                })
            });

            const data = await response.json();

            if (!data.success) {
                this.app.notifier.show('Error updating user role: ' + data.message, 'error');
            }
        } catch (error) {
            console.error('Error updating user role:', error);
            this.app.notifier.show('Failed to update user role', 'error');
        }
    }

    // --- Create Delivery ---
    async createDelivery() {
        this._renderPage('Create Delivery', `
            <div class="section-title">
                <h2>Create New Delivery</h2>
                <button class="btn-secondary" id="back-to-admin-dash"><i class="fas fa-arrow-left"></i> Back</button>
            </div>
            <div class="auth-card" style="max-width: 600px; margin: 0 auto;">
                <form id="admin-create-delivery-form">
                    <div class="form-group">
                        <label>Sender Details</label>
                        <input type="tel" name="sender_phone" placeholder="Sender Phone Number" required>
                        <input type="text" name="sender_name" placeholder="Sender Name" class="mt-2">
                    </div>
                    <div class="form-group">
                        <label>Receiver Details</label>
                        <input type="tel" name="receiver_phone" placeholder="Receiver Phone Number">
                        <input type="text" name="receiver_name" placeholder="Receiver Name" class="mt-2">
                    </div>
                    <div class="form-group">
                        <label>Package Details</label>
                        <textarea name="package_description" rows="2" placeholder="Description of items..." required></textarea>
                    </div>
                    <div class="form-group">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                            <input type="text" name="pickup_location" placeholder="Pickup Location" required>
                            <input type="text" name="delivery_location" placeholder="Delivery Location" required>
                        </div>
                    </div>
                    <div class="form-actions">
                        <button type="submit" class="btn-primary">Create Delivery</button>
                    </div>
                </form>
            </div>
        `);

        document.getElementById('back-to-admin-dash')?.addEventListener('click', () => this.app.loadAdminDashboard());
        
        const form = document.getElementById('admin-create-delivery-form');
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const btn = form.querySelector('button[type="submit"]');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Creating...';
            
            try {
                const formData = new FormData(form);
                const data = Object.fromEntries(formData.entries());
                
                const response = await fetch('api/admin/create_delivery.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });
                const result = await response.json();
                
                if (result.success) {
                    this.app.notifier.show('Delivery created successfully! Tracking ID: ' + result.tracking_id, 'success');
                    form.reset();
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                this.app.notifier.show(error.message || 'Failed to create delivery', 'error');
            } finally {
                btn.disabled = false;
                btn.innerHTML = 'Create Delivery';
            }
        });
    }

    // --- User Management ---
    async manageUsers() {
        this._renderPage('Manage Users', `
            <div class="section-title">
                <h2>Manage Users</h2>
                <button class="btn-secondary" id="back-to-admin-dash"><i class="fas fa-arrow-left"></i> Back</button>
            </div>
            <div class="search-bar-container">
                <input type="search" id="user-search" placeholder="Search by name or email...">
                <i class="fas fa-search"></i>
            </div>
            <div class="table-container" id="users-table-container">
                <div class="loading">Loading users...</div>
            </div>
            <div class="pagination-container" id="user-pagination"></div>
        `);
        this.setupManagementPageListeners('user');
        this.currentSort = { by: 'created_at', dir: 'desc' };
        this.fetchAndRenderUsers();
    }

    async fetchAndRenderUsers(searchTerm = '', page = 1, sortBy = this.currentSort.by, sortDir = this.currentSort.dir) {
        const container = document.getElementById('users-table-container');
        container.innerHTML = '<div class="loading">Loading users...</div>';
        this.currentSort = { by: sortBy, dir: sortDir };

        try {
            const url = new URL('api/admin/all_users.php', window.location.href);
            url.searchParams.set('search', searchTerm);
            url.searchParams.set('page', page);
            url.searchParams.set('sort_by', sortBy);
            url.searchParams.set('sort_dir', sortDir);

            const response = await fetch(url);
            const data = await response.json();
            if (!data.success) throw new Error(data.message);

            const tableRows = data.users.map(user => `
                <tr>
                    <td>${user.name}</td>
                    <td>${user.email}</td>
                    <td>
                        <select class="role-select" data-user-id="${user.id}">
                            <option value="customer" ${user.role === 'customer' ? 'selected' : ''}>Customer</option>
                            <option value="shop_owner" ${user.role === 'shop_owner' ? 'selected' : ''}>Shop Owner</option>
                            <option value="rider" ${user.role === 'rider' ? 'selected' : ''}>Rider</option>
                            <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>Admin</option>
                        </select>
                    </td>
                    <td>${new Date(user.created_at).toLocaleDateString()}</td>
                    <td><button class="btn-secondary btn-sm user-details-btn" data-user-id="${user.id}">Details</button></td>
                </tr>
            `).join('');

            container.innerHTML = `
                <table>
                    <thead><tr>
                        ${this._renderSortableHeader('user', 'Name', 'name')}
                        ${this._renderSortableHeader('user', 'Email', 'email')}
                        ${this._renderSortableHeader('user', 'Role', 'role')}
                        ${this._renderSortableHeader('user', 'Joined', 'created_at')}
                        <th>Actions</th>
                    </tr></thead>
                    <tbody>${tableRows}</tbody>
                </table>
            `;
            this._renderPagination('user', data.pagination);
        } catch (error) {
            container.innerHTML = `<div class="error">${error.message}</div>`;
        }
    }

    async showUserDetailsModal(userId) {
        const modalInstance = new Modal({
            title: 'User Details',
            content: '<div class="loading">Loading user details...</div>',
            size: 'large-modal'
        });
        const modal = modalInstance.show();

        try {
            const response = await fetch(`api/admin/get_user_details.php?id=${userId}`);
            const data = await response.json();
            if (!data.success) throw new Error(data.message);

            const user = data.user;
            let detailsHTML = '';

            if (user.role === 'customer') {
                const deliveries = user.details.recent_deliveries || [];
                const orders = user.details.recent_orders || [];
                detailsHTML = `
                    <h5>Recent Deliveries</h5>
                    ${deliveries.length > 0 ? deliveries.map(d => `<p>#${d.tracking_id} - ${d.status}</p>`).join('') : '<p>None</p>'}
                    <h5>Recent Shop Orders</h5>
                    ${orders.length > 0 ? orders.map(o => `<p>#${o.id} - $${o.total_amount} - ${o.status}</p>`).join('') : '<p>None</p>'}
                `;
            } else if (user.role === 'shop_owner') {
                const shops = user.details.shops || [];
                detailsHTML = `
                    <h5>Shops Owned</h5>
                    ${shops.length > 0 ? shops.map(s => `<p>${s.name} (${s.is_approved ? 'Approved' : 'Pending'})</p>`).join('') : '<p>None</p>'}
                `;
            } else if (user.role === 'rider') {
                const stats = user.details.delivery_stats || {};
                detailsHTML = `
                    <h5>Delivery Stats</h5>
                    <p>Pending: ${stats.pending || 0}</p>
                    <p>Accepted: ${stats.accepted || 0}</p>
                    <p>Delivered: ${stats.delivered || 0}</p>
                `;
            }

            const modalContent = `
                <div class="user-details-modal">
                    <div class="user-info">
                        <h4>${user.name}</h4>
                        <p><strong>Email:</strong> ${user.email}</p>
                        <p><strong>Phone:</strong> ${user.phone || 'N/A'}</p>
                        <p><strong>Role:</strong> ${user.role}</p>
                        <p><strong>Joined:</strong> ${new Date(user.created_at).toLocaleString()}</p>
                    </div>
                    <div class="user-activity">
                        ${detailsHTML}
                    </div>
                </div>
            `;

            modal.querySelector('.modal-body').innerHTML = modalContent;

        } catch (error) {
            modal.querySelector('.modal-body').innerHTML = `<div class="error">${error.message}</div>`;
        }

    }

    // --- Shop Management ---
    async manageShops() {
        this._renderPage('Manage Shops', `
            <div class="section-title">
                <h2>Manage Shops</h2>
                <button class="btn-secondary" id="back-to-admin-dash"><i class="fas fa-arrow-left"></i> Back</button>
            </div>
            <div class="search-bar-container">
                <input type="search" id="shop-search" placeholder="Search by shop or owner name...">
                <i class="fas fa-search"></i>
            </div>
            <div class="table-container" id="shops-table-container">
                <div class="loading">Loading shops...</div>
            </div>
            <div class="pagination-container" id="shop-pagination"></div>
        `);
        this.setupManagementPageListeners('shop');
        this.currentSort = { by: 'created_at', dir: 'desc' };
        this.fetchAndRenderShops();
    }

    async fetchAndRenderShops(searchTerm = '', page = 1, sortBy = this.currentSort.by, sortDir = this.currentSort.dir) {
        const container = document.getElementById('shops-table-container');
        container.innerHTML = '<div class="loading">Loading shops...</div>';
        this.currentSort = { by: sortBy, dir: sortDir };

        try {
            const url = new URL('api/admin/all_shops.php', window.location.href);
            url.searchParams.set('search', searchTerm);
            url.searchParams.set('page', page);
            url.searchParams.set('sort_by', sortBy);
            url.searchParams.set('sort_dir', sortDir);

            const response = await fetch(url);
            const data = await response.json();
            if (!data.success) throw new Error(data.message);

            const tableRows = data.shops.map(shop => {
                const statusText = shop.is_approved ? 'Approved' : 'Pending';
                const statusClass = shop.is_approved ? 'status-approved' : 'status-pending';
                const actionButton = shop.is_approved ?
                    `<button class="btn-danger btn-sm" data-action="revoke-shop" data-shop-id="${shop.id}">Revoke</button>` :
                    `<button class="btn-success btn-sm" data-action="approve-shop" data-shop-id="${shop.id}">Approve</button>`;

                return `
                <tr>
                    <td>${shop.name}</td>
                    <td>${shop.owner_name || 'N/A'}</td>
                    <td>${shop.location}</td>
                    <td><span class="status-text ${statusClass}">${statusText}</span></td>
                    <td class="action-cell">${actionButton} <button class="btn-secondary btn-sm view-shop-btn" data-shop-id="${shop.id}">View</button></td>
                </tr>
            `}).join('');

            container.innerHTML = `
                <table>
                    <thead><tr>
                        ${this._renderSortableHeader('shop', 'Shop Name', 'name')}
                        ${this._renderSortableHeader('shop', 'Owner', 'owner_name')}
                        ${this._renderSortableHeader('shop', 'Location', 'location')}
                        ${this._renderSortableHeader('shop', 'Status', 'is_approved')}
                        <th>Actions</th>
                    </tr></thead>
                    <tbody>${tableRows}</tbody>
                </table>
            `;
            this._renderPagination('shop', data.pagination);
        } catch (error) {
            container.innerHTML = `<div class="error">${error.message}</div>`;
        }
    }

    async handleUpdateShopStatus(shopId, isApproved) {
        try {
            const response = await fetch('api/admin/update_shop_status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ shop_id: shopId, is_approved: isApproved })
            });

            const result = await response.json();

            if (result.success) {
                this.app.notifier.show(result.message, 'success');
                // Refresh the shops list to show the updated status
                const currentPage = document.querySelector('.pagination-container .active')?.dataset.page || 1;
                this.fetchAndRenderShops(document.getElementById('shop-search')?.value || '', currentPage);
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            this.app.notifier.show(`Error: ${error.message}`, 'error');
        }
    }

    // --- Delivery Management ---
    async manageDeliveries() {
        this._renderPage('Manage Deliveries', `
            <div class="section-title">
                <h2>Manage Deliveries</h2>
                <button class="btn-secondary" id="back-to-admin-dash"><i class="fas fa-arrow-left"></i> Back</button>
            </div>
            <div class="search-bar-container">
                <input type="search" id="delivery-search" placeholder="Search by Tracking ID, Customer, or Rider...">
                <i class="fas fa-search"></i>
            </div>
            <div class="table-container" id="deliveries-table-container">
                <div class="loading">Loading deliveries...</div>
            </div>
            <div class="pagination-container" id="delivery-pagination"></div>
        `);
        this.setupManagementPageListeners('delivery');
        this.currentSort = { by: 'created_at', dir: 'desc' };
        this.fetchAndRenderDeliveries();
    }

    async fetchAndRenderDeliveries(searchTerm = '', page = 1, sortBy = this.currentSort.by, sortDir = this.currentSort.dir) {
        const container = document.getElementById('deliveries-table-container');
        container.innerHTML = '<div class="loading">Loading deliveries...</div>';
        this.currentSort = { by: sortBy, dir: sortDir };

        try {
            const url = new URL('api/admin/all_deliveries.php', window.location.href);
            url.searchParams.set('search', searchTerm);
            url.searchParams.set('page', page);
            url.searchParams.set('sort_by', sortBy);
            url.searchParams.set('sort_dir', sortDir);

            const response = await fetch(url);
            const data = await response.json();
            if (!data.success) throw new Error(data.message);

            const tableRows = data.deliveries.map(d => `
                <tr>
                    <td>${d.tracking_id}</td>
                    <td>${d.customer_name}</td>
                    <td>${d.rider_name || 'N/A'}</td>
                    <td><span class="delivery-status status-${d.status.replace('_', '-')}">${d.status}</span></td>
                    <td>$${parseFloat(d.price).toFixed(2)}</td>
                    <td><button class="btn-secondary btn-sm" onclick="app.customerManager.showTrackingModal(${d.id})">Track</button></td>
                </tr>
            `).join('');

            container.innerHTML = `
                <table>
                    <thead><tr>
                        ${this._renderSortableHeader('delivery', 'Tracking ID', 'tracking_id')}
                        ${this._renderSortableHeader('delivery', 'Customer', 'customer_name')}
                        ${this._renderSortableHeader('delivery', 'Rider', 'rider_name')}
                        ${this._renderSortableHeader('delivery', 'Status', 'status')}
                        ${this._renderSortableHeader('delivery', 'Price', 'price')}
                        <th>Actions</th>
                    </tr></thead>
                    <tbody>${tableRows}</tbody>
                </table>
            `;
            this._renderPagination('delivery', data.pagination);
        } catch (error) {
            container.innerHTML = `<div class="error">${error.message}</div>`;
        }

    }

    // --- Slides Management ---
    async manageSlides() {
        this._renderPage('Manage Slides', `
            <div class="section-title">
                <h2>Manage Slides</h2>
                <button class="btn-secondary" id="back-to-admin-dash"><i class="fas fa-arrow-left"></i> Back</button>
            </div>
            <div class="slide-form-container">
                <form id="slide-form">
                    <input type="hidden" name="id">
                    <div class="form-group">
                        <label for="slide-title">Title</label>
                        <input type="text" id="slide-title" name="title" required>
                    </div>
                    <div class="form-group">
                        <label for="slide-description">Description</label>
                        <input type="text" id="slide-description" name="description">
                    </div>
                    <div class="form-group">
                        <label for="slide-image">Image</label>
                        <input type="file" id="slide-image" name="image" accept="image/*">
                    </div>
                    <div class="form-actions">
                        <button type="submit" class="btn-primary">Add New Slide</button>
                        <button type="button" class="btn-secondary" id="cancel-slide-edit" style="display: none;">Cancel Edit</button>
                    </div>
                </form>
            </div>
            <div class="table-container" id="slides-list-container">
                <div class="loading">Loading slides...</div>
            </div>
        `);
        this.setupManagementPageListeners('slide');
        this.fetchAndRenderSlides();
    }

    async fetchAndRenderSlides() {
        const container = document.getElementById('slides-list-container');
        try {
            const response = await fetch('api/admin/manage_slides.php');
            const data = await response.json();
            if (!data.success) throw new Error(data.message);

            const slideItems = data.slides.map(slide => `
                <div class="slide-management-item" data-slide-id="${slide.id}">
                    <img src="${slide.image_path}" alt="${slide.title}" class="slide-preview">
                    <div class="slide-details">
                        <h4>${slide.title}</h4>
                        <p>${slide.description || 'No description'}</p>
                    </div>
                    <div class="slide-actions">
                        <label class="availability-toggle">
                            <input type="checkbox" class="slide-active-toggle" ${slide.is_active ? 'checked' : ''}>
                            <span class="availability-toggle-slider"></span>
                        </label>
                        <button class="btn-secondary btn-sm edit-slide"><i class="fas fa-edit"></i></button>
                        <button class="btn-danger btn-sm delete-slide"><i class="fas fa-trash"></i></button>
                    </div>
                </div>
            `).join('');
            container.innerHTML = slideItems || '<div class="empty-state">No slides found. Add one to get started.</div>';
        } catch (error) {
            container.innerHTML = `<div class="error">${error.message}</div>`;
        }
    }

    async handleSaveSlide(form) {
        try {
            const imageFile = form.elements['image'].files[0];
            const slideId = form.elements['id'].value;
            let imageUrl = null;

            // If it's a new slide, an image is required.
            if (!slideId && !imageFile) {
                throw new Error("An image is required for a new slide.");
            }

            if (imageFile) {
                const uploadFormData = new FormData();
                uploadFormData.append('image', imageFile);
                uploadFormData.append('type', 'slides');
                const uploadResponse = await fetch('api/upload.php', { method: 'POST', body: uploadFormData });
                const uploadResult = await uploadResponse.json();
                if (!uploadResult.success) throw new Error(uploadResult.message);
                imageUrl = uploadResult.url;
            }

            const data = {
                title: form.elements['title'].value,
                description: form.elements['description'].value,
                image_path: imageUrl, // Will be null if no new image is uploaded on edit
                is_active: true // Default to active, will be handled by toggle
            };
            if (slideId) data.id = slideId;

            const response = await fetch('api/admin/manage_slides.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await response.json();
            if (!result.success) throw new Error(result.message);

            this.app.notifier.show(result.message, 'success');
            form.reset();
            form.querySelector('button[type="submit"]').textContent = 'Add New Slide';
            document.getElementById('cancel-slide-edit').style.display = 'none';
            this.fetchAndRenderSlides();
        } catch (error) {
            this.app.notifier.show(error.message, 'error');
        }
    }

    async handleDeleteSlide(slideId) {
        const confirmed = await this.app.showConfirm('Are you sure you want to delete this slide?', 'Delete Slide');
        if (!confirmed) return;

        try {
            const response = await fetch('api/admin/manage_slides.php', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: slideId })
            });
            const result = await response.json();
            if (!result.success) throw new Error(result.message);
            this.app.notifier.show(result.message, 'success');
            this.fetchAndRenderSlides();
        } catch (error) {
            this.app.notifier.show(error.message, 'error');
        }
    }

    // --- System Settings ---
    async manageSettings() {
        this._renderPage('System Settings', this.getSettingsFormHTML());
        this.setupManagementPageListeners('settings');
        this.fetchAndRenderSettings();
    }

    getSettingsFormHTML() {
        return `
            <div class="section-title">
                <h2>System Settings</h2>
                <button class="btn-secondary" id="back-to-admin-dash"><i class="fas fa-arrow-left"></i> Back</button>
            </div>
            <form id="system-settings-form">
                <div class="settings-section">
                    <h4>Pricing</h4>
                    <div class="form-group"><label>Currency Symbol</label><input type="text" name="currency_symbol" value="$" title="e.g., $, €, £"></div>
                    <h5>Standard Delivery</h5>
                    <div class="form-group"><label>Base Price (Standard)</label><input type="number" name="base_price_standard" step="0.01" min="0"></div>
                    <div class="form-group"><label>Price Per Km (Standard)</label><input type="number" name="price_per_km_standard" step="0.01" min="0"></div>
                    <h5>Express Delivery</h5>
                    <div class="form-group"><label>Base Price (Express)</label><input type="number" name="base_price_express" step="0.01" min="0"></div>
                    <div class="form-group"><label>Price Per Km (Express)</label><input type="number" name="price_per_km_express" step="0.01" min="0"></div>
                </div>
                <div class="settings-section">
                    <h4>Fees & Discounts</h4>
                    <div class="form-group"><label>Multi-Shop Order Fee</label><input type="number" name="multi_shop_fee" step="0.01" min="0" title="Additional fee if cart contains items from multiple shops."></div>
                    <div class="form-group"><label>Loyalty: Delivery Count Threshold</label><input type="number" name="loyalty_delivery_threshold" step="1" min="1" title="Number of completed deliveries needed to earn a discount."></div>
                    <div class="form-group"><label>Loyalty: Delivery Discount (%)</label><input type="number" name="loyalty_delivery_discount_percent" step="1" min="0" max="100" title="Percentage discount for the next delivery after hitting the threshold."></div>
                </div>

                <div class="settings-section">
                    <h4>App Controls</h4>
                    <div class="form-group checkbox-group"><label class="checkbox-label"><input type="checkbox" name="allow_registrations"><span>Allow New User Registrations</span></label></div>
                    <div class="form-group checkbox-group"><label class="checkbox-label"><input type="checkbox" name="allow_shop_creation"><span>Allow Users to Create Shops</span></label></div>
                </div>

                <div class="settings-section">
                    <h4>Operating Hours</h4>
                    <div class="form-group"><label>Opening Time</label><input type="time" name="operating_hours_start"></div>
                    <div class="form-group"><label>Closing Time</label><input type="time" name="operating_hours_end"></div>
                </div>

                <div class="settings-section">
                    <h4>Payment Gateways</h4>
                    <div class="form-group checkbox-group"><label class="checkbox-label"><input type="checkbox" name="payment_cod"><span>Enable Cash on Delivery (COD)</span></label></div>
                    <div class="form-group checkbox-group"><label class="checkbox-label"><input type="checkbox" name="payment_mobile"><span>Enable Mobile Money</span></label></div>
                    <div class="form-group checkbox-group"><label class="checkbox-label"><input type="checkbox" name="payment_card"><span>Enable Bank Cards</span></label></div>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn-primary">Save Settings</button>
                </div>
            </form>
        `;
    }

    async fetchAndRenderSettings() {
        try {
            const response = await fetch('api/admin/settings.php');
            const data = await response.json();
            if (!data.success) throw new Error(data.message);

            const form = document.getElementById('system-settings-form');
            if (!form) return;

            for (const key in data.settings) {
                const element = form.elements[key];
                if (element) {
                    if (element.type === 'checkbox') {
                        element.checked = data.settings[key] === 'true';
                    } else {
                        element.value = data.settings[key];
                    }
                }
            }
        } catch (error) {
            this.app.notifier.show(`Failed to load settings: ${error.message}`, 'error');
        }
    }

    async handleSaveSettings(form) {
        const submitBtn = form.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';

        try {
            const formData = new FormData(form);
            const settings = {};
            // Handle text/number/time inputs
            for (const [key, value] of formData.entries()) {
                settings[key] = value;
            }
            // Handle checkboxes, as unchecked boxes are not included in FormData
            form.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                settings[checkbox.name] = checkbox.checked;
            });

            const response = await fetch('api/admin/settings.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(settings)
            });

            const result = await response.json();
            if (!result.success) throw new Error(result.message);

            this.app.notifier.show('Settings saved successfully!', 'success');

        } catch (error) {
            this.app.notifier.show(`Failed to save settings: ${error.message}`, 'error');
        } finally {
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Save Settings';
        }
    }

    _renderPagination(type, pagination) {
        const container = document.getElementById(`${type}-pagination`);
        if (!container || !pagination || pagination.total_pages <= 1) {
            if (container) container.innerHTML = '';
            return;
        }

        let pagesHTML = '';
        const { current_page, total_pages } = pagination;

        // Previous button
        pagesHTML += `<li class="page-item ${current_page === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${current_page - 1}">&laquo;</a>
        </li>`;

        // Page numbers
        for (let i = 1; i <= total_pages; i++) {
            pagesHTML += `<li class="page-item ${i === current_page ? 'active' : ''}">
                <a class="page-link" href="#" data-page="${i}">${i}</a>
            </li>`;
        }

        // Next button
        pagesHTML += `<li class="page-item ${current_page === total_pages ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${current_page + 1}">&raquo;</a>
        </li>`;

        container.innerHTML = `
            <nav>
                <ul class="pagination">${pagesHTML}</ul>
            </nav>
        `;
    }

    _renderSortableHeader(type, label, column) {
        let iconClass = 'fa-sort';
        if (this.currentSort.by === column) {
            iconClass = this.currentSort.dir === 'asc' ? 'fa-sort-up' : 'fa-sort-down';
        }
        return `
            <th>
                <a href="#" class="sort-link" data-type="${type}" data-sort="${column}">
                    ${label} <i class="fas ${iconClass}"></i>
                </a>
            </th>
        `;
    }

    // --- Common Listeners & Helpers ---
    setupManagementPageListeners(type) {
        document.getElementById('back-to-admin-dash')?.addEventListener('click', () => {
            this.app.loadAdminDashboard();
        });

        const searchInput = document.getElementById(`${type}-search`);
        if (searchInput) {
            let debounce;
            searchInput.addEventListener('input', (e) => {
                clearTimeout(debounce);
                debounce = setTimeout(() => {
                    const term = e.target.value;
                    switch (type) {
                        case 'user':
                            this.fetchAndRenderUsers(term, 1);
                            break;
                        case 'shop':
                            this.fetchAndRenderShops(term, 1);
                            break;
                        case 'delivery':
                            this.fetchAndRenderDeliveries(term, 1);
                            break;
                        case 'slide':
                            // No search for slides, but structure is here if needed
                            break;
                    }
                }, 300);
            });
        }

        // Listener for settings form
        if (type === 'settings') {
            const form = document.getElementById('system-settings-form');
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleSaveSettings(form);
            });
        }

        // Listener for pagination clicks
        const paginationContainer = document.getElementById(`${type}-pagination`);
        if (paginationContainer) {
            paginationContainer.addEventListener('click', (e) => {
                e.preventDefault();
                const pageLink = e.target.closest('.page-link');
                if (!pageLink || pageLink.parentElement.classList.contains('disabled')) return;

                const page = parseInt(pageLink.dataset.page, 10);
                const searchTerm = document.getElementById(`${type}-search`)?.value || '';

                switch (type) {
                    case 'user': this.fetchAndRenderUsers(searchTerm, page); break;
                    case 'shop': this.fetchAndRenderShops(searchTerm, page); break;
                    case 'delivery': this.fetchAndRenderDeliveries(searchTerm, page); break;
                }
            });
        }

        // Listener for sortable headers
        const tableContainer = document.getElementById(`${type}-table-container`);
        if (tableContainer) {
            tableContainer.addEventListener('click', (e) => {
                const sortLink = e.target.closest('.sort-link');
                if (!sortLink) return;
                e.preventDefault();

                const sortBy = sortLink.dataset.sort;
                const sortDir = (this.currentSort.by === sortBy && this.currentSort.dir === 'asc') ? 'desc' : 'asc';
                const searchTerm = document.getElementById(`${type}-search`)?.value || '';

                switch (type) {
                    case 'user': this.fetchAndRenderUsers(searchTerm, 1, sortBy, sortDir); break;
                    case 'shop': this.fetchAndRenderShops(searchTerm, 1, sortBy, sortDir); break;
                    case 'delivery': this.fetchAndRenderDeliveries(searchTerm, 1, sortBy, sortDir); break;
                }
            });
        }

        // Listener for role changes in the user management table
        if (type === 'user') {
            const tableContainer = document.getElementById('users-table-container');
            tableContainer.addEventListener('click', (e) => {
                if (e.target.classList.contains('role-select')) {
                    const userId = e.target.dataset.userId;
                    const newRole = e.target.value;
                    this.updateUserRole(userId, newRole);
                }

                const detailsButton = e.target.closest('.user-details-btn');
                if (detailsButton) {
                    const userId = detailsButton.dataset.userId;
                    this.showUserDetailsModal(userId);
                }
            });
        }

        // Listeners for shop management
        if (type === 'shop') {
            const tableContainer = document.getElementById('shops-table-container');
            tableContainer.addEventListener('click', (e) => {
                const approveBtn = e.target.closest('[data-action="approve-shop"]');
                if (approveBtn) {
                    this.handleUpdateShopStatus(approveBtn.dataset.shopId, true);
                }
                const revokeBtn = e.target.closest('[data-action="revoke-shop"]');
                if (revokeBtn) {
                    this.handleUpdateShopStatus(revokeBtn.dataset.shopId, false);
                }

                const viewBtn = e.target.closest('.view-shop-btn');
                if (viewBtn) {
                    this.app.shopManager.viewShop(viewBtn.dataset.shopId);
                }
            });
        }

        // Listeners for slide management
        if (type === 'slide') {
            const page = document.querySelector('.management-page');
            const form = document.getElementById('slide-form');

            form.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleSaveSlide(form);
            });

            page.addEventListener('click', (e) => {
                const slideItem = e.target.closest('.slide-management-item');
                if (!slideItem) return;

                const slideId = slideItem.dataset.slideId;

                if (e.target.closest('.edit-slide')) {
                    form.querySelector('[name="id"]').value = slideId;
                    form.querySelector('[name="title"]').value = slideItem.querySelector('h4').textContent;
                    form.querySelector('[name="description"]').value = slideItem.querySelector('p').textContent;
                    // Don't pre-fill the file input, but indicate an image exists.
                    form.querySelector('button[type="submit"]').textContent = 'Update Slide';
                    document.getElementById('cancel-slide-edit').style.display = 'inline-block';
                    form.scrollIntoView({ behavior: 'smooth' });
                }

                if (e.target.closest('.delete-slide')) {
                    this.handleDeleteSlide(slideId);
                }
            });

            document.getElementById('cancel-slide-edit').addEventListener('click', () => {
                form.reset();
                form.querySelector('button[type="submit"]').textContent = 'Add New Slide';
                document.getElementById('cancel-slide-edit').style.display = 'none';
            });
        }
    }

    // --- Revenue Details ---
    async showRevenueDetails() {
        const mainContent = document.getElementById('main-content');
        mainContent.innerHTML = this.getRevenueDashboardHTML();
        this.setupRevenueListeners();
        // Initial load with default date range (last 30 days)
        this.fetchAndRenderRevenue();
    }

    getRevenueDashboardHTML() {
        const today = new Date().toISOString().split('T')[0];
        const thirtyDaysAgo = new Date(new Date().setDate(new Date().getDate() - 30)).toISOString().split('T')[0];

        return `
            <div class="revenue-dashboard">
                <div class="section-title">
                    <h2>Revenue Analytics</h2>
                    <button class="btn-secondary" id="back-to-admin-dash" style="width: auto;">
                        <i class="fas fa-arrow-left"></i> Back to Dashboard
                    </button>
                </div>

                <div class="filters-container">
                    <div class="form-group">
                        <label for="start-date">Start Date</label>
                        <input type="date" id="start-date" value="${thirtyDaysAgo}">
                    </div>
                    <div class="form-group">
                        <label for="end-date">End Date</label>
                        <input type="date" id="end-date" value="${today}">
                    </div>
                    <button class="btn-primary" id="apply-revenue-filter" style="width: auto;">Apply</button>
                </div>

                <div id="revenue-chart-container" class="chart-container">
                    <div class="loading">Loading chart data...</div>
                </div>

                <div id="revenue-table-container" class="table-container">
                    <div class="loading">Loading table data...</div>
                </div>
            </div>
        `;
    }

    setupRevenueListeners() {
        document.getElementById('back-to-admin-dash')?.addEventListener('click', () => {
            this.app.loadAdminDashboard();
        });
        document.getElementById('apply-revenue-filter')?.addEventListener('click', () => {
            this.fetchAndRenderRevenue();
        });
    }

    async fetchAndRenderRevenue() {
        const startDate = document.getElementById('start-date').value;
        const endDate = document.getElementById('end-date').value;

        const chartContainer = document.getElementById('revenue-chart-container');
        const tableContainer = document.getElementById('revenue-table-container');
        chartContainer.innerHTML = '<div class="loading">Loading chart data...</div>';
        tableContainer.innerHTML = '<div class="loading">Loading table data...</div>';

        try {
            const response = await fetch(`api/admin/revenue.php?start_date=${startDate}&end_date=${endDate}`);
            const data = await response.json();

            if (data.success) {
                this.renderRevenueChart(chartContainer, data.breakdown);
                this.renderRevenueTable(tableContainer, data.breakdown);
            } else {
                throw new Error(data.message);
            }
        } catch (error) {
            chartContainer.innerHTML = `<div class="error">${error.message}</div>`;
            tableContainer.innerHTML = '';
        }
    }

    renderRevenueChart(container, data) {
        if (data.length === 0) {
            container.innerHTML = '<div class="empty-state">No revenue data for this period.</div>';
            return;
        }
        const maxRevenue = Math.max(...data.map(d => parseFloat(d.total_revenue)));
        const chartBars = data.map(d => `
            <div class="bar" style="height: ${(d.total_revenue / maxRevenue * 100)}%;" title="$${parseFloat(d.total_revenue).toFixed(2)} on ${d.period}">
                <div class="bar-label">${new Date(d.period + 'T00:00:00').toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</div>
            </div>
        `).join('');
        container.innerHTML = `<div class="bar-chart">${chartBars}</div>`;
    }

    renderRevenueTable(container, data) {
        if (data.length === 0) {
            container.innerHTML = '';
            return;
        }
        const tableRows = data.map(d => `
            <tr>
                <td>${new Date(d.period + 'T00:00:00').toLocaleDateString()}</td>
                <td>$${parseFloat(d.delivery_revenue).toFixed(2)}</td>
                <td>$${parseFloat(d.order_revenue).toFixed(2)}</td>
                <td>$${parseFloat(d.total_revenue).toFixed(2)}</td>
            </tr>
        `).join('');
        container.innerHTML = `
            <table>
                <thead>
                    <tr><th>Date</th><th>Delivery Revenue</th><th>Shop Order Revenue</th><th>Total Revenue</th></tr>
                </thead>
                <tbody>${tableRows}</tbody>
            </table>
        `;
    }
};
