
class AdminDashboard {
    constructor() {
        this.token = localStorage.getItem('token');
        this.user = JSON.parse(localStorage.getItem('user') || '{}');
        this.currentView = 'overview';
        this.currentMenuSubView = 'categories'; // For Menu tab sub-navigation
        this.restaurants = [];
        this.users = [];
        this.categories = [];
        this.categoryTypes = [];
        this.menuItems = [];
        this.promotions = [];
        this.celebrationMenus = [];
        this.hotItems = [];

        this.currentRestaurantId = null;
        this.selectedCategoryFilters = new Set();
        this.selectedMenuType = null; // Currently selected menu type for hierarchical navigation
        this.submittingForms = new Set(); // Track forms being submitted to prevent double submission
        this.totalMenuItemsCount = 0; // Total menu items count for super admin
        

        this.restaurantSearchTerm = '';
        this.restaurantStatusFilter = 'all';
        

        this.userSearchTerm = '';
        this.userStatusFilter = 'all';
        this.userRestaurantFilter = 'all';
        

        this.menuItemSearchTerm = '';
        this.menuItemSaleFilter = 'all';
        this.menuItemVisibilityFilter = 'all';
        this.menuItemSortBy = 'display_order';
        this.menuItemSortOrder = 'asc';
        

        this.currentDotStyle = 'square';
        this.currentCornerStyle = 'square';
        
        this.init();
    }

    async init() {
        if (!this.token || !this.user.id) {
            window.location.href = '/admin';
            return;
        }
        axios.defaults.headers.common['Authorization'] = `Bearer ${this.token}`;

        await this.loadData();
        this.render();
        this.setupEventListeners();
        

        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('changePassword') === '1' || this.user.must_change_password) {
            this.showPasswordChangeModal();
        }
    }
    preventDoubleSubmission(formId, submitButton) {
        if (this.submittingForms.has(formId)) {
            return false; // Already submitting, prevent duplicate
        }
        
        this.submittingForms.add(formId);
        

        const originalText = submitButton.innerHTML;
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing...';
        

        submitButton.dataset.originalText = originalText;
        
        return true; // Allow submission
    }
    
    restoreSubmissionState(formId, submitButton) {
        this.submittingForms.delete(formId);
        

        submitButton.disabled = false;
        submitButton.innerHTML = submitButton.dataset.originalText || submitButton.innerHTML;
        delete submitButton.dataset.originalText;
    }

    async loadData() {
        try {

            if (this.user.role === 'super_admin') {
                try {
                    await axios.post('/api/admin/restaurants/deactivate-expired');
                } catch (error) {
                    console.error('Error auto-deactivating expired restaurants:', error);
                }
            }
            const restaurantResponse = await axios.get('/api/restaurants');
            if (restaurantResponse.data.success) {
                this.restaurants = restaurantResponse.data.data;
            }
            if (this.user.role === 'super_admin') {
                try {
                    const userResponse = await axios.get('/api/admin/users');
                    if (userResponse.data.success) {
                        this.users = userResponse.data.data;
                    }
                } catch (error) {
                    console.error('Error loading users:', error);
                }
                
                try {
                    const totalMenuItemsResponse = await axios.get('/api/admin/total-menu-items');
                    if (totalMenuItemsResponse.data.success) {
                        this.totalMenuItemsCount = totalMenuItemsResponse.data.data;
                    }
                } catch (error) {
                    console.error('Error loading total menu items count:', error);
                }
            }
            this.currentRestaurantId = this.user.restaurant_id || (this.restaurants.length > 0 ? this.restaurants[0].id : null);
            if (this.currentRestaurantId) {
                await this.loadRestaurantData(this.currentRestaurantId);
            }
        } catch (error) {
            console.error('Error loading data:', error);
            if (error.response && error.response.status === 401) {
                this.logout();
            }
        }
    }

    async loadRestaurantData(restaurantId) {
        try {

            const categoryTypesResponse = await axios.get(`/api/admin/restaurants/${restaurantId}/category-types`);
            if (categoryTypesResponse.data.success) {
                this.categoryTypes = categoryTypesResponse.data.data;
            }
            const allCategories = [];
            for (const type of this.categoryTypes) {
                const response = await axios.get(`/api/admin/restaurants/${restaurantId}/categories?type=${encodeURIComponent(type.name)}`);
                if (response.data.success) {
                    allCategories.push(...response.data.data);
                }
            }
            
            this.categories = allCategories;
            this.selectedCategoryFilters.clear();
            

            const itemsResponse = await axios.get(`/api/admin/restaurants/${restaurantId}/menu-items`);
            if (itemsResponse.data.success) {
                this.menuItems = itemsResponse.data.data;
            }
            const promotionsResponse = await axios.get(`/api/admin/restaurants/${restaurantId}/promotions`);
            if (promotionsResponse.data.success) {
                this.promotions = promotionsResponse.data.data;
            }
            const celebrationMenusResponse = await axios.get(`/api/admin/restaurants/${restaurantId}/celebration-menus`);
            if (celebrationMenusResponse.data.success) {
                this.celebrationMenus = celebrationMenusResponse.data.data;
            }
            const hotItemsResponse = await axios.get(`/api/admin/restaurants/${restaurantId}/hot-items`);
            if (hotItemsResponse.data.success) {
                this.hotItems = hotItemsResponse.data.data;
            }

        } catch (error) {
            console.error('Error loading restaurant data:', error);
        }
    }

    async changeRestaurant(restaurantId) {
        this.currentRestaurantId = parseInt(restaurantId);
        await this.loadRestaurantData(this.currentRestaurantId);
        this.render();
    }

    getCurrentRestaurantSlug() {
        const restaurant = this.restaurants.find(r => r.id === this.currentRestaurantId);
        return restaurant ? restaurant.slug : null;
    }
    handleCategoryFilterChange(categoryId) {
        this.selectedCategoryFilters.clear();
        if (categoryId) {
            this.selectedCategoryFilters.add(parseInt(categoryId));
        }
        this.loadRestaurantDataWithFilter();
    }
    
    clearCategoryFilter() {
        this.selectedCategoryFilters.clear();
        const dropdown = document.getElementById('category-filter-dropdown');
        if (dropdown) dropdown.value = '';
        this.loadRestaurantDataWithFilter();
    }
    
    selectMenuType(typeName) {
        this.selectedMenuType = typeName;
        // Clear category filter when changing type
        this.selectedCategoryFilters.clear();
        this.loadRestaurantDataWithFilter();
    }
    
    clearAllMenuFilters() {
        this.selectedMenuType = null;
        this.selectedCategoryFilters.clear();
        this.loadRestaurantDataWithFilter();
    }
    
    async loadRestaurantDataWithFilter() {
        if (!this.currentRestaurantId) return;
        
        try {

            let url = `/api/admin/restaurants/${this.currentRestaurantId}/menu-items`;
            if (this.selectedCategoryFilters.size > 0) {
                const categoryIds = Array.from(this.selectedCategoryFilters).join(',');
                url += `?categories=${categoryIds}`;
            }
            
            const itemsResponse = await axios.get(url);
            if (itemsResponse.data.success) {
                this.menuItems = itemsResponse.data.data;
            }
            
            this.render();
        } catch (error) {
            console.error('Error loading filtered menu items:', error);
        }
    }
    handleMenuItemSearch(searchTerm) {
        this.menuItemSearchTerm = searchTerm;
        this.updateMenuItemsTable();
    }

    handleSaleFilter(filter) {
        this.menuItemSaleFilter = filter;
        this.updateMenuItemsTable();
    }

    handleVisibilityFilter(filter) {
        this.menuItemVisibilityFilter = filter;
        this.updateMenuItemsTable();
    }

    handleSortBy(sortBy) {
        if (this.menuItemSortBy === sortBy) {

            this.menuItemSortOrder = this.menuItemSortOrder === 'asc' ? 'desc' : 'asc';
        } else {
            this.menuItemSortBy = sortBy;
            this.menuItemSortOrder = 'asc';
        }
        this.updateMenuItemsTable();
    }

    sortByColumn(column) {
        this.handleSortBy(column);
    }

    toggleSortOrder() {
        this.menuItemSortOrder = this.menuItemSortOrder === 'asc' ? 'desc' : 'asc';
        this.updateMenuItemsTable();
    }
    updateMenuItemsTable() {
        const tableBody = document.getElementById('menuItemsTableBody');
        if (!tableBody) {

            this.render();
            return;
        }
        const targetRestaurantId = this.currentRestaurantId;
        if (!targetRestaurantId) return;

        let filteredMenuItems = this.menuItems;
        

        if (this.selectedCategoryFilters.size > 0) {
            filteredMenuItems = filteredMenuItems.filter(item => this.selectedCategoryFilters.has(item.category_id));
        }
        

        if (this.menuItemSearchTerm.trim()) {
            const searchTerm = this.menuItemSearchTerm.toLowerCase();
            filteredMenuItems = filteredMenuItems.filter(item => 
                item.name.toLowerCase().includes(searchTerm) ||
                (item.description && item.description.toLowerCase().includes(searchTerm))
            );
        }
        

        if (this.menuItemSaleFilter === 'on_sale') {
            filteredMenuItems = filteredMenuItems.filter(item => item.is_on_sale);
        } else if (this.menuItemSaleFilter === 'not_on_sale') {
            filteredMenuItems = filteredMenuItems.filter(item => !item.is_on_sale);
        }
        

        if (this.menuItemVisibilityFilter === 'visible') {
            filteredMenuItems = filteredMenuItems.filter(item => item.is_visible);
        } else if (this.menuItemVisibilityFilter === 'hidden') {
            filteredMenuItems = filteredMenuItems.filter(item => !item.is_visible);
        }
        

        filteredMenuItems.sort((a, b) => {
            let aVal, bVal;
            switch (this.menuItemSortBy) {
                case 'name':
                    aVal = a.name.toLowerCase();
                    bVal = b.name.toLowerCase();
                    break;
                case 'price':
                    aVal = parseFloat(a.price);
                    bVal = parseFloat(b.price);
                    break;
                case 'category':
                    const aCat = this.categories.find(c => c.id === a.category_id);
                    const bCat = this.categories.find(c => c.id === b.category_id);
                    aVal = aCat ? aCat.name.toLowerCase() : '';
                    bVal = bCat ? bCat.name.toLowerCase() : '';
                    break;
                case 'sale_status':
                    aVal = a.is_on_sale ? 1 : 0;
                    bVal = b.is_on_sale ? 1 : 0;
                    break;
                case 'visibility':
                    aVal = a.is_visible ? 1 : 0;
                    bVal = b.is_visible ? 1 : 0;
                    break;
                case 'display_order':
                default:
                    const aCatOrder = this.categories.find(c => c.id === a.category_id)?.display_order || 0;
                    const bCatOrder = this.categories.find(c => c.id === b.category_id)?.display_order || 0;
                    if (aCatOrder !== bCatOrder) {
                        aVal = aCatOrder;
                        bVal = bCatOrder;
                    } else {
                        aVal = a.display_order;
                        bVal = b.display_order;
                    }
                    break;
            }

            if (typeof aVal === 'string') {
                return this.menuItemSortOrder === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
            } else {
                return this.menuItemSortOrder === 'asc' ? aVal - bVal : bVal - aVal;
            }
        });
        const tableRowsHTML = filteredMenuItems.map(item => {
            const category = this.categories.find(c => c.id === item.category_id);
            
            return `
                <tr ${this.isMobileDevice() ? '' : 'draggable="true"'} data-item-id="${item.id}" class="menu-item-row ${this.isMobileDevice() ? '' : 'cursor-move'} ${!item.is_visible ? 'bg-red-50 opacity-75' : 'hover:bg-gray-50'}">
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            ${this.isMobileDevice() ? `
                                <div class="flex flex-col space-y-1 mr-3">
                                    <button onclick="dashboard.moveMenuItem(${item.id}, 'up')" 
                                            class="bg-blue-100 text-blue-700 hover:bg-blue-200 p-1.5 rounded border border-blue-300 shadow-sm transition-colors">
                                        <i class="fas fa-chevron-up text-sm"></i>
                                    </button>
                                    <button onclick="dashboard.moveMenuItem(${item.id}, 'down')" 
                                            class="bg-blue-100 text-blue-700 hover:bg-blue-200 p-1.5 rounded border border-blue-300 shadow-sm transition-colors">
                                        <i class="fas fa-chevron-down text-sm"></i>
                                    </button>
                                </div>
                            ` : `
                                <div class="text-gray-400 mr-3 drag-handle">
                                    <i class="fas fa-grip-vertical"></i>
                                </div>
                            `}
                            ${item.image_url ? `
                                <img src="${item.image_url}" alt="${item.name}" 
                                     class="w-10 h-10 rounded object-cover mr-3">
                            ` : `
                                <div class="w-10 h-10 rounded bg-gray-200 flex items-center justify-center mr-3">
                                    <i class="fas fa-image text-gray-400"></i>
                                </div>
                            `}
                            <div class="flex-1">
                                <div class="text-sm font-medium text-gray-900 flex items-center">
                                    ${item.name}
                                    ${!item.is_visible ? `<span class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800"><i class="fas fa-eye-slash mr-1"></i>Hidden</span>` : ''}
                                </div>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ${category ? category.name : 'Uncategorized'}
                        <div class="text-xs text-gray-500">${category ? category.type : ''}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ${item.price} ден.
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        ${item.is_on_sale ? `
                            <div class="text-sm text-red-600 font-medium">
                                <i class="fas fa-tag mr-1"></i>
                                ${item.sale_type === 'percentage' ? `${item.sale_value}% OFF` : `${item.sale_value} ден. OFF`}
                            </div>
                        ` : `
                            <div class="text-sm text-gray-500">
                                <i class="fas fa-minus mr-1"></i>
                                No Sale
                            </div>
                        `}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ${item.size_info || '-'}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <div class="flex justify-end space-x-2">
                            <button onclick="dashboard.toggleItemVisibility(${item.id}, ${!item.is_visible})"
                                    class="${item.is_visible ? 'text-yellow-600 hover:text-yellow-800' : 'text-green-600 hover:text-green-800'} transition-colors"
                                    title="${item.is_visible ? 'Hide from menu' : 'Show in menu'}">
                                <i class="fas fa-eye${item.is_visible ? '-slash' : ''} text-lg"></i>
                            </button>
                            <button onclick="dashboard.editMenuItem(${item.id})"
                                    class="text-blue-600 hover:text-blue-900 transition-colors"
                                    title="Edit item">
                                <i class="fas fa-edit text-lg"></i>
                            </button>
                            <button onclick="dashboard.duplicateMenuItem(${item.id})"
                                    class="text-purple-600 hover:text-purple-900 transition-colors"
                                    title="Duplicate item">
                                <i class="fas fa-copy text-lg"></i>
                            </button>
                            <button onclick="dashboard.deleteMenuItem(${item.id})"
                                    class="text-red-600 hover:text-red-900 transition-colors"
                                    title="Delete item">
                                <i class="fas fa-trash text-lg"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }).join('');
        tableBody.innerHTML = tableRowsHTML;
        if (!this.isMobileDevice()) {
            this.initializeDragAndDrop();
        }
    }

    clearAllFilters() {
        this.selectedCategoryFilters.clear();
        this.menuItemSearchTerm = '';
        this.menuItemSaleFilter = 'all';
        this.menuItemVisibilityFilter = 'all';
        this.menuItemSortBy = 'display_order';
        this.menuItemSortOrder = 'asc';
        

        const searchInput = document.getElementById('menu-search');
        if (searchInput) searchInput.value = '';
        
        const saleFilter = document.getElementById('sale-filter');
        if (saleFilter) saleFilter.value = 'all';
        
        const visibilityFilter = document.getElementById('visibility-filter');
        if (visibilityFilter) visibilityFilter.value = 'all';
        
        const sortBy = document.getElementById('sort-by');
        if (sortBy) sortBy.value = 'display_order';
        
        this.updateMenuItemsTable();
    }

    toggleFiltersPanel() {
        const panel = document.getElementById('filters-panel');
        const icon = document.getElementById('filters-toggle-icon');
        
        if (panel && icon) {
            const isHidden = panel.classList.contains('hidden');
            
            if (isHidden) {
                panel.classList.remove('hidden');
                icon.classList.remove('fa-chevron-down');
                icon.classList.add('fa-chevron-up');
            } else {
                panel.classList.add('hidden');
                icon.classList.remove('fa-chevron-up');
                icon.classList.add('fa-chevron-down');
            }
        }
    }

    renderRestaurantSelector(context = '') {
        if (this.user.role !== 'super_admin' || !this.restaurants.length) {
            return '';
        }

        const currentRestaurantId = this.currentRestaurantId || this.restaurants[0]?.id;
        
        return `
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">Select Restaurant:</label>
                <select id="restaurant-selector-${context}" 
                        onchange="dashboard.changeRestaurantForContext('${context}', this.value)" 
                        class="border border-gray-300 rounded-lg px-3 py-2 bg-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                    ${this.restaurants.map(restaurant => `
                        <option value="${restaurant.id}" ${restaurant.id === currentRestaurantId ? 'selected' : ''}>
                            ${restaurant.name}
                        </option>
                    `).join('')}
                </select>
            </div>
        `;
    }

    changeRestaurantForContext(context, restaurantId) {
        const id = parseInt(restaurantId);
        this.currentRestaurantId = id;
        
        if (context === 'qr-code') {

            this.render();

            setTimeout(() => this.loadQRCode(), 100);
        } else {

            this.changeRestaurant(id);
        }
    }

    logout() {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = '/';
    }

    switchView(view) {

        if (view === 'categories') {
            this.currentView = 'menu';
            this.currentMenuSubView = 'categories';
        } else if (view === 'menu-items') {
            this.currentView = 'menu';
            this.currentMenuSubView = 'menu-items';

        } else {
            this.currentView = view;
        }
        
        this.render();
        

        if ((this.currentView === 'menu' && this.currentMenuSubView === 'categories') && !this.isMobileDevice()) {
            setTimeout(() => {
                this.setupCategoryTypeDragDrop();
                this.setupCategoryDragDrop();
            }, 100);
        }
        if ((this.currentView === 'menu' && this.currentMenuSubView === 'menu-items') && !this.isMobileDevice()) {
            setTimeout(() => this.setupDragAndDrop(), 100);
        }
        if (view === 'csv-upload') {
            setTimeout(() => this.setupCSVUploadEvents(), 100);
        }
    }

    setupEventListeners() {

        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal-backdrop')) {
                this.closeModal();
            }
        });
        

        document.addEventListener('change', (e) => {
            if (e.target.id === 'excelFileInput') {
                this.handleExcelFileChange(e);
            }
            

            if (e.target.id === 'qr-color-dark') {
                const textInput = document.getElementById('qr-color-dark-text');
                if (textInput) textInput.value = e.target.value;
            }
            if (e.target.id === 'qr-color-light') {
                const textInput = document.getElementById('qr-color-light-text');
                if (textInput) textInput.value = e.target.value;
            }
            if (e.target.id === 'qr-color-dark-text') {
                const colorInput = document.getElementById('qr-color-dark');
                if (colorInput) colorInput.value = e.target.value;
            }
            if (e.target.id === 'qr-color-light-text') {
                const colorInput = document.getElementById('qr-color-light');
                if (colorInput) colorInput.value = e.target.value;
            }
            

            
            if (e.target.id === 'qr-logo-background') {
                const options = document.getElementById('qr-logo-bg-options');
                if (options) {
                    options.style.display = e.target.checked ? 'grid' : 'none';
                }
            }
        });
        

        document.addEventListener('click', (e) => {
            if (e.target.closest('[onclick*="switchView"]') && e.target.textContent?.includes('QR Code')) {
                setTimeout(() => this.loadQRCode(), 100);
            }
        });
        

        if (!this.isMobileDevice()) {
            this.setupDragAndDrop();
        }
    }

    setupDragAndDrop() {

        document.removeEventListener('dragstart', this.handleDragStart);
        document.removeEventListener('dragover', this.handleDragOver);
        document.removeEventListener('drop', this.handleDrop);
        

        document.addEventListener('dragstart', this.handleDragStart.bind(this));
        document.addEventListener('dragover', this.handleDragOver.bind(this));
        document.addEventListener('drop', this.handleDrop.bind(this));
        document.addEventListener('dragend', this.handleDragEnd.bind(this));
    }

    handleDragStart(e) {
        if (e.target.classList.contains('menu-item-row')) {
            e.target.style.opacity = '0.5';
            e.dataTransfer.setData('text/plain', e.target.dataset.itemId);
            this.draggedElement = e.target;
        }
    }

    handleDragOver(e) {
        e.preventDefault();
        const row = e.target.closest('.menu-item-row');
        if (row && row !== this.draggedElement) {
            row.style.borderTop = '3px solid #3B82F6';
        }
    }

    handleDragEnd(e) {
        if (e.target.classList.contains('menu-item-row')) {
            e.target.style.opacity = '';
        }

        document.querySelectorAll('.menu-item-row').forEach(row => {
            row.style.borderTop = '';
        });
    }

    async handleDrop(e) {
        e.preventDefault();
        const dropTarget = e.target.closest('.menu-item-row');
        
        if (dropTarget && this.draggedElement && dropTarget !== this.draggedElement) {
            const draggedId = parseInt(this.draggedElement.dataset.itemId);
            const targetId = parseInt(dropTarget.dataset.itemId);
            
            await this.reorderMenuItems(draggedId, targetId);
        }
        

        document.querySelectorAll('.menu-item-row').forEach(row => {
            row.style.borderTop = '';
            row.style.opacity = '';
        });
        this.draggedElement = null;
    }

    setupCategoryTypeDragDrop() {
        const typeCards = document.querySelectorAll('.category-type-card');
        
        typeCards.forEach(card => {
            card.addEventListener('dragstart', (e) => {

                if (e.target.closest('.category-item') || e.target.closest('button') || e.target.closest('.space-y-2')) {
                    e.preventDefault();
                    return;
                }
                
                const typeId = card.dataset.typeId;
                if (typeId) {
                    e.dataTransfer.setData('text/plain', typeId);
                    e.target.classList.add('opacity-50');
                    this.draggedTypeElement = e.target;
                } else {
                    e.preventDefault();
                }
            });

            card.addEventListener('dragend', (e) => {
                e.target.classList.remove('opacity-50');

                document.querySelectorAll('.category-type-card').forEach(c => {
                    c.classList.remove('border-blue-300', 'bg-blue-50');
                });
            });

            card.addEventListener('dragover', (e) => {
                e.preventDefault();
                

                document.querySelectorAll('.category-type-card').forEach(c => {
                    c.classList.remove('border-blue-300', 'bg-blue-50');
                });
                

                const dropTarget = e.target.closest('.category-type-card');
                if (dropTarget && dropTarget !== this.draggedTypeElement) {
                    dropTarget.classList.add('border-blue-300', 'bg-blue-50');
                }
            });

            card.addEventListener('drop', async (e) => {
                e.preventDefault();
                e.stopPropagation(); // Prevent bubbling to category items
                
                const draggedTypeId = parseInt(e.dataTransfer.getData('text/plain'));
                const dropTarget = e.target.closest('.category-type-card');
                
                if (dropTarget && dropTarget !== this.draggedTypeElement) {
                    const targetTypeId = parseInt(dropTarget.dataset.typeId);
                    
                    if (draggedTypeId !== targetTypeId) {
                        await this.reorderCategoryTypes(draggedTypeId, targetTypeId);
                    }
                }
                

                document.querySelectorAll('.category-type-card').forEach(c => {
                    c.classList.remove('border-blue-300', 'bg-blue-50', 'opacity-50');
                });
                this.draggedTypeElement = null;
            });
        });
    }

    setupCategoryDragDrop() {
        const categoryItems = document.querySelectorAll('.category-item');
        
        categoryItems.forEach(item => {
            item.addEventListener('dragstart', (e) => {

                if (e.target.closest('button')) {
                    e.preventDefault();
                    return;
                }
                
                e.dataTransfer.setData('text/plain', e.target.dataset.id);
                e.target.classList.add('opacity-50');
            });

            item.addEventListener('dragend', (e) => {
                e.target.classList.remove('opacity-50');

                document.querySelectorAll('.category-item').forEach(cat => {
                    cat.classList.remove('border-blue-300', 'bg-blue-50');
                });
            });

            item.addEventListener('dragover', (e) => {
                e.preventDefault();
                

                if (e.target.closest('button')) {
                    return;
                }
                

                document.querySelectorAll('.category-item').forEach(cat => {
                    cat.classList.remove('border-blue-300', 'bg-blue-50');
                });
                

                const dropTarget = e.target.closest('.category-item');
                if (dropTarget) {
                    dropTarget.classList.add('border-blue-300', 'bg-blue-50');
                }
            });

            item.addEventListener('drop', async (e) => {
                e.preventDefault();
                

                if (e.target.closest('button')) {
                    return;
                }
                
                const draggedId = parseInt(e.dataTransfer.getData('text/plain'));
                const dropTarget = e.target.closest('.category-item');
                
                if (dropTarget && draggedId) {
                    const targetId = parseInt(dropTarget.dataset.id);
                    const targetType = dropTarget.dataset.type;
                    
                    if (draggedId !== targetId) {
                        await this.reorderCategories(draggedId, targetId, targetType);
                    }
                }
                

                document.querySelectorAll('.category-item').forEach(cat => {
                    cat.classList.remove('border-blue-300', 'bg-blue-50', 'opacity-50');
                });
            });
        });
    }

    async reorderCategoryTypes(draggedId, targetId) {
        try {
            const sortedTypes = this.categoryTypes.sort((a, b) => a.display_order - b.display_order);
            
            const draggedIndex = sortedTypes.findIndex(t => t.id === draggedId);
            const targetIndex = sortedTypes.findIndex(t => t.id === targetId);

            if (draggedIndex === -1 || targetIndex === -1) return;
            const [draggedItem] = sortedTypes.splice(draggedIndex, 1);
            sortedTypes.splice(targetIndex, 0, draggedItem);
            const updatedTypes = sortedTypes.map((type, index) => ({
                id: type.id,
                display_order: index + 1
            }));

            const response = await axios.put('/api/admin/category-types/order', {
                types: updatedTypes
            });

            if (response.data.success) {

                updatedTypes.forEach(updated => {
                    const type = this.categoryTypes.find(t => t.id === updated.id);
                    if (type) {
                        type.display_order = updated.display_order;
                    }
                });
                

                this.render();
                

                setTimeout(() => {
                    this.setupCategoryTypeDragDrop();
                    this.setupCategoryDragDrop();
                }, 100);
            } else {
                alert('Failed to reorder category types. Please try again.');
            }
        } catch (error) {
            console.error('Error reordering category types:', error);
            alert('Error reordering category types. Please try again.');
        }
    }

    async reorderCategories(draggedId, targetId, type) {
        try {
            const categoriesOfType = this.categories
                .filter(c => c.type === type)
                .sort((a, b) => a.display_order - b.display_order);

            const draggedIndex = categoriesOfType.findIndex(c => c.id === draggedId);
            const targetIndex = categoriesOfType.findIndex(c => c.id === targetId);

            if (draggedIndex === -1 || targetIndex === -1) return;
            const [draggedItem] = categoriesOfType.splice(draggedIndex, 1);
            categoriesOfType.splice(targetIndex, 0, draggedItem);
            const updatedCategories = categoriesOfType.map((cat, index) => ({
                id: cat.id,
                display_order: index + 1
            }));

            const response = await axios.put('/api/admin/categories/order', {
                categories: updatedCategories
            });

            if (response.data.success) {

                updatedCategories.forEach(updated => {
                    const cat = this.categories.find(c => c.id === updated.id);
                    if (cat) {
                        cat.display_order = updated.display_order;
                    }
                });
                

                this.render();
            } else {
                alert('Failed to reorder categories. Please try again.');
            }
        } catch (error) {
            console.error('Error reordering categories:', error);
            alert('Error reordering categories. Please try again.');
        }
    }

    async reorderMenuItems(draggedId, targetId) {
        try {
            const draggedItem = this.menuItems.find(item => item.id === draggedId);
            const targetItem = this.menuItems.find(item => item.id === targetId);
            
            if (!draggedItem || !targetItem) return;
            

            const categoryItems = this.menuItems.filter(item => item.category_id === draggedItem.category_id)
                .sort((a, b) => a.display_order - b.display_order);
            

            const draggedIndex = categoryItems.findIndex(item => item.id === draggedId);
            categoryItems.splice(draggedIndex, 1);
            

            const targetIndex = categoryItems.findIndex(item => item.id === targetId);
            categoryItems.splice(targetIndex, 0, draggedItem);
            

            for (let i = 0; i < categoryItems.length; i++) {
                categoryItems[i].display_order = i + 1;
                

                await axios.put(`/api/admin/menu-items/${categoryItems[i].id}`, {
                    display_order: categoryItems[i].display_order
                });
            }
            

            await this.loadRestaurantData(this.currentRestaurantId);
            this.render();
            
        } catch (error) {
            console.error('Error reordering menu items:', error);
            alert('Error updating item order. Please try again.');
        }
    }

    showModal(title, content) {
        const modal = `
            <div class="modal-backdrop fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-screen overflow-y-auto">
                    <div class="flex items-center justify-between p-6 border-b border-gray-200">
                        <h3 class="text-lg font-medium text-gray-900">${title}</h3>
                        <button onclick="dashboard.closeModal()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="p-6">
                        ${content}
                    </div>
                </div>
            </div>
        `;
        document.body.insertAdjacentHTML('beforeend', modal);
        
        // Check and display Albanian fields after modal is shown
        setTimeout(() => {
            if (window.checkAndDisplayAlbanianFields && this.currentRestaurantId) {
                checkAndDisplayAlbanianFields(this.currentRestaurantId, this);
            }
        }, 100);
    }

    closeModal() {
        const modal = document.querySelector('.modal-backdrop');
        if (modal) {
            modal.remove();
        }
    }
    
    showBulkPriceUpdateModal() {
        const menuItems = this.menuItems.filter(item => item.restaurant_id === this.currentRestaurantId);
        
        if (menuItems.length === 0) {
            alert('No menu items available for this restaurant.');
            return;
        }
        
        const content = `
            <div class="space-y-4">
                <p class="text-gray-600 mb-4">Update prices for multiple menu items at once. Changes are saved automatically.</p>
                
                <!-- Search Box -->
                <div class="mb-4">
                    <input type="text" id="bulkPriceSearch" placeholder="Search by item name..." 
                           class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                           oninput="dashboard.filterBulkPriceItems(this.value)">
                </div>
                
                <!-- Items List -->
                <div class="max-h-96 overflow-y-auto border border-gray-200 rounded-lg">
                    <table class="w-full" id="bulkPriceTable">
                        <thead class="bg-gray-50 sticky top-0">
                            <tr>
                                <th class="px-4 py-2 text-left text-sm font-semibold text-gray-700">Item Name</th>
                                <th class="px-4 py-2 text-left text-sm font-semibold text-gray-700">Current Price (ден)</th>
                                <th class="px-4 py-2 text-left text-sm font-semibold text-gray-700">New Price (ден)</th>
                            </tr>
                        </thead>
                        <tbody id="bulkPriceTableBody">
                            ${menuItems.map(item => `
                                <tr class="border-t border-gray-200 bulk-price-row" data-item-name="${item.name_mk.toLowerCase()}">
                                    <td class="px-4 py-2 text-sm text-gray-900">${item.name_mk}</td>
                                    <td class="px-4 py-2 text-sm text-gray-600">${item.price}</td>
                                    <td class="px-4 py-2">
                                        <input type="number" 
                                               step="1" 
                                               min="0" 
                                               data-item-id="${item.id}"
                                               placeholder="${item.price}"
                                               class="w-full border border-gray-300 rounded px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bulk-price-input">
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
                
                <!-- Action Buttons -->
                <div class="flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="button" onclick="dashboard.submitBulkPriceUpdate()" 
                            class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700">
                        <i class="fas fa-check mr-2"></i>Update Prices
                    </button>
                </div>
            </div>
        `;
        
        this.showModal('Bulk Price Update', content);
    }
    
    filterBulkPriceItems(searchTerm) {
        const rows = document.querySelectorAll('.bulk-price-row');
        const lowerSearch = searchTerm.toLowerCase();
        
        rows.forEach(row => {
            const itemName = row.getAttribute('data-item-name');
            if (itemName.includes(lowerSearch)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }
    
    async submitBulkPriceUpdate() {
        const inputs = document.querySelectorAll('.bulk-price-input');
        const updates = [];
        
        inputs.forEach(input => {
            const newPrice = input.value.trim();
            if (newPrice !== '') {
                updates.push({
                    id: parseInt(input.getAttribute('data-item-id')),
                    price: parseFloat(newPrice)
                });
            }
        });
        
        if (updates.length === 0) {
            alert('Please enter at least one new price.');
            return;
        }
        
        try {
            const response = await axios.post('/api/admin/menu-items/bulk-price-update', {
                updates: updates
            });
            
            if (response.data.success) {
                alert(`Successfully updated ${response.data.details.updated} out of ${response.data.details.total} items.`);
                
                if (response.data.details.errors.length > 0) {
                    console.error('Errors:', response.data.details.errors);
                }
                
                // Reload menu items
                await this.loadRestaurantData(this.currentRestaurantId);
                this.updateMenuItemsTable();
                this.closeModal();
            } else {
                alert('Failed to update prices: ' + response.data.message);
            }
        } catch (error) {
            console.error('Error updating prices:', error);
            alert('Error updating prices: ' + (error.response?.data?.message || error.message));
        }
    }
    
    getSubscriptionStatus(restaurant) {

        if (!restaurant.subscription_end) return 'Active (Infinite)';
        
        const endDate = new Date(restaurant.subscription_end);
        const now = new Date();
        const daysLeft = Math.ceil((endDate - now) / (1000 * 60 * 60 * 24));
        
        if (daysLeft < 0) return 'Expired';
        if (daysLeft <= 30) return `${daysLeft} days left`;
        return 'Active';
    }
    getSubscriptionDates(restaurant) {
        if (!restaurant.subscription_start && !restaurant.subscription_end) {
            return 'Infinite subscription';
        }
        
        const startDate = restaurant.subscription_start ? new Date(restaurant.subscription_start).toLocaleDateString() : 'N/A';
        const endDate = restaurant.subscription_end ? new Date(restaurant.subscription_end).toLocaleDateString() : 'Infinite';
        
        return `${startDate} - ${endDate}`;
    }
    getDaysLeft(restaurant) {
        if (!restaurant.subscription_end) return null;
        
        const endDate = new Date(restaurant.subscription_end);
        const now = new Date();
        const daysLeft = Math.ceil((endDate - now) / (1000 * 60 * 60 * 24));
        
        return daysLeft;
    }
    updateRestaurantsTable() {
        const tableBody = document.getElementById('restaurantsTableBody');
        if (!tableBody) {

            this.render();
            return;
        }
        let filteredRestaurants = [...this.restaurants];
        const searchTerm = (this.restaurantSearchTerm || '').trim();
        if (searchTerm) {
            filteredRestaurants = filteredRestaurants.filter(restaurant =>
                restaurant.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                (restaurant.description && restaurant.description.toLowerCase().includes(searchTerm.toLowerCase())) ||
                (restaurant.email && restaurant.email.toLowerCase().includes(searchTerm.toLowerCase()))
            );
        }
        const statusFilter = this.restaurantStatusFilter || 'all';
        if (statusFilter !== 'all') {
            filteredRestaurants = filteredRestaurants.filter(restaurant =>
                statusFilter === 'active' ? restaurant.is_active : !restaurant.is_active
            );
        }
        const sortedRestaurants = filteredRestaurants.sort((a, b) => {
            const aCritical = this.isSubscriptionCritical(a);
            const bCritical = this.isSubscriptionCritical(b);
            if (aCritical && !bCritical) return -1;
            if (!aCritical && bCritical) return 1;
            return 0;
        });
        const tableRowsHTML = sortedRestaurants.map(restaurant => {
            const daysLeft = this.getSubscriptionDaysLeft(restaurant);
            const isCritical = this.isSubscriptionCritical(restaurant);
            
            return `
                <tr class="hover:bg-gray-50 ${isCritical ? 'bg-red-50 border-l-4 border-red-500' : ''}">
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            ${restaurant.logo_url ? 
                                `<img src="${restaurant.logo_url}" alt="Logo" class="w-8 h-8 rounded-full object-cover mr-3">` : 
                                `<div class="w-8 h-8 bg-gray-300 rounded-full flex items-center justify-center mr-3">
                                    <i class="fas fa-utensils text-gray-600 text-sm"></i>
                                </div>`
                            }
                            <div>
                                <div class="text-sm font-medium text-gray-900">${this.escapeHtml(restaurant.name)}</div>
                                <div class="text-sm text-gray-500">${restaurant.slug}</div>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-900">${this.escapeHtml(restaurant.email || 'N/A')}</div>
                        <div class="text-sm text-gray-500">${this.escapeHtml(restaurant.phone || 'N/A')}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-900">
                            ${restaurant.subscription_start ? new Date(restaurant.subscription_start).toLocaleDateString() : 'N/A'} - 
                            ${restaurant.subscription_end ? new Date(restaurant.subscription_end).toLocaleDateString() : 'N/A'}
                        </div>
                        ${restaurant.subscription_end ? `
                            <div class="text-xs ${isCritical ? 'text-red-600 font-semibold' : daysLeft <= 60 ? 'text-orange-600' : 'text-gray-500'}">
                                ${daysLeft > 0 ? `${daysLeft} days left` : `Expired ${Math.abs(daysLeft)} days ago`}
                                ${isCritical ? ' ⚠️' : ''}
                            </div>
                        ` : ''}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ${restaurant.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
                            ${restaurant.is_active ? 'Active' : 'Inactive'}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                        <button onclick="dashboard.editRestaurant(${restaurant.id})" class="text-indigo-600 hover:text-indigo-900">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        <button onclick="dashboard.toggleRestaurantStatus(${restaurant.id}, ${restaurant.is_active})" 
                                class="text-${restaurant.is_active ? 'red' : 'green'}-600 hover:text-${restaurant.is_active ? 'red' : 'green'}-900">
                            <i class="fas fa-${restaurant.is_active ? 'ban' : 'check'}"></i> ${restaurant.is_active ? 'Deactivate' : 'Activate'}
                        </button>
                        <button onclick="dashboard.deleteRestaurant(${restaurant.id})" class="text-red-600 hover:text-red-900">
                            <i class="fas fa-trash"></i> Delete
                        </button>
                    </td>
                </tr>
            `;
        }).join('');
        tableBody.innerHTML = tableRowsHTML;
    }
    updateUsersTable() {
        const tableBody = document.getElementById('usersTableBody');
        if (!tableBody) {

            this.render();
            return;
        }
        let filteredUsers = [...this.users];
        const searchTerm = (this.userSearchTerm || '').trim();
        if (searchTerm) {
            filteredUsers = filteredUsers.filter(user =>
                user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                user.email.toLowerCase().includes(searchTerm.toLowerCase())
            );
        }
        const statusFilter = this.userStatusFilter || 'all';
        if (statusFilter !== 'all') {
            filteredUsers = filteredUsers.filter(user =>
                statusFilter === 'active' ? user.is_active : !user.is_active
            );
        }
        const restaurantFilter = this.userRestaurantFilter || 'all';
        if (restaurantFilter !== 'all') {
            filteredUsers = filteredUsers.filter(user =>
                user.restaurant_id === parseInt(restaurantFilter)
            );
        }
        const tableRowsHTML = filteredUsers.map(user => {
            const restaurant = this.restaurants.find(r => r.id === user.restaurant_id);
            
            return `
                <tr class="hover:bg-gray-50">
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm font-medium text-gray-900">${this.escapeHtml(user.name)}</div>
                        <div class="text-sm text-gray-500">${this.escapeHtml(user.email)}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ${user.role === 'super_admin' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'}">
                            ${user.role === 'super_admin' ? 'Super Admin' : 'Restaurant Admin'}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ${restaurant ? this.escapeHtml(restaurant.name) : 'N/A'}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ${user.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
                            ${user.is_active ? 'Active' : 'Inactive'}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        ${user.created_at ? new Date(user.created_at).toLocaleDateString() : 'N/A'}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                        <button onclick="dashboard.editUser(${user.id})" class="text-indigo-600 hover:text-indigo-900">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        <button onclick="dashboard.resetUserPassword(${user.id})" class="text-yellow-600 hover:text-yellow-900">
                            <i class="fas fa-key"></i> Reset Password
                        </button>
                        <button onclick="dashboard.toggleUserStatus(${user.id}, ${user.is_active})" 
                                class="text-${user.is_active ? 'red' : 'green'}-600 hover:text-${user.is_active ? 'red' : 'green'}-900">
                            <i class="fas fa-${user.is_active ? 'ban' : 'check'}"></i> ${user.is_active ? 'Deactivate' : 'Activate'}
                        </button>
                        <button onclick="dashboard.deleteUser(${user.id})" class="text-red-600 hover:text-red-900">
                            <i class="fas fa-trash"></i> Delete
                        </button>
                    </td>
                </tr>
            `;
        }).join('');
        tableBody.innerHTML = tableRowsHTML;
    }
    filterRestaurants(searchTerm = '', statusFilter = 'all') {
        this.restaurantSearchTerm = (searchTerm || '').trim();
        this.restaurantStatusFilter = statusFilter;
        this.updateRestaurantsTable();
    }
    filterUsers(searchTerm = '', statusFilter = 'all', restaurantFilter = 'all') {
        this.userSearchTerm = (searchTerm || '').trim();
        this.userStatusFilter = statusFilter;
        this.userRestaurantFilter = restaurantFilter;
        this.updateUsersTable();
    }
    isSubscriptionCritical(restaurant) {
        if (!restaurant.subscription_end) return false;
        
        const endDate = new Date(restaurant.subscription_end);
        const now = new Date();
        const daysLeft = Math.ceil((endDate - now) / (1000 * 60 * 60 * 24));
        
        return daysLeft <= 30;
    }

    render() {
        const app = document.getElementById('app');
        
        app.innerHTML = `
            <!-- Header -->
            <div class="bg-white shadow-sm border-b border-gray-200">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center py-4 space-y-2 sm:space-y-0">
                        <div class="flex flex-col sm:flex-row sm:items-center space-y-1 sm:space-y-0 sm:space-x-4">
                            <h1 class="text-xl sm:text-2xl font-bold text-gray-900">
                                <i class="fas fa-cog mr-2 text-orange-600"></i>
                                <span class="hidden sm:inline">Admin Dashboard</span>
                                <span class="sm:hidden">Admin</span>
                            </h1>
                            <span class="text-xs sm:text-sm text-gray-500">
                                ${this.user.role === 'super_admin' ? 'Super Administrator' : 'Restaurant Manager'}
                            </span>
                        </div>
                        
                        <div class="flex flex-col sm:flex-row items-start sm:items-center space-y-2 sm:space-y-0 sm:space-x-4 w-full sm:w-auto">
                            <span class="text-xs sm:text-sm text-gray-700 order-2 sm:order-1">Welcome, ${this.user.name}</span>
                            <div class="order-3 sm:order-2">${this.renderSubscriptionBadge()}</div>
                            <div class="flex items-center space-x-2 sm:space-x-4 order-1 sm:order-3 self-end sm:self-auto">

                                <a href="/" class="text-gray-600 hover:text-gray-800 text-sm">
                                    <i class="fas fa-home mr-1"></i><span class="hidden sm:inline">Home</span>
                                </a>
                                <button onclick="dashboard.logout()" class="text-red-600 hover:text-red-800 text-sm">
                                    <i class="fas fa-sign-out-alt mr-1"></i><span class="hidden sm:inline">Logout</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Navigation -->
            <div class="bg-gray-50 border-b border-gray-200">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div class="overflow-x-auto scrollbar-hide">
                        <nav class="flex space-x-2 sm:space-x-6 min-w-max py-1">
                            ${this.renderNavItem('overview', 'tachometer-alt', window.t ? window.t('admin.overview') : 'Overview')}
                            ${this.user.role === 'super_admin' ? this.renderNavItem('restaurants', 'building', window.t ? window.t('admin.restaurants') : 'Restaurants') : ''}
                            ${this.user.role === 'super_admin' ? this.renderNavItem('users', 'users', window.t ? window.t('admin.users') : 'Users') : ''}
                            ${this.renderNavItem('menu', 'utensils', 'Menu')}
                            ${this.renderNavItem('qr-codes', 'qrcode', window.t ? window.t('admin.qr_codes') : 'QR Code')}
                            ${this.renderNavItem('csv-upload', 'file-import', 'Import/Export')}
                        </nav>
                    </div>
                </div>
            </div>

            <!-- Content -->
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                ${this.renderContent()}
            </div>
        `;
        window.dashboard = this;
    }

    renderSubscriptionBadge() {
        if (this.user.role !== 'restaurant_admin' || !this.user.restaurant_id) {
            return '';
        }

        const restaurant = this.restaurants.find(r => r.id === this.user.restaurant_id);
        if (!restaurant || !restaurant.subscription_end) {
            return '';
        }

        const status = this.getSubscriptionStatus(restaurant);
        const isCritical = this.isSubscriptionCritical(restaurant);
        
        return `
            <div class="flex items-center space-x-2">
                <span class="text-xs text-gray-500">Subscription:</span>
                <span class="px-2 py-1 text-xs font-semibold rounded-full ${
                    isCritical 
                        ? 'bg-red-100 text-red-800' 
                        : 'bg-green-100 text-green-800'
                }">
                    ${status}
                </span>
            </div>
        `;
    }

    renderNavItem(view, icon, label) {
        const isActive = this.currentView === view;
        return `
            <button onclick="dashboard.switchView('${view}')" 
                    class="py-3 px-2 sm:px-3 border-b-2 font-medium text-xs sm:text-sm transition-colors whitespace-nowrap flex-shrink-0 ${
                        isActive 
                            ? 'border-orange-600 text-orange-600' 
                            : 'border-transparent text-gray-500 hover:text-gray-700'
                    }">
                <i class="fas fa-${icon} mr-1 sm:mr-2"></i>
                <span class="hidden sm:inline">${label}</span>
                <span class="sm:hidden">${label.split(' ')[0]}</span>
            </button>
        `;
    }

    renderContent() {
        switch (this.currentView) {
            case 'overview':
                return this.renderOverview();
            case 'restaurants':
                return this.renderRestaurants();
            case 'users':
                return this.renderUsers();
            case 'menu':
                return this.renderMenu();
            case 'qr-codes':
                return this.renderQRCodes();
            case 'csv-upload':
                return this.renderCSVUpload();
            default:
                return this.renderOverview();
        }
    }

    renderOverview() {
        const userRestaurant = this.user.restaurant_id 
            ? this.restaurants.find(r => r.id === this.user.restaurant_id)
            : null;

        return `
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                ${this.user.role === 'super_admin' ? `
                    <div class="bg-white p-6 rounded-lg shadow-sm border">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <i class="fas fa-building text-2xl text-blue-600"></i>
                            </div>
                            <div class="ml-4">
                                <p class="text-sm font-medium text-gray-500">Restaurants</p>
                                <p class="text-2xl font-bold text-gray-900">${this.restaurants.length}</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-white p-6 rounded-lg shadow-sm border">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <i class="fas fa-users text-2xl text-green-600"></i>
                            </div>
                            <div class="ml-4">
                                <p class="text-sm font-medium text-gray-500">Users</p>
                                <p class="text-2xl font-bold text-gray-900">${this.users.length}</p>
                            </div>
                        </div>
                    </div>
                ` : ''}
                
                <div class="bg-white p-6 rounded-lg shadow-sm border">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <i class="fas fa-tags text-2xl text-purple-600"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">Categories</p>
                            <p class="text-2xl font-bold text-gray-900">${this.categories.length}</p>
                        </div>
                    </div>
                </div>
                
                <div class="bg-white p-6 rounded-lg shadow-sm border">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <i class="fas fa-utensils text-2xl text-orange-600"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">Menu Items</p>
                            <p class="text-2xl font-bold text-gray-900">${
                                this.user.role === 'super_admin' ? this.totalMenuItemsCount : this.menuItems.length
                            }</p>
                        </div>
                    </div>
                </div>
            </div>

            ${userRestaurant ? `
                <div class="bg-white rounded-lg shadow-sm border p-6 mb-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4 flex items-center justify-between">
                        <span>Your Restaurant</span>
                        ${userRestaurant.subscription_end ? `
                            <span class="px-3 py-1 text-sm font-semibold rounded-full ${
                                this.isSubscriptionCritical(userRestaurant) 
                                    ? 'bg-red-100 text-red-800' 
                                    : 'bg-green-100 text-green-800'
                            }">
                                Subscription: ${this.getSubscriptionStatus(userRestaurant)}
                            </span>
                        ` : ''}
                    </h3>
                    <div class="flex items-center space-x-4">
                        ${userRestaurant.logo_url ? `
                            <img src="${userRestaurant.logo_url}" alt="${userRestaurant.name}" 
                                 class="w-16 h-16 rounded-full object-cover">
                        ` : `
                            <div class="w-16 h-16 rounded-full bg-gray-200 flex items-center justify-center">
                                <i class="fas fa-building text-gray-400"></i>
                            </div>
                        `}
                        <div class="flex-1">
                            <div class="flex items-center justify-between mb-2">
                                <h4 class="text-xl font-bold text-gray-900">${userRestaurant.name}</h4>
                                <a href="/menu/${userRestaurant.slug}" target="_blank" 
                                   class="inline-flex items-center px-3 py-1.5 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700 transition-colors">
                                    <i class="fas fa-eye mr-2"></i>
                                    View Menu
                                </a>
                            </div>
                            ${userRestaurant.description ? `<p class="text-gray-600">${userRestaurant.description}</p>` : ''}
                            <div class="flex space-x-4 mt-2 text-sm text-gray-500">
                                ${userRestaurant.address ? `<span><i class="fas fa-map-marker-alt mr-1"></i>${userRestaurant.address}</span>` : ''}
                                ${userRestaurant.phone ? `<span><i class="fas fa-phone mr-1"></i>${userRestaurant.phone}</span>` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            ` : ''}

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Quick Actions</h3>
                    <div class="space-y-2">
                        <button onclick="dashboard.switchView('menu')" 
                                class="w-full text-left p-3 rounded-lg hover:bg-gray-50 flex items-center">
                            <i class="fas fa-utensils mr-3 text-orange-600"></i>
                            <span>Manage Menu</span>
                        </button>
                        ${this.user.role === 'restaurant_admin' && this.user.restaurant_id ? `
                            <button onclick="dashboard.editRestaurant(${this.user.restaurant_id})" 
                                    class="w-full text-left p-3 rounded-lg hover:bg-gray-50 flex items-center">
                                <i class="fas fa-edit mr-3 text-blue-600"></i>
                                <span>Edit Restaurant Info</span>
                            </button>
                        ` : ''}
                        ${this.user.role === 'super_admin' ? `
                            <button onclick="dashboard.switchView('restaurants')" 
                                    class="w-full text-left p-3 rounded-lg hover:bg-gray-50 flex items-center">
                                <i class="fas fa-building mr-3 text-blue-600"></i>
                                <span>Manage Restaurants</span>
                            </button>
                            <button onclick="dashboard.switchView('users')" 
                                    class="w-full text-left p-3 rounded-lg hover:bg-gray-50 flex items-center">
                                <i class="fas fa-users mr-3 text-green-600"></i>
                                <span>Manage Users</span>
                            </button>
                        ` : ''}
                    </div>
                </div>
                
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">System Status</h3>
                    <div class="space-y-2 text-sm text-gray-600">
                        <p><i class="fas fa-info-circle mr-2 text-blue-500"></i>Dashboard loaded successfully</p>
                        <p><i class="fas fa-check-circle mr-2 text-green-500"></i>All systems operational</p>
                        ${userRestaurant ? `<p><i class="fas fa-building mr-2 text-orange-500"></i>Managing: ${userRestaurant.name}</p>` : ''}
                    </div>
                </div>
            </div>
        `;
    }
    
    renderMenu() {
        const targetRestaurantId = this.currentRestaurantId;
        
        if (!targetRestaurantId) {
            return '<div class="text-center py-8 text-gray-600">No restaurant selected or available.</div>';
        }
        
        return `
            <div class="space-y-6">
                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 space-y-3 sm:space-y-0">
                    <h2 class="text-2xl font-bold text-gray-900">Menu Management</h2>
                    ${this.user.role === 'super_admin' ? `
                        <div class="w-full sm:w-auto">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Restaurant:</label>
                            <select id="restaurant-select" onchange="dashboard.changeRestaurant(this.value)" 
                                    class="border border-gray-300 rounded-lg px-3 py-2 min-w-[200px]">
                                ${this.restaurants.map(restaurant => `
                                    <option value="${restaurant.id}" ${restaurant.id === targetRestaurantId ? 'selected' : ''}>
                                        ${restaurant.name}
                                    </option>
                                `).join('')}
                            </select>
                        </div>
                    ` : ''}
                </div>
                
                <!-- Sub-navigation tabs -->
                <div class="bg-white border-b border-gray-200 rounded-t-lg">
                    <div class="overflow-x-auto admin-menu-nav">
                        <nav class="flex space-x-8 px-6 min-w-max" role="tablist">
                            ${this.renderMenuSubNavItem('categories', 'tags', 'Categories')}
                            ${this.renderMenuSubNavItem('menu-items', 'utensils', 'Menu Items')}
                            ${this.renderMenuSubNavItem('hot-items', 'fire', 'Hot Items')}
                            ${this.renderMenuSubNavItem('promotions', 'percentage', 'Promotions')}
                            ${this.renderMenuSubNavItem('celebration-menus', 'glass-cheers', 'Celebration Menu')}

                        </nav>
                    </div>
                </div>
                
                <!-- Content based on selected sub-view -->
                <div class="bg-white rounded-b-lg shadow-sm border border-t-0">
                    <div class="p-6">
                        ${this.renderMenuSubContent()}
                    </div>
                </div>
            </div>
        `;
    }
    
    renderMenuSubNavItem(subView, icon, label) {
        const isActive = this.currentMenuSubView === subView;
        return `
            <button onclick="dashboard.switchMenuSubView('${subView}')" 
                    class="py-4 px-1 border-b-2 font-medium text-sm transition-colors whitespace-nowrap ${
                        isActive 
                            ? 'border-orange-600 text-orange-600' 
                            : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                    }">
                <i class="fas fa-${icon} mr-2"></i>
                ${label}
            </button>
        `;
    }
    
    renderMenuSubContent() {
        switch (this.currentMenuSubView) {
            case 'categories':
                return this.renderCategoriesContent();
            case 'menu-items':
                return this.renderMenuItems();
            case 'hot-items':
                return this.renderHotItemsContent();
            case 'promotions':
                return this.renderPromotionsContent();
            case 'celebration-menus':
                return this.renderCelebrationMenusContent();

            default:
                return this.renderCategoriesContent();
        }
    }
    
    switchMenuSubView(subView) {
        this.currentMenuSubView = subView;
        this.render();
    }

    renderRestaurants() {
        if (this.user.role !== 'super_admin') {
            return '<div class="text-center py-8 text-red-600">Access denied. Super admin only.</div>';
        }
        let filteredRestaurants = [...this.restaurants];
        const searchTerm = (this.restaurantSearchTerm || '').trim();
        if (searchTerm) {
            filteredRestaurants = filteredRestaurants.filter(restaurant =>
                restaurant.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                (restaurant.description && restaurant.description.toLowerCase().includes(searchTerm.toLowerCase())) ||
                (restaurant.email && restaurant.email.toLowerCase().includes(searchTerm.toLowerCase()))
            );
        }
        const statusFilter = this.restaurantStatusFilter || 'all';
        if (statusFilter !== 'all') {
            filteredRestaurants = filteredRestaurants.filter(restaurant =>
                statusFilter === 'active' ? restaurant.is_active : !restaurant.is_active
            );
        }
        const sortedRestaurants = filteredRestaurants.sort((a, b) => {
            const aCritical = this.isSubscriptionCritical(a);
            const bCritical = this.isSubscriptionCritical(b);
            if (aCritical && !bCritical) return -1;
            if (!aCritical && bCritical) return 1;
            return 0;
        });

        return `
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                <h2 class="text-2xl font-bold text-gray-900">Restaurant Management</h2>
                <div class="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
                    <div class="flex flex-col sm:flex-row gap-2">
                        <input type="text" 
                               placeholder="Search restaurants..."
                               value="${this.restaurantSearchTerm || ''}"
                               oninput="dashboard.filterRestaurants(this.value, dashboard.restaurantStatusFilter)"
                               class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                        <select onchange="dashboard.filterRestaurants(dashboard.restaurantSearchTerm, this.value)"
                                class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                            <option value="all" ${(this.restaurantStatusFilter || 'all') === 'all' ? 'selected' : ''}>All Status</option>
                            <option value="active" ${this.restaurantStatusFilter === 'active' ? 'selected' : ''}>Active Only</option>
                            <option value="inactive" ${this.restaurantStatusFilter === 'inactive' ? 'selected' : ''}>Inactive Only</option>
                        </select>
                    </div>
                    <button onclick="dashboard.showAddRestaurantForm()" 
                            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 text-sm whitespace-nowrap">
                        <i class="fas fa-plus mr-2"></i>Add Restaurant
                    </button>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border overflow-hidden overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200"">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Restaurant</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Slug</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Contact</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Subscription</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="restaurantsTableBody" class="bg-white divide-y divide-gray-200">
                        ${sortedRestaurants.map(restaurant => `
                            <tr class="${this.isSubscriptionCritical(restaurant) ? 'bg-red-50' : ''}">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="flex items-center">
                                        ${restaurant.logo_url ? `
                                            <img src="${restaurant.logo_url}" alt="${restaurant.name}" 
                                                 class="w-10 h-10 rounded-full object-cover mr-3">
                                        ` : `
                                            <div class="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center mr-3">
                                                <i class="fas fa-building text-gray-400"></i>
                                            </div>
                                        `}
                                        <div class="max-w-xs">
                                            <div class="text-sm font-medium text-gray-900">${restaurant.name}</div>
                                            ${restaurant.description ? `
                                                <div class="text-sm text-gray-500 max-w-full overflow-x-auto" 
                                                     style="white-space: nowrap; scrollbar-width: thin; scrollbar-color: #d1d5db #f3f4f6;"
                                                     title="${restaurant.description}">
                                                    ${restaurant.description}
                                                </div>
                                            ` : ''}
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm text-gray-900 font-mono bg-gray-100 px-2 py-1 rounded text-xs">
                                        ${restaurant.slug || 'N/A'}
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm text-gray-900">
                                        ${restaurant.email ? `<div><i class="fas fa-envelope mr-1"></i>${restaurant.email}</div>` : ''}
                                        ${restaurant.phone ? `<div><i class="fas fa-phone mr-1"></i>${restaurant.phone}</div>` : ''}
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="space-y-1">
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                                            this.isSubscriptionCritical(restaurant) 
                                                ? 'bg-red-100 text-red-800' 
                                                : 'bg-green-100 text-green-800'
                                        }">
                                            ${this.getSubscriptionStatus(restaurant)}
                                        </span>
                                        <div class="text-xs text-gray-500">
                                            <div>${this.getSubscriptionDates(restaurant)}</div>
                                            ${this.getDaysLeft(restaurant) !== null ? `<div class="font-medium ${this.getDaysLeft(restaurant) <= 0 ? 'text-red-600' : this.getDaysLeft(restaurant) <= 30 ? 'text-orange-600' : 'text-green-600'}">${Math.abs(this.getDaysLeft(restaurant))} ${this.getDaysLeft(restaurant) <= 0 ? 'days overdue' : 'days left'}</div>` : ''}
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                                        restaurant.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                                    }">
                                        ${restaurant.is_active ? 'Active' : 'Inactive'}
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <button onclick="dashboard.editRestaurant(${restaurant.id})" 
                                            class="text-blue-600 hover:text-blue-900 mr-3">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button onclick="dashboard.toggleRestaurantStatus(${restaurant.id}, ${!restaurant.is_active})" 
                                            class="text-orange-600 hover:text-orange-900 mr-3" 
                                            title="${restaurant.is_active ? 'Deactivate' : 'Activate'} Restaurant">
                                        <i class="fas fa-${restaurant.is_active ? 'ban' : 'check-circle'}"></i>
                                    </button>
                                    <a href="/menu/${restaurant.slug}" target="_blank" 
                                       class="text-green-600 hover:text-green-900 mr-3"
                                       title="View Restaurant Menu">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <button onclick="dashboard.deleteRestaurant(${restaurant.id})" 
                                            class="text-red-600 hover:text-red-900">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;
    }

    renderUsers() {
        if (this.user.role !== 'super_admin') {
            return '<div class="text-center py-8 text-red-600">Access denied. Super admin only.</div>';
        }
        let filteredUsers = [...this.users];
        const searchTerm = (this.userSearchTerm || '').trim();
        if (searchTerm) {
            filteredUsers = filteredUsers.filter(user =>
                user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                user.email.toLowerCase().includes(searchTerm.toLowerCase())
            );
        }
        const statusFilter = this.userStatusFilter || 'all';
        if (statusFilter !== 'all') {
            filteredUsers = filteredUsers.filter(user =>
                statusFilter === 'active' ? user.is_active : !user.is_active
            );
        }
        const restaurantFilter = this.userRestaurantFilter || 'all';
        if (restaurantFilter !== 'all') {
            filteredUsers = filteredUsers.filter(user =>
                user.restaurant_id && user.restaurant_id.toString() === restaurantFilter.toString()
            );
        }

        return `
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                <h2 class="text-2xl font-bold text-gray-900">User Management</h2>
                <div class="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
                    <div class="flex flex-col sm:flex-row gap-2">
                        <input type="text" 
                               placeholder="Search users..."
                               value="${this.userSearchTerm || ''}"
                               oninput="dashboard.filterUsers(this.value, dashboard.userStatusFilter, dashboard.userRestaurantFilter)"
                               class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                        <select onchange="dashboard.filterUsers(dashboard.userSearchTerm, this.value, dashboard.userRestaurantFilter)"
                                class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                            <option value="all" ${(this.userStatusFilter || 'all') === 'all' ? 'selected' : ''}>All Status</option>
                            <option value="active" ${this.userStatusFilter === 'active' ? 'selected' : ''}>Active Only</option>
                            <option value="inactive" ${this.userStatusFilter === 'inactive' ? 'selected' : ''}>Inactive Only</option>
                        </select>
                        <select onchange="dashboard.filterUsers(dashboard.userSearchTerm, dashboard.userStatusFilter, this.value)"
                                class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                            <option value="all" ${(this.userRestaurantFilter || 'all') === 'all' ? 'selected' : ''}>All Restaurants</option>
                            ${this.restaurants.map(restaurant => `
                                <option value="${restaurant.id}" ${this.userRestaurantFilter && this.userRestaurantFilter.toString() === restaurant.id.toString() ? 'selected' : ''}>${restaurant.name}</option>
                            `).join('')}
                        </select>
                    </div>
                    <button onclick="dashboard.showAddUserForm()" 
                            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 text-sm whitespace-nowrap">
                        <i class="fas fa-plus mr-2"></i>Add User
                    </button>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border overflow-hidden overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">User</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Role</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Restaurant</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="usersTableBody" class="bg-white divide-y divide-gray-200">
                        ${filteredUsers.map(user => {
                            const restaurant = user.restaurant_id 
                                ? this.restaurants.find(r => r.id === user.restaurant_id)
                                : null;
                            
                            return `
                                <tr>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div>
                                            <div class="text-sm font-medium text-gray-900">${user.name}</div>
                                            <div class="text-sm text-gray-500">${user.email}</div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                                            user.role === 'super_admin' ? 'bg-red-100 text-red-800' : 'bg-blue-100 text-blue-800'
                                        }">
                                            ${user.role === 'super_admin' ? 'Super Admin' : 'Restaurant Admin'}
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        ${restaurant ? restaurant.name : 'N/A'}
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                                            user.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                                        }">
                                            ${user.is_active ? 'Active' : 'Inactive'}
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                        <button onclick="dashboard.toggleUserStatus(${user.id}, ${!user.is_active})" 
                                                class="text-purple-600 hover:text-purple-900 mr-3"
                                                ${user.id === this.user.id ? 'disabled title="Cannot deactivate yourself"' : ''}
                                                title="${user.is_active ? 'Deactivate' : 'Activate'} User">
                                            <i class="fas fa-${user.is_active ? 'user-slash' : 'user-check'}"></i>
                                        </button>
                                        <button onclick="dashboard.resetPassword(${user.id})" 
                                                class="text-orange-600 hover:text-orange-900 mr-3">
                                            <i class="fas fa-key"></i>
                                        </button>
                                        <button onclick="dashboard.deleteUser(${user.id})" 
                                                class="text-red-600 hover:text-red-900"
                                                ${user.id === this.user.id ? 'disabled title="Cannot delete yourself"' : ''}>
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            `;
                        }).join('')}
                    </tbody>
                </table>
            </div>
        `;
    }

    renderCategories() {
        return this.renderCategoriesContent();
    }
    
    renderCategoriesContent() {
        const targetRestaurantId = this.currentRestaurantId;
        
        if (!targetRestaurantId) {
            return '<div class="text-center py-8 text-gray-600">No restaurant selected or available.</div>';
        }
        const typeIcons = {
            'Food': 'fas fa-hamburger',
            'Drinks': 'fas fa-cocktail',
            'Desserts': 'fas fa-birthday-cake',
            'Appetizers': 'fas fa-utensils',
            'Beverages': 'fas fa-coffee'
        };

        const typeColors = {
            'Food': 'orange-600',
            'Drinks': 'blue-600', 
            'Desserts': 'pink-600',
            'Appetizers': 'green-600',
            'Beverages': 'purple-600'
        };

        return `
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-lg font-semibold text-gray-900">Categories</h3>
                <div class="flex flex-wrap gap-2">
                    <button onclick="dashboard.showAddCategoryTypeForm()" 
                            class="bg-green-600 text-white px-3 py-2 rounded-lg hover:bg-green-700 text-sm">
                        <i class="fas fa-plus mr-1"></i>Add Type
                    </button>
                    <button onclick="dashboard.showAddCategoryForm()" 
                            class="bg-blue-600 text-white px-3 py-2 rounded-lg hover:bg-blue-700 text-sm">
                        <i class="fas fa-plus mr-1"></i>Add Category
                    </button>
                </div>
            </div>

            <!-- Category Types Header with Mobile-Friendly Drag Info -->
            <div class="mb-4 p-4 bg-blue-50 rounded-lg border border-blue-200">
                <div class="flex items-start text-sm text-blue-700">
                    <i class="fas fa-info-circle mr-2 mt-0.5 flex-shrink-0"></i>
                    <div class="space-y-1">
                        <div class="font-medium">Drag and Drop Instructions:</div>
                        <div class="flex flex-col sm:flex-row sm:space-x-4 space-y-1 sm:space-y-0 text-xs">
                            <span class="flex items-center">
                                <i class="fas fa-desktop mr-1 hidden sm:inline"></i>
                                <i class="fas fa-mouse-pointer mr-1 sm:hidden"></i>
                                <strong class="sm:hidden">Desktop:</strong> Drag type headers & categories to reorder
                            </span>
                            <span class="flex items-center">
                                <i class="fas fa-mobile-alt mr-1"></i>
                                <strong class="sm:hidden">Mobile:</strong> 
                                <span class="hidden sm:inline">Touch & hold → drag with finger</span>
                                <span class="sm:hidden">Touch & hold, then drag with finger ↕️</span>
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Category Types Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="category-types-grid">
                ${this.categoryTypes.sort((a, b) => a.display_order - b.display_order).map(type => {
                    const categoriesOfType = this.categories
                        .filter(c => c.type === type.name)
                        .sort((a, b) => a.display_order - b.display_order);
                    
                    const icon = typeIcons[type.name] || 'fas fa-tag';
                    const color = typeColors[type.name] || 'gray-600';
                    
                    return `
                        <div class="category-type-card ${!type.is_visible ? 'bg-gray-100 border-red-200 opacity-75' : 'bg-white'} rounded-lg shadow-sm border p-6 ${this.isMobileDevice() ? '' : 'cursor-move'} ${!type.is_visible ? 'relative' : ''}" 
                             ${this.isMobileDevice() ? '' : 'draggable="true"'}
                             data-type-id="${type.id}"
                             data-type-name="${type.name}">
                            ${!type.is_visible ? `
                                <div class="absolute top-2 right-2 bg-red-500 text-white text-xs px-2 py-1 rounded-full">
                                    HIDDEN
                                </div>
                            ` : ''}
                            <h3 class="text-lg font-bold text-gray-900 mb-4 flex items-center justify-between">
                                <div class="flex items-center">
                                    ${this.isMobileDevice() ? `
                                        <div class="flex flex-col space-y-1 mr-3">
                                            <button onclick="dashboard.moveCategoryType(${type.id}, 'up')" 
                                                    class="bg-blue-100 text-blue-700 hover:bg-blue-200 p-2 rounded border border-blue-300 shadow-sm transition-colors">
                                                <i class="fas fa-chevron-up text-sm"></i>
                                            </button>
                                            <button onclick="dashboard.moveCategoryType(${type.id}, 'down')" 
                                                    class="bg-blue-100 text-blue-700 hover:bg-blue-200 p-2 rounded border border-blue-300 shadow-sm transition-colors">
                                                <i class="fas fa-chevron-down text-sm"></i>
                                            </button>
                                        </div>
                                    ` : `
                                        <i class="fas fa-grip-vertical text-gray-400 mr-2"></i>
                                    `}
                                    <i class="${icon} mr-2 text-${color}"></i>
                                    ${type.name}
                                    <span class="text-xs text-gray-400 ml-2">(Order: ${type.display_order})</span>
                                </div>
                                <div class="flex space-x-2">
                                    ${type.is_on_sale ? `
                                        <button onclick="dashboard.toggleCategoryTypeSale('${type.name}', false)" 
                                                class="text-red-600 hover:text-red-700 text-sm bg-red-100 px-2 py-1 rounded"
                                                title="Remove sale from all ${type.name} items">
                                            <i class="fas fa-fire mr-1"></i>
                                            ${type.sale_type === 'percentage' ? `${type.sale_value}%` : `${type.sale_value} ден`}
                                        </button>
                                    ` : `
                                        <button onclick="dashboard.toggleCategoryTypeSale('${type.name}', true)" 
                                                class="text-gray-500 hover:text-red-600 text-sm"
                                                title="Add sale to all ${type.name} items">
                                            <i class="fas fa-fire"></i>
                                        </button>
                                    `}
                                    <button onclick="dashboard.toggleCategoryTypeVisibility(${type.id}, ${!type.is_visible})" 
                                            class="${type.is_visible ? 'text-yellow-600 hover:text-yellow-800' : 'text-green-600 hover:text-green-800'} text-sm"
                                            title="${type.is_visible ? 'Hide from menu' : 'Show in menu'}">
                                        <i class="fas fa-${type.is_visible ? 'eye-slash' : 'eye'}"></i>
                                    </button>
                                    <button onclick="dashboard.editCategoryType(${type.id})" 
                                            class="text-blue-600 hover:text-blue-800 text-sm"
                                            title="Edit category type">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button onclick="dashboard.deleteCategoryType(${type.id})" 
                                            class="text-red-500 hover:text-red-700 text-sm"
                                            title="Delete category type">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </h3>
                            <div class="space-y-2" id="${type.name.toLowerCase()}-categories-list">
                                ${categoriesOfType.map(category => `
                                    <div class="category-item ${this.isMobileDevice() ? '' : 'cursor-move'} flex items-center justify-between p-3 ${!category.is_visible ? 'bg-red-50 border-red-200 opacity-75' : 'bg-gray-50'} rounded-lg border-2 ${!category.is_visible ? 'border-red-200' : 'border-transparent hover:border-gray-300'} transition-colors relative"
                                         ${this.isMobileDevice() ? '' : 'draggable="true"'}
                                         data-id="${category.id}"
                                         data-type="${type.name}">
                                        ${!category.is_visible ? `
                                            <div class="absolute top-1 right-1 bg-red-500 text-white text-xs px-1.5 py-0.5 rounded">
                                                HIDDEN
                                            </div>
                                        ` : ''}
                                        <div class="flex items-center">
                                            ${this.isMobileDevice() ? `
                                                <div class="flex flex-col space-y-1 mr-3">
                                                    <button onclick="dashboard.moveCategory(${category.id}, '${type.name}', 'up')" 
                                                            class="bg-blue-100 text-blue-700 hover:bg-blue-200 p-1.5 rounded border border-blue-300 shadow-sm transition-colors">
                                                        <i class="fas fa-chevron-up text-sm"></i>
                                                    </button>
                                                    <button onclick="dashboard.moveCategory(${category.id}, '${type.name}', 'down')" 
                                                            class="bg-blue-100 text-blue-700 hover:bg-blue-200 p-1.5 rounded border border-blue-300 shadow-sm transition-colors">
                                                        <i class="fas fa-chevron-down text-sm"></i>
                                                    </button>
                                                </div>
                                            ` : `
                                                <i class="fas fa-grip-vertical text-gray-400 mr-3"></i>
                                            `}
                                            <div>
                                                <div class="font-medium text-gray-900">${category.name}</div>
                                                ${category.description ? `<div class="text-sm text-gray-500">${category.description}</div>` : ''}
                                                ${category.parent_id ? `<div class="text-xs text-purple-600">Subcategory</div>` : ''}
                                                <div class="text-xs text-gray-400">Order: ${category.display_order}</div>
                                            </div>
                                        </div>
                                        <div class="flex space-x-2">
                                            ${category.is_on_sale ? `
                                                <button onclick="dashboard.toggleCategorySale(${category.id}, false)" 
                                                        class="text-red-600 hover:text-red-700 text-xs bg-red-100 px-2 py-1 rounded"
                                                        title="Remove sale from all items in ${category.name}">
                                                    <i class="fas fa-fire mr-1"></i>
                                                    ${category.sale_type === 'percentage' ? `${category.sale_value}%` : `${category.sale_value} ден`}
                                                </button>
                                            ` : `
                                                <button onclick="dashboard.toggleCategorySale(${category.id}, true)" 
                                                        class="text-gray-500 hover:text-red-600 text-sm"
                                                        title="Add sale to all items in ${category.name}">
                                                    <i class="fas fa-fire"></i>
                                                </button>
                                            `}
                                            <button onclick="dashboard.editCategory(${category.id})" 
                                                    class="text-blue-600 hover:text-blue-800">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button onclick="dashboard.toggleCategoryVisibility(${category.id}, ${!category.is_visible})" 
                                                    class="${category.is_visible ? 'text-yellow-600 hover:text-yellow-800' : 'text-green-600 hover:text-green-800'}"
                                                    title="${category.is_visible ? 'Hide from menu' : 'Show in menu'}">
                                                <i class="fas fa-${category.is_visible ? 'eye-slash' : 'eye'}"></i>
                                            </button>
                                            <button onclick="dashboard.deleteCategory(${category.id})" 
                                                    class="text-red-600 hover:text-red-800">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                `).join('') || '<p class="text-gray-500 text-sm">No categories yet.</p>'}
                            </div>
                        </div>
                    `;
                }).join('') || '<div class="col-span-full text-center py-8 text-gray-600">No category types available. <button onclick="dashboard.showAddCategoryTypeForm()" class="text-blue-600 hover:text-blue-800">Add a category type</button> to get started.</div>'}
            </div>
        `;
    }

    renderMenuItems() {
        const targetRestaurantId = this.currentRestaurantId;
        
        if (!targetRestaurantId) {
            return '<div class="text-center py-8 text-gray-600">No restaurant selected or available.</div>';
        }
        const availableCategories = this.categories.filter(c => c.restaurant_id === targetRestaurantId);
        

        let filteredMenuItems = this.menuItems;
        
        // Filter by selected type
        if (this.selectedMenuType) {
            const typeCategories = availableCategories.filter(c => c.type === this.selectedMenuType);
            const typeCategoryIds = typeCategories.map(c => c.id);
            filteredMenuItems = filteredMenuItems.filter(item => typeCategoryIds.includes(item.category_id));
        }

        // Filter by selected category
        if (this.selectedCategoryFilters.size > 0) {
            filteredMenuItems = filteredMenuItems.filter(item => this.selectedCategoryFilters.has(item.category_id));
        }
        

        if (this.menuItemSearchTerm.trim()) {
            const searchTerm = this.menuItemSearchTerm.toLowerCase();
            filteredMenuItems = filteredMenuItems.filter(item => 
                item.name.toLowerCase().includes(searchTerm) ||
                (item.description && item.description.toLowerCase().includes(searchTerm))
            );
        }
        

        if (this.menuItemSaleFilter === 'on_sale') {
            filteredMenuItems = filteredMenuItems.filter(item => item.is_on_sale);
        } else if (this.menuItemSaleFilter === 'not_on_sale') {
            filteredMenuItems = filteredMenuItems.filter(item => !item.is_on_sale);
        }
        

        if (this.menuItemVisibilityFilter === 'visible') {
            filteredMenuItems = filteredMenuItems.filter(item => item.is_visible);
        } else if (this.menuItemVisibilityFilter === 'hidden') {
            filteredMenuItems = filteredMenuItems.filter(item => !item.is_visible);
        }
        

        filteredMenuItems.sort((a, b) => {
            let aVal, bVal;
            switch (this.menuItemSortBy) {
                case 'name':
                    aVal = a.name.toLowerCase();
                    bVal = b.name.toLowerCase();
                    break;
                case 'price':
                    aVal = parseFloat(a.price);
                    bVal = parseFloat(b.price);
                    break;
                case 'category':
                    const aCat = this.categories.find(c => c.id === a.category_id);
                    const bCat = this.categories.find(c => c.id === b.category_id);
                    aVal = aCat ? aCat.name.toLowerCase() : '';
                    bVal = bCat ? bCat.name.toLowerCase() : '';
                    break;
                case 'sale_status':
                    aVal = a.is_on_sale ? 1 : 0;
                    bVal = b.is_on_sale ? 1 : 0;
                    break;
                case 'visibility':
                    aVal = a.is_visible ? 1 : 0;
                    bVal = b.is_visible ? 1 : 0;
                    break;
                case 'display_order':
                default:
                    aVal = a.display_order || 0;
                    bVal = b.display_order || 0;
                    break;
            }
            
            if (typeof aVal === 'string') {
                return this.menuItemSortOrder === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
            } else {
                return this.menuItemSortOrder === 'asc' ? aVal - bVal : bVal - aVal;
            }
        });

        return `
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-3">
                <h3 class="text-lg font-semibold text-gray-900">Menu Items Management</h3>
                <div class="flex gap-2">
                    <button onclick="dashboard.showBulkPriceUpdateModal()" 
                            class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 whitespace-nowrap">
                        <i class="fas fa-dollar-sign mr-2"></i>Bulk Price Update
                    </button>
                    <button onclick="dashboard.showAddMenuItemForm()" 
                            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 whitespace-nowrap">
                        <i class="fas fa-plus mr-2"></i>Add Menu Item
                    </button>
                </div>
            </div>

            <!-- Hierarchical Navigation: Type → Category → Items -->
            <div class="mb-6 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg p-4">
                <div class="flex flex-col gap-4">
                    <!-- Step 1: Select Type -->
                    <div class="flex flex-col">
                        <label class="text-sm font-semibold text-gray-700 mb-2 flex items-center">
                            <span class="bg-blue-600 text-white rounded-full w-6 h-6 flex items-center justify-center mr-2 text-xs">1</span>
                            Select Menu Type
                        </label>
                        <div class="flex flex-wrap gap-2">
                            <button onclick="dashboard.selectMenuType(null)" 
                                    class="px-4 py-2 rounded-lg font-medium transition-all ${!this.selectedMenuType ? 'bg-blue-600 text-white shadow-md' : 'bg-white text-gray-700 hover:bg-gray-50 border border-gray-300'}">
                                <i class="fas fa-list mr-1"></i>All Types (${this.menuItems.length})
                            </button>
                            ${this.categoryTypes.map(type => {
                                const typeCategories = availableCategories.filter(c => c.type === type.name);
                                const typeItems = this.menuItems.filter(item => 
                                    typeCategories.some(cat => cat.id === item.category_id)
                                );
                                const isSelected = this.selectedMenuType === type.name;
                                return `
                                    <button onclick="dashboard.selectMenuType('${type.name}')" 
                                            class="px-4 py-2 rounded-lg font-medium transition-all ${isSelected ? 'bg-blue-600 text-white shadow-md' : 'bg-white text-gray-700 hover:bg-gray-50 border border-gray-300'}">
                                        <i class="fas fa-folder mr-1"></i>${type.name} (${typeItems.length})
                                    </button>
                                `;
                            }).join('')}
                        </div>
                    </div>

                    <!-- Step 2: Select Category (shown when type is selected) -->
                    ${this.selectedMenuType ? `
                        <div class="flex flex-col border-t border-blue-200 pt-4">
                            <label class="text-sm font-semibold text-gray-700 mb-2 flex items-center">
                                <span class="bg-blue-600 text-white rounded-full w-6 h-6 flex items-center justify-center mr-2 text-xs">2</span>
                                Select Category in "${this.selectedMenuType}"
                            </label>
                            <div class="flex flex-wrap gap-2">
                                <button onclick="dashboard.handleCategoryFilterChange('')" 
                                        class="px-4 py-2 rounded-lg font-medium transition-all ${this.selectedCategoryFilters.size === 0 ? 'bg-indigo-600 text-white shadow-md' : 'bg-white text-gray-700 hover:bg-gray-50 border border-gray-300'}">
                                    <i class="fas fa-th-large mr-1"></i>All Categories
                                </button>
                                ${availableCategories
                                    .filter(c => c.type === this.selectedMenuType)
                                    .sort((a, b) => a.display_order - b.display_order)
                                    .map(category => {
                                        const categoryItems = this.menuItems.filter(item => item.category_id === category.id);
                                        const isSelected = this.selectedCategoryFilters.has(category.id);
                                        return `
                                            <button onclick="dashboard.handleCategoryFilterChange(${category.id})" 
                                                    class="px-4 py-2 rounded-lg font-medium transition-all ${isSelected ? 'bg-indigo-600 text-white shadow-md' : 'bg-white text-gray-700 hover:bg-gray-50 border border-gray-300'}">
                                                <i class="fas fa-tag mr-1"></i>${category.name} (${categoryItems.length})
                                            </button>
                                        `;
                                    }).join('')}
                            </div>
                        </div>
                    ` : ''}
                    
                    <!-- Step 3: Info about viewing items -->
                    <div class="flex items-center justify-between text-sm border-t border-blue-200 pt-3">
                        <div class="flex items-center text-gray-700">
                            <span class="bg-blue-600 text-white rounded-full w-6 h-6 flex items-center justify-center mr-2 text-xs">3</span>
                            <span class="font-medium">Menu Items List</span>
                            ${this.selectedMenuType || this.selectedCategoryFilters.size > 0 ? `
                                <span class="ml-2 text-blue-600 font-semibold">(${filteredMenuItems.length} filtered)</span>
                            ` : `
                                <span class="ml-2 text-gray-500">(${filteredMenuItems.length} total)</span>
                            `}
                        </div>
                        ${this.selectedMenuType || this.selectedCategoryFilters.size > 0 ? `
                            <button onclick="dashboard.clearAllMenuFilters()" 
                                    class="px-3 py-1.5 text-xs bg-red-100 text-red-700 border border-red-300 rounded-lg hover:bg-red-200 transition-colors">
                                <i class="fas fa-times mr-1"></i>Clear All Filters
                            </button>
                        ` : ''}
                    </div>
                </div>
            </div>

            <!-- Additional Filters and Search -->
            <div class="mb-6 bg-gray-50 border border-gray-200 rounded-lg">
                <!-- Collapsible Header -->
                <button onclick="dashboard.toggleFiltersPanel()" 
                        class="w-full p-4 text-left hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 rounded-lg">
                    <div class="flex items-center justify-between">
                        <span class="text-sm font-medium text-gray-700">
                            <i class="fas fa-filter mr-2"></i>
                            Filters & Search
                        </span>
                        <i id="filters-toggle-icon" class="fas fa-chevron-down text-gray-500 transition-transform"></i>
                    </div>
                </button>
                
                <!-- Collapsible Content -->
                <div id="filters-panel" class="hidden px-4 pb-4 border-t border-gray-200">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 pt-4">
                    <!-- Search Input -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Search Items</label>
                        <input type="text" id="menu-search" placeholder="Search by name or description..." 
                               value="${this.menuItemSearchTerm}"
                               oninput="dashboard.handleMenuItemSearch(this.value)"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <!-- Sale Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Sale Status</label>
                        <select id="sale-filter" onchange="dashboard.handleSaleFilter(this.value)"
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="all" ${this.menuItemSaleFilter === 'all' ? 'selected' : ''}>All Items</option>
                            <option value="on_sale" ${this.menuItemSaleFilter === 'on_sale' ? 'selected' : ''}>On Sale</option>
                            <option value="not_on_sale" ${this.menuItemSaleFilter === 'not_on_sale' ? 'selected' : ''}>Not On Sale</option>
                        </select>
                    </div>
                    
                    <!-- Visibility Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Visibility</label>
                        <select id="visibility-filter" onchange="dashboard.handleVisibilityFilter(this.value)"
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="all" ${this.menuItemVisibilityFilter === 'all' ? 'selected' : ''}>All Items</option>
                            <option value="visible" ${this.menuItemVisibilityFilter === 'visible' ? 'selected' : ''}>Visible</option>
                            <option value="hidden" ${this.menuItemVisibilityFilter === 'hidden' ? 'selected' : ''}>Hidden</option>
                        </select>
                    </div>
                    
                    <!-- Sort Options -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Sort By</label>
                        <div class="flex gap-2">
                            <select id="sort-by" onchange="dashboard.handleSortBy(this.value)"
                                    class="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="display_order" ${this.menuItemSortBy === 'display_order' ? 'selected' : ''}>Order</option>
                                <option value="name" ${this.menuItemSortBy === 'name' ? 'selected' : ''}>Name</option>
                                <option value="price" ${this.menuItemSortBy === 'price' ? 'selected' : ''}>Price</option>
                                <option value="category" ${this.menuItemSortBy === 'category' ? 'selected' : ''}>Category</option>
                                <option value="sale_status" ${this.menuItemSortBy === 'sale_status' ? 'selected' : ''}>Sale</option>
                                <option value="visibility" ${this.menuItemSortBy === 'visibility' ? 'selected' : ''}>Visibility</option>
                            </select>
                            <button onclick="dashboard.toggleSortOrder()" title="Toggle sort order"
                                    class="px-3 py-2 border border-gray-300 rounded-lg text-sm hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <i class="fas fa-sort-${this.menuItemSortOrder === 'asc' ? 'up' : 'down'}"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Clear all filters button -->
                    ${(this.menuItemSearchTerm || this.menuItemSaleFilter !== 'all' || this.menuItemVisibilityFilter !== 'all' || this.selectedCategoryFilters.size > 0) ? `
                        <div class="mt-4 flex justify-end">
                            <button onclick="dashboard.clearAllFilters()" 
                                    class="px-4 py-2 text-sm bg-gray-200 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-300 transition-colors">
                                <i class="fas fa-times mr-2"></i>Clear All Filters
                            </button>
                        </div>
                    ` : ''}
                </div>
            </div>

            <!-- Menu Items Reordering Instructions -->
            <div class="mb-4 p-4 bg-green-50 rounded-lg border border-green-200">
                <div class="flex items-start text-sm text-green-700">
                    <i class="fas fa-sort mr-2 mt-0.5 flex-shrink-0"></i>
                    <div class="space-y-1">
                        <div class="font-medium">Menu Items Reordering:</div>
                        <div class="flex flex-col sm:flex-row sm:space-x-4 space-y-1 sm:space-y-0 text-xs">
                            <span class="flex items-center">
                                <i class="fas fa-desktop mr-1 hidden sm:inline"></i>
                                <i class="fas fa-mouse-pointer mr-1 sm:hidden"></i>
                                <strong class="sm:hidden">Desktop:</strong> Drag rows to reorder within same category
                            </span>
                            <span class="flex items-center">
                                <i class="fas fa-mobile-alt mr-1"></i>
                                <strong class="sm:hidden">Mobile:</strong> 
                                <span class="hidden sm:inline">Use ↑↓ arrows to move items</span>
                                <span class="sm:hidden">Use up/down arrows (↑↓) to move items</span>
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border overflow-hidden overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th onclick="dashboard.sortByColumn('name')" 
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 transition-colors">
                                Item
                                ${this.menuItemSortBy === 'name' ? `<i class="fas fa-sort-${this.menuItemSortOrder === 'asc' ? 'up' : 'down'} ml-1"></i>` : '<i class="fas fa-sort ml-1 opacity-30"></i>'}
                            </th>
                            <th onclick="dashboard.sortByColumn('category')" 
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 transition-colors">
                                Category
                                ${this.menuItemSortBy === 'category' ? `<i class="fas fa-sort-${this.menuItemSortOrder === 'asc' ? 'up' : 'down'} ml-1"></i>` : '<i class="fas fa-sort ml-1 opacity-30"></i>'}
                            </th>
                            <th onclick="dashboard.sortByColumn('price')" 
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 transition-colors">
                                Price
                                ${this.menuItemSortBy === 'price' ? `<i class="fas fa-sort-${this.menuItemSortOrder === 'asc' ? 'up' : 'down'} ml-1"></i>` : '<i class="fas fa-sort ml-1 opacity-30"></i>'}
                            </th>
                            <th onclick="dashboard.sortByColumn('sale_status')" 
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 transition-colors">
                                Sale
                                ${this.menuItemSortBy === 'sale_status' ? `<i class="fas fa-sort-${this.menuItemSortOrder === 'asc' ? 'up' : 'down'} ml-1"></i>` : '<i class="fas fa-sort ml-1 opacity-30"></i>'}
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Size</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200" id="menuItemsTableBody">
                        ${filteredMenuItems.map(item => {
                            const category = this.categories.find(c => c.id === item.category_id);
                            
                            return `
                                <tr ${this.isMobileDevice() ? '' : 'draggable="true"'} data-item-id="${item.id}" class="menu-item-row ${this.isMobileDevice() ? '' : 'cursor-move'} ${!item.is_visible ? 'bg-red-50 opacity-75' : 'hover:bg-gray-50'}">
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            ${this.isMobileDevice() ? `
                                                <div class="flex flex-col space-y-1 mr-3">
                                                    <button onclick="dashboard.moveMenuItem(${item.id}, 'up')" 
                                                            class="bg-blue-100 text-blue-700 hover:bg-blue-200 p-1.5 rounded border border-blue-300 shadow-sm transition-colors">
                                                        <i class="fas fa-chevron-up text-sm"></i>
                                                    </button>
                                                    <button onclick="dashboard.moveMenuItem(${item.id}, 'down')" 
                                                            class="bg-blue-100 text-blue-700 hover:bg-blue-200 p-1.5 rounded border border-blue-300 shadow-sm transition-colors">
                                                        <i class="fas fa-chevron-down text-sm"></i>
                                                    </button>
                                                </div>
                                            ` : `
                                                <div class="text-gray-400 mr-3 drag-handle">
                                                    <i class="fas fa-grip-vertical"></i>
                                                </div>
                                            `}
                                            ${item.image_url ? `
                                                <img src="${item.image_url}" alt="${item.name}" 
                                                     class="w-10 h-10 rounded object-cover mr-3">
                                            ` : `
                                                <div class="w-10 h-10 rounded bg-gray-200 flex items-center justify-center mr-3">
                                                    <i class="fas fa-image text-gray-400"></i>
                                                </div>
                                            `}
                                            <div>
                                                <div class="text-sm font-medium text-gray-900 flex items-center">
                                                    ${item.name}
                                                    ${!item.is_visible ? `<span class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800"><i class="fas fa-eye-slash mr-1"></i>Hidden</span>` : ''}
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        ${category ? category.name : 'N/A'}
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                        ${item.is_on_sale && item.original_price ? `
                                            <div class="flex flex-col">
                                                <span class="text-xs text-gray-400 line-through">${parseFloat(item.original_price).toFixed(0)} ден</span>
                                                <span class="text-red-600 font-bold">${parseFloat(item.price).toFixed(0)} ден</span>
                                            </div>
                                        ` : `
                                            ${parseFloat(item.price).toFixed(0)} ден
                                        `}
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm">
                                        ${item.is_on_sale ? `
                                            <div class="flex items-center">
                                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                    <i class="fas fa-fire mr-1"></i>
                                                    ${item.sale_type === 'percentage' ? `${item.sale_value}%` : 
                                                      item.sale_type === 'fixed_discount' ? `${item.sale_value} ден` : 
                                                      'SALE'}
                                                </span>
                                                <button onclick="dashboard.toggleItemSale(${item.id}, false)" 
                                                        class="ml-2 text-gray-400 hover:text-red-600 text-xs">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </div>
                                        ` : `
                                            <button onclick="dashboard.toggleItemSale(${item.id}, true)" 
                                                    class="text-gray-400 hover:text-red-600 text-sm">
                                                <i class="fas fa-plus mr-1"></i>Add Sale
                                            </button>
                                        `}
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        ${item.size_info || '-'}
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                        <button onclick="dashboard.editMenuItem(${item.id})" 
                                                class="text-blue-600 hover:text-blue-900 mr-3"
                                                title="Edit item">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button onclick="dashboard.duplicateMenuItem(${item.id})" 
                                                class="text-purple-600 hover:text-purple-900 mr-3"
                                                title="Duplicate item">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                        <button onclick="dashboard.toggleHotItem(${item.id})" 
                                                class="${item.is_hot_item ? 'text-orange-600 hover:text-orange-800' : 'text-gray-400 hover:text-orange-600'} mr-3"
                                                title="${item.is_hot_item ? 'Remove from hot items' : 'Mark as hot item'}">
                                            <i class="fas fa-fire${item.is_hot_item ? '' : '-alt'}"></i>
                                        </button>
                                        <button onclick="dashboard.toggleItemVisibility(${item.id}, ${!item.is_visible})" 
                                                class="${item.is_visible ? 'text-yellow-600 hover:text-yellow-800' : 'text-green-600 hover:text-green-800'} mr-3"
                                                title="${item.is_visible ? 'Hide from menu' : 'Show in menu'}">
                                            <i class="fas fa-${item.is_visible ? 'eye-slash' : 'eye'}"></i>
                                        </button>
                                        <button onclick="dashboard.deleteMenuItem(${item.id})" 
                                                class="text-red-600 hover:text-red-900"
                                                title="Delete item">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            `;
                        }).join('')}
                    </tbody>
                </table>
            </div>
        `;
    }

    toggleMenuItemQuantity(checkbox) {
        const itemRow = checkbox.closest('[data-item-id]');
        if (!itemRow) return;
        
        const quantityInput = itemRow.querySelector('.item-quantity');
        if (!quantityInput) return;
        
        if (checkbox.checked) {
            quantityInput.disabled = false;
            quantityInput.focus();
        } else {
            quantityInput.disabled = true;
        }
        
        this.updatePromotionItemsTotal();
    }

    updatePromotionItemsTotal() {
        const checkboxes = document.querySelectorAll('input[name="menu_items"]:checked');
        const totalElement = document.getElementById('selectedItemsTotal');
        
        if (!totalElement) return;
        
        let total = 0;
        checkboxes.forEach(checkbox => {
            const itemId = parseInt(checkbox.value);
            const item = this.menuItems.find(item => item.id === itemId);
            if (item) {
                const quantityInput = document.querySelector(`input[name="quantity_${itemId}"]`);
                const quantity = quantityInput ? parseInt(quantityInput.value) || 1 : 1;
                total += parseFloat(item.price) * quantity;
            }
        });
        
        totalElement.textContent = `${total.toFixed(0)} ден`;
    }

    renderHotItemsContent() {
        const targetRestaurantId = this.currentRestaurantId;
        
        if (!targetRestaurantId) {
            return '<div class="text-center py-8 text-gray-600">No restaurant selected or available.</div>';
        }

        return `
            <div class="flex justify-between items-center mb-6">
                <div class="flex items-center gap-3">
                    <h3 class="text-lg font-semibold text-gray-900">Hot Items</h3>
                    <button onclick="dashboard.showEditHotItemsSettings()" 
                            class="text-blue-600 hover:text-blue-800 transition-colors"
                            title="Edit Hot Items Label and Description">
                        <i class="fas fa-edit"></i>
                    </button>
                </div>
                <button onclick="dashboard.showAddHotItemForm()" 
                        class="bg-orange-600 text-white px-4 py-2 rounded-lg hover:bg-orange-700">
                    <i class="fas fa-plus mr-2"></i>Add Hot Item
                </button>
            </div>

            ${this.hotItems.length === 0 ? `
                <div class="text-center py-8 text-gray-500">
                    <i class="fas fa-fire text-4xl mb-4"></i>
                    <p class="text-lg mb-2">No hot items found</p>
                    <p class="text-sm">Create standalone hot items to feature your best dishes.</p>
                </div>
            ` : `
                <div class="bg-white shadow overflow-hidden sm:rounded-md">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Price</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Description</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                ${this.hotItems.map(item => `
                                    <tr class="${!item.is_visible ? 'bg-red-50' : ''}">
                                        <td class="px-6 py-4">
                                            <div class="flex items-center">
                                                ${item.image_url ? `
                                                    <img src="${item.image_url}" alt="${item.name}" class="w-12 h-12 rounded object-cover mr-3">
                                                ` : ''}
                                                <div>
                                                    <div class="text-sm font-medium text-gray-900">${item.name || item.name_en || item.name_mk}</div>
                                                    ${item.size_info ? `<div class="text-xs text-gray-500">${item.size_info}</div>` : ''}
                                                </div>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-semibold">
                                            ${parseFloat(item.price).toFixed(0)} ден
                                        </td>
                                        <td class="px-6 py-4">
                                            <div class="text-sm text-gray-600 truncate max-w-xs">${item.description || item.description_en || item.description_mk || '-'}</div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                                                item.is_visible ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                                            }">
                                                ${item.is_visible ? 'Visible' : 'Hidden'}
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <button onclick="dashboard.editHotItem(${item.id})" 
                                                    class="text-blue-600 hover:text-blue-900 mr-3"
                                                    title="Edit item">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button onclick="dashboard.toggleHotItemVisibility(${item.id}, ${!item.is_visible})" 
                                                    class="${item.is_visible ? 'text-yellow-600 hover:text-yellow-800' : 'text-green-600 hover:text-green-800'} mr-3"
                                                    title="${item.is_visible ? 'Hide from menu' : 'Show in menu'}">
                                                <i class="fas fa-${item.is_visible ? 'eye-slash' : 'eye'}"></i>
                                            </button>
                                            <button onclick="dashboard.deleteHotItem(${item.id})" 
                                                    class="text-red-600 hover:text-red-900"
                                                    title="Delete item">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            `}
        `;
    }

    renderPromotionsContent() {
        const targetRestaurantId = this.currentRestaurantId;
        
        if (!targetRestaurantId) {
            return '<div class="text-center py-8 text-gray-600">No restaurant selected or available.</div>';
        }

        return `
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-lg font-semibold text-gray-900">Promotions</h3>
                <button onclick="dashboard.showAddPromotionForm()" 
                        class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-plus mr-2"></i>Add Promotion
                </button>
            </div>

            ${this.promotions.length === 0 ? `
                <div class="text-center py-8 text-gray-500">
                    <i class="fas fa-percentage text-4xl mb-4"></i>
                    <p class="text-lg mb-2">No promotions found</p>
                    <p class="text-sm">Create your first promotion to offer special deals to customers.</p>
                </div>
            ` : `
                <div class="bg-white shadow overflow-hidden sm:rounded-md">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Order</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Price</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Items</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200" id="promotionsTableBody">
                                ${this.promotions.map((promotion, index) => `
                                    <tr class="${!promotion.is_visible ? 'bg-red-50' : ''}" 
                                        data-promotion-id="${promotion.id}">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <div class="flex items-center space-x-2">
                                                ${!this.isMobileDevice() ? `
                                                    <button onclick="dashboard.movePromotion(${promotion.id}, 'up')" 
                                                            ${index === 0 ? 'disabled' : ''}
                                                            class="text-gray-400 hover:text-gray-600 disabled:opacity-30 disabled:cursor-not-allowed">
                                                        <i class="fas fa-arrow-up"></i>
                                                    </button>
                                                    <span class="text-sm font-medium">${promotion.display_order || (index + 1)}</span>
                                                    <button onclick="dashboard.movePromotion(${promotion.id}, 'down')" 
                                                            ${index === this.promotions.length - 1 ? 'disabled' : ''}
                                                            class="text-gray-400 hover:text-gray-600 disabled:opacity-30 disabled:cursor-not-allowed">
                                                        <i class="fas fa-arrow-down"></i>
                                                    </button>
                                                ` : `
                                                    <span class="text-sm font-medium">${promotion.display_order || (index + 1)}</span>
                                                `}
                                            </div>
                                        </td>
                                        <td class="px-6 py-4">
                                            <div class="text-sm font-medium text-gray-900">${promotion.name}</div>
                                            ${promotion.description ? `<div class="text-sm text-gray-500">${promotion.description}</div>` : ''}
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-semibold">
                                            ${parseFloat(promotion.price).toFixed(0)} ден
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-900">
                                            <div class="max-w-xs">
                                                ${promotion.menu_items && promotion.menu_items.length > 0 ? `
                                                    <div class="space-y-1">
                                                        ${promotion.menu_items.slice(0, 3).map(item => `
                                                            <div class="text-xs bg-gray-100 px-2 py-1 rounded">${item.quantity > 1 ? `${item.quantity}x ` : ''}${item.name}</div>
                                                        `).join('')}
                                                        ${promotion.menu_items.length > 3 ? `
                                                            <div class="text-xs text-gray-500">+${promotion.menu_items.length - 3} more items</div>
                                                        ` : ''}
                                                    </div>
                                                ` : `
                                                    <span class="text-gray-500 text-xs">No items selected</span>
                                                `}
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                                                promotion.is_visible ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                                            }">
                                                ${promotion.is_visible ? 'Active' : 'Deactivated'}
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <button onclick="dashboard.editPromotion(${promotion.id})" 
                                                    class="text-blue-600 hover:text-blue-900 mr-3">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button onclick="dashboard.togglePromotionVisibility(${promotion.id}, ${!promotion.is_visible})" 
                                                    class="${promotion.is_visible ? 'text-yellow-600 hover:text-yellow-800' : 'text-green-600 hover:text-green-800'} mr-3"
                                                    title="${promotion.is_visible ? 'Hide from menu' : 'Show in menu'}">
                                                <i class="fas fa-${promotion.is_visible ? 'eye-slash' : 'eye'}"></i>
                                            </button>
                                            <button onclick="dashboard.deletePromotion(${promotion.id})" 
                                                    class="text-red-600 hover:text-red-900">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            `}
        `;
    }

    renderCelebrationMenusContent() {
        const targetRestaurantId = this.currentRestaurantId;
        
        if (!targetRestaurantId) {
            return '<div class="text-center py-8 text-gray-600">No restaurant selected or available.</div>';
        }

        return `
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-lg font-semibold text-gray-900">Celebration Menus</h3>
                <button onclick="dashboard.showAddCelebrationMenuForm()" 
                        class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-plus mr-2"></i>Add Celebration Menu
                </button>
            </div>

            ${this.celebrationMenus.length === 0 ? `
                <div class="text-center py-8 text-gray-500">
                    <i class="fas fa-glass-cheers text-4xl mb-4"></i>
                    <p class="text-lg mb-2">No celebration menus found</p>
                    <p class="text-sm">Create your first celebration menu for special events and gatherings.</p>
                </div>
            ` : `
                <div class="bg-white shadow overflow-hidden sm:rounded-md">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Price Per Person</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Sections</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                ${this.celebrationMenus.map(menu => `
                                    <tr class="${!menu.is_visible ? 'bg-red-50' : ''}">
                                        <td class="px-6 py-4">
                                            <div class="text-sm font-medium text-gray-900">${menu.name || menu.name_en || menu.name_mk}</div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-semibold">
                                            ${parseFloat(menu.price_per_person).toFixed(0)} ден
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-900">
                                            <div class="text-xs text-gray-500">${menu.sections ? menu.sections.length : 0} sections</div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                                                menu.is_visible ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                                            }">
                                                ${menu.is_visible ? 'Active' : 'Deactivated'}
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <button onclick="dashboard.editCelebrationMenu(${menu.id})" 
                                                    class="text-blue-600 hover:text-blue-900 mr-3">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button onclick="dashboard.toggleCelebrationMenuVisibility(${menu.id}, ${!menu.is_visible})" 
                                                    class="${menu.is_visible ? 'text-yellow-600 hover:text-yellow-800' : 'text-green-600 hover:text-green-800'} mr-3"
                                                    title="${menu.is_visible ? 'Hide from menu' : 'Show in menu'}">
                                                <i class="fas fa-${menu.is_visible ? 'eye-slash' : 'eye'}"></i>
                                            </button>
                                            <button onclick="dashboard.deleteCelebrationMenu(${menu.id})" 
                                                    class="text-red-600 hover:text-red-900">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            `}
        `;
    }

    renderQRCodes() {
        let currentRestaurant = null;
        
        if (this.user.role === 'super_admin') {

            if (!this.currentRestaurantId && this.restaurants.length > 0) {
                this.currentRestaurantId = this.restaurants[0].id;
            }
            currentRestaurant = this.restaurants.find(r => r.id === this.currentRestaurantId);
        } else {

            currentRestaurant = this.restaurants.find(r => r.id === this.user.restaurant_id);
        }

        if (!currentRestaurant) {
            return `
                <div class="text-center py-8">
                    <div class="max-w-md mx-auto">
                        <i class="fas fa-exclamation-triangle text-yellow-500 text-4xl mb-4"></i>
                        <h3 class="text-lg font-medium text-gray-900 mb-2">No Restaurant Available</h3>
                        <p class="text-gray-500">
                            ${this.user.role === 'super_admin' 
                                ? 'No restaurants found. Please create a restaurant first.' 
                                : 'No restaurant assigned to your account. Please contact administrator.'}
                        </p>
                    </div>
                </div>
            `;
        }

        return `
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h2 class="text-2xl font-bold text-gray-900">QR Code Management</h2>
                    <p class="text-gray-600 mt-1">Manage QR codes for ${currentRestaurant.name}</p>
                </div>
                ${this.user.role === 'super_admin' ? this.renderRestaurantSelector('qr-code') : ''}
            </div>

            <div class="bg-white rounded-lg shadow-sm border overflow-hidden">
                <div class="p-6">
                    <!-- QR Code Preview Section -->
                    <div class="flex flex-col lg:flex-row gap-6">
                        <!-- QR Code Display -->
                        <div class="w-full lg:w-1/2">
                            <h3 class="text-lg font-semibold text-gray-900 mb-4">Current QR Code</h3>
                            <div class="bg-gray-50 rounded-lg p-4 sm:p-6 text-center">
                                <div id="qr-preview" class="mb-4">
                                    <div class="inline-block p-3 sm:p-4 bg-white rounded-lg shadow-sm">
                                        <div class="w-48 h-48 sm:w-64 sm:h-64 bg-gray-200 rounded flex items-center justify-center mx-auto" id="qr-image-container">
                                            <i class="fas fa-qrcode text-4xl sm:text-6xl text-gray-400"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="space-y-2">
                                    <p class="text-sm text-gray-600">Menu URL:</p>
                                    <p class="text-xs sm:text-sm font-mono bg-gray-100 p-2 rounded break-all">${window.location.origin}/menu/${currentRestaurant.slug}</p>
                                </div>
                            </div>
                        </div>

                        <!-- Controls -->
                        <div class="w-full lg:w-1/2">
                            <h3 class="text-lg font-semibold text-gray-900 mb-4">QR Code Options</h3>
                            
                            <!-- Design Tabs -->
                            <div class="mb-6">
                                <div class="flex border-b border-gray-200 -mb-px">
                                    <button onclick="dashboard.switchQRTab('basic')" id="tab-basic" class="px-4 py-2 text-sm font-medium border-b-2 border-blue-600 text-blue-600">
                                        Basic
                                    </button>
                                    <button onclick="dashboard.switchQRTab('colors')" id="tab-colors" class="px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700">
                                        Colors
                                    </button>
                                    <button onclick="dashboard.switchQRTab('shapes')" id="tab-shapes" class="px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700">
                                        Shapes
                                    </button>
                                    <button onclick="dashboard.switchQRTab('logo')" id="tab-logo" class="px-4 py-2 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700">
                                        Logo
                                    </button>
                                </div>
                            </div>

                            <!-- Basic Tab -->
                            <div id="qr-tab-basic" class="mb-6">
                                <div class="space-y-4">
                                    <!-- Size Options -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Size</label>
                                        <select id="qr-size" class="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                                            <option value="256">Small (256x256)</option>
                                            <option value="512" selected>Medium (512x512)</option>
                                            <option value="1024">Large (1024x1024)</option>
                                            <option value="2048">Extra Large (2048x2048)</option>
                                        </select>
                                    </div>
                                    
                                    <!-- Error Correction Level -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Error Correction Level</label>
                                        <select id="qr-error-correction" class="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                                            <option value="L">Low (7%)</option>
                                            <option value="M" selected>Medium (15%)</option>
                                            <option value="Q">Quartile (25%)</option>
                                            <option value="H">High (30%)</option>
                                        </select>
                                        <p class="text-xs text-gray-500 mt-1">Higher levels allow more damage but create denser codes</p>
                                    </div>
                                    
                                    <!-- Margin -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Margin</label>
                                        <input type="range" id="qr-margin" min="0" max="10" value="1" class="w-full">
                                        <div class="flex justify-between text-xs text-gray-500 mt-1">
                                            <span>0 (No margin)</span>
                                            <span>10 (Large margin)</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Colors Tab -->
                            <div id="qr-tab-colors" class="mb-6 hidden">
                                <div class="space-y-4">
                                    <!-- Color Mode -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Color Mode</label>
                                        <select id="qr-color-mode" class="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                                            <option value="solid" selected>Solid Colors</option>
                                        </select>
                                    </div>
                                    
                                    <!-- Solid Colors -->
                                    <div id="qr-solid-colors">
                                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700 mb-2">Foreground Color</label>
                                                <div class="flex items-center space-x-2">
                                                    <input type="color" id="qr-color-dark" value="#000000" class="w-10 h-8 sm:w-12 sm:h-10 border border-gray-300 rounded">
                                                    <input type="text" id="qr-color-dark-text" value="#000000" class="flex-1 p-2 border border-gray-300 rounded-md text-sm">
                                                </div>
                                            </div>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700 mb-2">Background Color</label>
                                                <div class="flex items-center space-x-2">
                                                    <input type="color" id="qr-color-light" value="#FFFFFF" class="w-10 h-8 sm:w-12 sm:h-10 border border-gray-300 rounded">
                                                    <input type="text" id="qr-color-light-text" value="#FFFFFF" class="flex-1 p-2 border border-gray-300 rounded-md text-sm">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    
                                    <!-- Color Presets -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Color Presets</label>
                                        <div class="grid grid-cols-4 gap-2">
                                            <button onclick="dashboard.applyColorPreset('#000000', '#FFFFFF')" class="w-full h-8 rounded border-2 border-gray-300" style="background: linear-gradient(45deg, #000000 50%, #FFFFFF 50%);" title="Classic Black & White"></button>
                                            <button onclick="dashboard.applyColorPreset('#1f2937', '#f3f4f6')" class="w-full h-8 rounded border-2 border-gray-300" style="background: linear-gradient(45deg, #1f2937 50%, #f3f4f6 50%);" title="Dark Gray & Light Gray"></button>
                                            <button onclick="dashboard.applyColorPreset('#3b82f6', '#eff6ff')" class="w-full h-8 rounded border-2 border-gray-300" style="background: linear-gradient(45deg, #3b82f6 50%, #eff6ff 50%);" title="Blue Theme"></button>
                                            <button onclick="dashboard.applyColorPreset('#10b981', '#f0fdf4')" class="w-full h-8 rounded border-2 border-gray-300" style="background: linear-gradient(45deg, #10b981 50%, #f0fdf4 50%);" title="Green Theme"></button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Shapes Tab -->
                            <div id="qr-tab-shapes" class="mb-6 hidden">
                                <div class="space-y-4">
                                    <!-- Dot Style -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Dot Style</label>
                                        <div class="grid grid-cols-3 gap-2">
                                            <button onclick="dashboard.setDotStyle('square')" id="dot-square" class="p-3 border-2 border-blue-600 rounded-md text-center bg-blue-50">
                                                <div class="w-4 h-4 bg-black mx-auto mb-1"></div>
                                                <span class="text-xs">Square</span>
                                            </button>
                                            <button onclick="dashboard.setDotStyle('round')" id="dot-round" class="p-3 border-2 border-gray-300 rounded-md text-center hover:border-blue-600">
                                                <div class="w-4 h-4 bg-black rounded-full mx-auto mb-1"></div>
                                                <span class="text-xs">Round</span>
                                            </button>
                                            <button onclick="dashboard.setDotStyle('rounded')" id="dot-rounded" class="p-3 border-2 border-gray-300 rounded-md text-center hover:border-blue-600">
                                                <div class="w-4 h-4 bg-black rounded-sm mx-auto mb-1"></div>
                                                <span class="text-xs">Rounded</span>
                                            </button>
                                        </div>
                                    </div>
                                    
                                    <!-- Corner Style -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Corner Style (Finder Patterns)</label>
                                        <div class="grid grid-cols-3 gap-2">
                                            <button onclick="dashboard.setCornerStyle('square')" id="corner-square" class="p-3 border-2 border-blue-600 rounded-md text-center bg-blue-50">
                                                <div class="w-4 h-4 border-2 border-black mx-auto mb-1"></div>
                                                <span class="text-xs">Square</span>
                                            </button>
                                            <button onclick="dashboard.setCornerStyle('round')" id="corner-round" class="p-3 border-2 border-gray-300 rounded-md text-center hover:border-blue-600">
                                                <div class="w-4 h-4 border-2 border-black rounded-full mx-auto mb-1"></div>
                                                <span class="text-xs">Round</span>
                                            </button>
                                            <button onclick="dashboard.setCornerStyle('rounded')" id="corner-rounded" class="p-3 border-2 border-gray-300 rounded-md text-center hover:border-blue-600">
                                                <div class="w-4 h-4 border-2 border-black rounded-sm mx-auto mb-1"></div>
                                                <span class="text-xs">Rounded</span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Logo Tab -->
                            <div id="qr-tab-logo" class="mb-6 hidden">
                                <div class="space-y-4">
                                    <!-- Logo Options -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">
                                            <input type="checkbox" id="qr-include-logo" ${currentRestaurant.logo_url ? 'checked' : ''} class="mr-2">
                                            Include Restaurant Logo
                                        </label>
                                        ${currentRestaurant.logo_url ? 
                                            `<p class="text-xs text-gray-500 mt-1">Using current restaurant logo</p>` :
                                            `<p class="text-xs text-orange-600 mt-1">No logo available. Upload a restaurant logo first.</p>`
                                        }
                                    </div>
                                    
                                    ${currentRestaurant.logo_url ? `
                                    <!-- Logo Size -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Logo Size</label>
                                        <input type="range" id="qr-logo-size" min="10" max="30" value="20" class="w-full">
                                        <div class="flex justify-between text-xs text-gray-500 mt-1">
                                            <span>10% (Small)</span>
                                            <span>30% (Large)</span>
                                        </div>
                                        <p class="text-xs text-gray-500 mt-1">Percentage of QR code size</p>
                                    </div>
                                    
                                    <!-- Logo Background -->
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-2">
                                            <input type="checkbox" id="qr-logo-background" checked class="mr-2">
                                            Logo Background
                                        </label>
                                        <div class="grid grid-cols-2 gap-4 mt-2" id="qr-logo-bg-options">
                                            <div>
                                                <label class="block text-xs text-gray-600 mb-1">Background Color</label>
                                                <input type="color" id="qr-logo-bg-color" value="#ffffff" class="w-full h-8 border border-gray-300 rounded">
                                            </div>
                                            <div>
                                                <label class="block text-xs text-gray-600 mb-1">Border Radius</label>
                                                <select id="qr-logo-border-radius" class="w-full p-2 border border-gray-300 rounded text-sm">
                                                    <option value="0">None</option>
                                                    <option value="4">Small</option>
                                                    <option value="8" selected>Medium</option>
                                                    <option value="50">Round</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    ` : ''}
                                </div>
                            </div>

                            <!-- Action Buttons -->
                            <div class="space-y-3">
                                <button onclick="dashboard.previewQRCode()" class="w-full bg-blue-600 text-white px-4 py-3 rounded-md hover:bg-blue-700 transition-colors text-sm sm:text-base">
                                    <i class="fas fa-eye mr-2"></i>Preview Changes
                                </button>
                                <button onclick="dashboard.regenerateQRCode()" class="w-full bg-green-600 text-white px-4 py-3 rounded-md hover:bg-green-700 transition-colors text-sm sm:text-base">
                                    <i class="fas fa-sync-alt mr-2"></i>Regenerate QR Code
                                </button>
                                
                                <!-- Download Options -->
                                <div class="border-t pt-3">
                                    <h4 class="text-sm font-medium text-gray-700 mb-2">Download PNG Options</h4>
                                    ${document.getElementById('qr-include-logo')?.checked && currentRestaurant.logo_url ? 
                                        `<div class="mb-2 p-2 bg-blue-50 border border-blue-200 rounded text-xs text-blue-700">
                                            <i class="fas fa-info-circle mr-1"></i>
                                            Logo will be included in downloaded PNG files
                                        </div>` : 
                                        ''
                                    }
                                    <div class="grid grid-cols-1 gap-2">
                                        <button onclick="dashboard.downloadQRCode('png', 512)" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors text-sm">
                                            <i class="fas fa-download mr-2"></i>PNG 512x512 (Web Quality)
                                        </button>
                                        <button onclick="dashboard.downloadQRCode('png', 1024)" class="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700 transition-colors text-sm">
                                            <i class="fas fa-download mr-2"></i>PNG 1024x1024 (Print Quality)
                                        </button>
                                        <button onclick="dashboard.downloadQRCode('png', 2048)" class="bg-purple-600 text-white px-4 py-2 rounded-md hover:bg-purple-700 transition-colors text-sm">
                                            <i class="fas fa-download mr-2"></i>PNG 2048x2048 (High Quality)
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Print Tips -->
                            <div class="mt-6 p-4 bg-blue-50 rounded-md">
                                <h4 class="text-sm font-semibold text-blue-900 mb-2">Print Tips</h4>
                                <ul class="text-xs text-blue-800 space-y-1">
                                    <li>• Use high resolution (1024px+) for best print quality</li>
                                    <li>• Print on white paper for best contrast</li>
                                    <li>• Test scanning before mass printing</li>
                                    <li>• Keep QR codes at least 2cm x 2cm for reliable scanning</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    renderCSVUpload() {
        return `
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-bold text-gray-900">Import/Export Management</h2>
            </div>

            <!-- CSV Export Section -->
            <div class="bg-white rounded-lg shadow-sm border p-6 mb-8">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">
                    <i class="fas fa-file-export mr-2 text-green-600"></i>Export Restaurant Data
                </h3>
                <p class="text-gray-600 mb-6">Export all restaurant data (categories, menu items) to XLSX format.</p>
                
                ${this.user.role === 'super_admin' ? `
                    <div class="mb-6">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Select Restaurant to Export</label>
                        <select id="export-restaurant-select" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-green-500">
                            <option value="">Select Restaurant</option>
                            ${this.restaurants.map(r => `<option value="${r.id}">${r.name}</option>`).join('')}
                        </select>
                    </div>
                ` : `
                    <div class="mb-6">
                        <p class="text-sm text-gray-600">Exporting data for: <strong>${this.restaurants.find(r => r.id === this.user.restaurant_id)?.name || 'Your Restaurant'}</strong></p>
                    </div>
                `}
                
                <button onclick="dashboard.exportCSV()" 
                        class="bg-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700 transition-colors">
                    <i class="fas fa-download mr-2"></i>Export to XLSX
                </button>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <!-- Template Download Section -->
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">
                        <i class="fas fa-download mr-2 text-green-600"></i>Download Excel Template
                    </h3>
                    <p class="text-gray-600 mb-6">Download the Excel template with 3 separate sheets for Types, Categories, and Menu Items.</p>
                    
                    <div class="p-4 border-2 border-dashed border-green-300 rounded-lg hover:bg-green-50 mb-4 text-center">
                        <i class="fas fa-file-excel text-4xl text-green-600 mb-2"></i>
                        <h4 class="font-medium text-gray-900 mb-2">Restaurant Data Excel Template</h4>
                        <p class="text-sm text-gray-600 mb-4">3-sheet Excel template: Types, Categories, and Menu Items sheets</p>
                        <button onclick="dashboard.downloadExcelTemplate()" 
                                class="bg-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700 font-medium">
                            <i class="fas fa-download mr-2"></i>Download Excel Template
                        </button>
                    </div>
                    
                    <div class="p-4 bg-green-50 rounded-lg">
                        <h5 class="text-sm font-medium text-green-900 mb-2">Template Features:</h5>
                        <ul class="text-sm text-green-800 space-y-1">
                            <li>• <strong>Types Sheet:</strong> Enter category types</li>
                            <li>• <strong>Categories Sheet:</strong> Enter categories with their type assignment</li>
                            <li>• <strong>Menu Items Sheet:</strong> Enter items with category, name, description, price, size, allergens</li>
                            <li>• Auto-defaults: is_active=true, is_visible=true, is_on_sale=false</li>
                            <li>• Restaurant ID restriction: users can only add to their own restaurant</li>
                            <li>• Display order automatically assigned sequentially</li>
                        </ul>
                    </div>
                </div>

                <!-- Excel Upload Section -->
                <div class="bg-white rounded-lg shadow-sm border p-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">
                        <i class="fas fa-upload mr-2 text-blue-600"></i>Bulk Import Excel Data
                    </h3>
                    <p class="text-gray-600 mb-6">Upload an Excel file with 3 sheets containing your restaurant data - Types, Categories, and Menu Items.</p>
                    
                    ${this.user.role === 'super_admin' ? `
                        <div class="mb-6">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Select Restaurant</label>
                            <select id="csvUploadRestaurant" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="">Select Restaurant</option>
                                ${this.restaurants.map(r => `<option value="${r.id}">${r.name}</option>`).join('')}
                            </select>
                        </div>
                    ` : ''}
                    
                    <form id="excelUploadForm">
                        <!-- Excel File Upload -->
                        <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 mb-4 text-center">
                            <div class="mb-4">
                                <i class="fas fa-file-excel text-4xl text-blue-500 mb-2"></i>
                                <p class="text-lg font-medium text-gray-700">Upload Restaurant Data Excel</p>
                                <p class="text-sm text-gray-500">Excel file with 3 sheets: Types, Categories, and Menu Items</p>
                            </div>
                            <input type="file" name="excelFile" id="excelFileInput" accept=".xlsx" required
                                   class="w-full text-sm text-gray-500 file:mr-4 file:py-3 file:px-6 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                        </div>
                        
                        <div class="mb-6">
                            <button type="submit" 
                                    class="w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 font-medium flex items-center justify-center">
                                <i class="fas fa-cloud-upload-alt mr-2"></i>Import Excel Data
                            </button>
                        </div>
                    </form>
                    
                    <!-- Upload Instructions -->
                    <div class="p-4 bg-blue-50 rounded-lg">
                        <h4 class="text-sm font-medium text-blue-900 mb-3">Import Instructions:</h4>
                        <ul class="text-sm text-blue-800 space-y-1 mb-4">
                            <li>• Download the Excel template first to see the correct format</li>
                            <li>• Use separate sheets: Types, Categories, Menu Items</li>
                            <li>• <strong>Types Sheet:</strong> List category types (e.g., "Appetizers", "Main Courses")</li>
                            <li>• <strong>Categories Sheet:</strong> List categories with assigned Type</li>
                            <li>• <strong>Menu Items Sheet:</strong> List items with Category, name, description, price, size, allergens</li>
                            <li>• All items auto-set: is_active=true, is_visible=true, is_on_sale=false</li>
                            <li>• Restaurant restriction: only your own restaurant data</li>
                            <li>• Display order assigned automatically (1st item = 1, 2nd item = 2, etc.)</li>
                        </ul>
                        
                        <div class="border-t pt-3">
                            <p class="text-sm font-medium text-blue-900 mb-2">Sheet Structure:</p>
                            <p class="text-xs text-blue-700 mb-1"><strong>Types:</strong> Type Name</p>
                            <p class="text-xs text-blue-700 mb-1"><strong>Categories:</strong> Category Name, Type</p>
                            <p class="text-xs text-blue-700"><strong>Menu Items:</strong> Category, Name, Description, Price, Size Info, Allergens</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    showAddRestaurantForm() {
        const content = `
            <form id="restaurantForm" enctype="multipart/form-data">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Restaurant Name</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            <div class="lang-field lang-field-mk">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Name (Macedonian)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_mk"
                                       placeholder="Внесете име на ресторан"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div class="lang-field lang-field-en">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Name (English)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_en"
                                       placeholder="Enter restaurant name"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div class="lang-field lang-field-al">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Name (Albanian)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_al"
                                       placeholder="Vendosni emrin e restorantit"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <input type="hidden" name="name" id="hiddenName">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Slug (URL identifier)</label>
                        <input type="text" name="slug" required 
                               placeholder="e.g., my-restaurant (letters, numbers, hyphens only)"
                               pattern="[a-z0-9-]+" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Email (Optional)</label>
                        <input type="email" name="email" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Phone</label>
                        <input type="tel" name="phone" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Website (Optional)</label>
                        <input type="url" name="website" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Facebook (Optional)</label>
                        <input type="url" name="facebook" 
                               placeholder="e.g., https://facebook.com/restaurant"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Instagram (Optional)</label>
                        <input type="url" name="instagram" 
                               placeholder="e.g., https://instagram.com/restaurant"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Restaurant Description</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            <div class="lang-field lang-field-mk">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Description (Macedonian)</span>
                                    </span>
                                </label>
                                <textarea name="description_mk" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                            </div>
                            <div class="lang-field lang-field-en">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Description (English)</span>
                                    </span>
                                </label>
                                <textarea name="description_en" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                            </div>
                            <div class="lang-field lang-field-al">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Description (Albanian)</span>
                                    </span>
                                </label>
                                <textarea name="description_al" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                            </div>
                        </div>
                        <input type="hidden" name="description" id="hiddenDescription">
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Address</label>
                        <textarea name="address" rows="2" 
                                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Subscription Start</label>
                        <input type="date" name="subscription_start" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Subscription End</label>
                        <input type="date" name="subscription_end" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">WiFi Network Name</label>
                        <input type="text" name="wifi_name" 
                               placeholder="e.g., Restaurant_WiFi"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <p class="text-sm text-gray-500 mt-1">WiFi network name that customers can see</p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">WiFi Password</label>
                        <input type="text" name="wifi_password" 
                               placeholder="e.g., welcome123"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <p class="text-sm text-gray-500 mt-1">WiFi password for customers</p>
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-3">Supported Languages</label>
                        <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                            <label class="flex items-center space-x-2 p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                <input type="checkbox" name="supported_languages" value="mk" checked 
                                       class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 language-checkbox">
                                <span class="text-2xl">🇲🇰</span>
                                <span class="text-sm font-medium text-gray-700">Macedonian</span>
                            </label>
                            <label class="flex items-center space-x-2 p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                <input type="checkbox" name="supported_languages" value="en" checked 
                                       class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 language-checkbox">
                                <span class="text-2xl">🇬🇧</span>
                                <span class="text-sm font-medium text-gray-700">English</span>
                            </label>
                            <label class="flex items-center space-x-2 p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                <input type="checkbox" name="supported_languages" value="al" checked 
                                       class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 language-checkbox">
                                <span class="text-2xl">🇦🇱</span>
                                <span class="text-sm font-medium text-gray-700">Albanian</span>
                            </label>
                        </div>
                        <p class="text-sm text-gray-500 mt-2">Select which languages this restaurant will use. Only selected language fields will appear in forms.</p>
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="flex items-center space-x-3">
                            <input type="checkbox" name="has_infinite_subscription" 
                                   class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                            <div>
                                <span class="text-sm font-medium text-gray-700">Infinite Subscription</span>
                                <p class="text-sm text-gray-500">Check this to prevent automatic deactivation of this restaurant</p>
                            </div>
                        </label>
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Color Theme</label>
                        <select name="selected_theme" id="themeSelector"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Loading themes...</option>
                        </select>
                        <p class="text-sm text-gray-500 mt-1">Choose a color scheme for the restaurant's live menu</p>
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Logo Image (Optional)</label>
                        <input type="file" name="logo" accept="image/*" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <p class="text-sm text-gray-500 mt-1">Upload a logo image (max 5MB)</p>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        Create Restaurant
                    </button>
                </div>
            </form>
        `;
        
        this.showModal('Add New Restaurant', content);
        
        // Load themes
        this.loadThemesForForm();
        
        // Set up language field visibility toggle
        this.setupLanguageFieldToggle();
        
        // Set up form handling to populate hidden fields
        const form = document.getElementById('restaurantForm');
        form.addEventListener('submit', (e) => {
            const nameMk = form.name_mk.value;
            const nameEn = form.name_en.value;
            const nameAl = form.name_al.value;
            const descMk = form.description_mk.value;
            const descEn = form.description_en.value;
            const descAl = form.description_al.value;
            form.querySelector('#hiddenName').value = nameMk || nameEn || nameAl || '';
            form.querySelector('#hiddenDescription').value = descMk || descEn || descAl || '';
        });
        
        document.getElementById('restaurantForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitButton = e.target.querySelector('button[type="submit"]');
            if (!this.preventDoubleSubmission('restaurantForm', submitButton)) {
                return; // Prevent duplicate submission
            }
            
            try {
                await this.handleRestaurantForm(e.target);
            } finally {
                this.restoreSubmissionState('restaurantForm', submitButton);
            }
        });
    }

    async handleRestaurantForm(form, isEdit = false, restaurantId = null) {
        try {
            const formData = new FormData(form);
            let logoUrl = formData.get('current_logo_url') || '';
            const logoFile = formData.get('logo');
            const deleteLogo = formData.get('delete_logo') === 'true';
            
            // If user wants to delete current logo, set it to null
            if (deleteLogo) {
                logoUrl = null;
            } else if (logoFile && logoFile.size > 0) {
                const uploadFormData = new FormData();
                uploadFormData.append('image', logoFile);
                uploadFormData.append('is_logo', 'true'); // Indicate this is a logo for proper naming
                

                const restaurantSlug = formData.get('slug');
                if (!restaurantSlug) {
                    throw new Error('Restaurant slug is required for logo upload');
                }
                
                const uploadResponse = await axios.post(`/api/upload/restaurants/${restaurantSlug}`, uploadFormData, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                });
                
                if (uploadResponse.data.success) {
                    logoUrl = uploadResponse.data.data.url;
                }
            }

            const selectedTheme = formData.get('selected_theme');
            
            // Get all selected languages
            const supportedLanguages = [];
            formData.getAll('supported_languages').forEach(lang => {
                supportedLanguages.push(lang);
            });
            
            const restaurantData = {
                name: formData.get('name'),
                name_mk: formData.get('name_mk'),
                name_en: formData.get('name_en'),
                name_al: formData.get('name_al'),
                slug: formData.get('slug'),
                description: formData.get('description'),
                description_mk: formData.get('description_mk'),
                description_en: formData.get('description_en'),
                description_al: formData.get('description_al'),
                supported_languages: supportedLanguages.length > 0 ? supportedLanguages : ['mk', 'en', 'al'],
                address: formData.get('address'),
                phone: formData.get('phone'),
                email: formData.get('email') || null,
                website: formData.get('website') || null,
                facebook: formData.get('facebook') || null,
                instagram: formData.get('instagram') || null,
                subscription_start: formData.get('subscription_start'),
                subscription_end: formData.get('subscription_end'),
                logo_url: logoUrl,
                wifi_name: formData.get('wifi_name') || null,
                wifi_password: formData.get('wifi_password') || null,
                has_infinite_subscription: formData.get('has_infinite_subscription') === 'on',
                selected_theme: selectedTheme && selectedTheme !== '' ? parseInt(selectedTheme) : null
            };

            let response;
            if (isEdit) {
                response = await axios.put(`/api/admin/restaurants/${restaurantId}`, restaurantData);
            } else {
                response = await axios.post('/api/admin/restaurants', restaurantData);
            }

            if (response.data.success) {
                this.closeModal();
                await this.loadData();
                this.render();
                

                this.showModal('Success', `
                    <div class="text-center">
                        <i class="fas fa-check-circle text-green-500 text-4xl mb-4"></i>
                        <p class="text-lg">Restaurant ${isEdit ? 'updated' : 'created'} successfully!</p>
                        <button onclick="dashboard.closeModal()" 
                                class="mt-4 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                            OK
                        </button>
                    </div>
                `);
            }
        } catch (error) {
            console.error('Error saving restaurant:', error);
            alert('Error saving restaurant. Please try again.');
        }
    }

    showAddUserForm() {
        const content = `
            <form id="userForm">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Name</label>
                        <input type="text" name="name" required 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Email</label>
                        <input type="email" name="email" required 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Password</label>
                        <input type="password" name="password" required 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Role</label>
                        <select name="role" id="userRole" onchange="dashboard.toggleRestaurantSelect()" required 
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Select Role</option>
                            <option value="super_admin">Super Admin</option>
                            <option value="restaurant_admin">Restaurant Admin</option>
                        </select>
                    </div>
                    
                    <div id="restaurantSelectDiv" class="md:col-span-2" style="display: none;">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Assign to Restaurant</label>
                        <select name="restaurant_id" id="userRestaurant" 
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Select Restaurant</option>
                            ${this.restaurants.map(restaurant => `
                                <option value="${restaurant.id}">${restaurant.name}</option>
                            `).join('')}
                        </select>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        Create User
                    </button>
                </div>
            </form>
        `;
        
        this.showModal('Add New User', content);
        
        document.getElementById('userForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitButton = e.target.querySelector('button[type="submit"]');
            if (!this.preventDoubleSubmission('userForm', submitButton)) {
                return; // Prevent duplicate submission
            }
            
            try {
                await this.handleUserForm(e.target);
            } finally {
                this.restoreSubmissionState('userForm', submitButton);
            }
        });
    }

    toggleRestaurantSelect() {
        const roleSelect = document.getElementById('userRole');
        const restaurantDiv = document.getElementById('restaurantSelectDiv');
        const restaurantSelect = document.getElementById('userRestaurant');
        
        if (roleSelect.value === 'restaurant_admin') {
            restaurantDiv.style.display = 'block';
            restaurantSelect.required = true;
        } else {
            restaurantDiv.style.display = 'none';
            restaurantSelect.required = false;
            restaurantSelect.value = '';
        }
    }

    async handleUserForm(form) {
        try {
            const formData = new FormData(form);
            const userData = {
                name: formData.get('name'),
                email: formData.get('email'),
                password: formData.get('password'),
                role: formData.get('role'),
                restaurant_id: formData.get('restaurant_id') ? parseInt(formData.get('restaurant_id')) : null
            };

            const response = await axios.post('/api/admin/users', userData);

            if (response.data.success) {
                this.closeModal();
                await this.loadData();
                this.render();
                
                this.showModal('Success', `
                    <div class="text-center">
                        <i class="fas fa-check-circle text-green-500 text-4xl mb-4"></i>
                        <p class="text-lg">User created successfully!</p>
                        <button onclick="dashboard.closeModal()" 
                                class="mt-4 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                            OK
                        </button>
                    </div>
                `);
            }
        } catch (error) {
            console.error('Error creating user:', error);
            const message = error.response?.data?.message || 'Error creating user. Please try again.';
            alert(message);
        }
    }

    showAddCategoryForm() {
        const content = `
            <form id="categoryForm">
                <div class="grid grid-cols-1 gap-6">
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Category Names</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div id="categoryMacedonianNameField">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Category Name (MK)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_mk" required 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div id="categoryEnglishNameField">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Category Name (EN)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_en" required 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div id="categoryAlbanianNameField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Category Name (Albanian)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_al" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <input type="hidden" name="name" id="hiddenCategoryName">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Type</label>
                        <select name="type" required 
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Select Type</option>
                            ${this.categoryTypes.map(type => `
                                <option value="${type.name}">${type.name}</option>
                            `).join('')}
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Menu Layout</label>
                        <select name="layout" required 
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="grid">Grid Layout (Image on top, text below)</option>
                            <option value="horizontal">Horizontal Layout (Image on left, text on right)</option>
                        </select>
                        <p class="text-sm text-gray-500 mt-1">Choose how menu items in this category will be displayed</p>
                    </div>
                    
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Category Description</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div id="categoryMacedonianDescField">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Description (Macedonian)</span>
                                    </span>
                                </label>
                                <textarea name="description_mk" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                            </div>
                            <div id="categoryEnglishDescField">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Description (English)</span>
                                    </span>
                                </label>
                                <textarea name="description_en" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                            </div>
                            <div id="categoryAlbanianDescField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Description (Albanian)</span>
                                    </span>
                                </label>
                                <textarea name="description_al" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                            </div>
                        </div>
                        <input type="hidden" name="description" id="hiddenCategoryDescription">
                    </div>
                    
                    <!-- Category Sale Toggle -->
                    <div class="border-t pt-4 mt-4">
                        <label class="flex items-center mb-3">
                            <input type="checkbox" id="category_is_on_sale" name="is_on_sale" onchange="dashboard.toggleCategorySaleFields()" 
                                   class="mr-2 text-red-600 focus:ring-red-500 border-gray-300 rounded">
                            <span class="text-sm font-medium text-gray-700">Put entire category on sale</span>
                        </label>
                        
                        <!-- Category Sale Fields (hidden by default) -->
                        <div id="category-sale-fields" class="hidden grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Sale Type</label>
                                <select name="sale_type" id="category_sale_type" onchange="dashboard.handleCategorySaleTypeChange()" 
                                        class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-red-500">
                                    <option value="">Select sale type</option>
                                    <option value="percentage">Percentage discount (%)</option>
                                    <option value="fixed_discount">Fixed discount (ден)</option>
                                </select>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2" id="category_sale_value_label">Sale Value</label>
                                <input type="number" name="sale_value" id="category_sale_value" step="0.01" min="0" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-red-500"
                                       placeholder="Enter value">
                                <p class="text-sm text-gray-500 mt-1" id="category_sale_help_text">Select a sale type first</p>
                            </div>
                        </div>
                    </div>

                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        Create Category
                    </button>
                </div>
            </form>
        `;
        
        this.showModal('Add New Category', content);
        
        // Set up form handling to populate hidden fields
        const form = document.getElementById('categoryForm');
        form.addEventListener('submit', (e) => {
            // Use Macedonian as primary fallback to English, then to empty
            const nameMk = form.name_mk.value;
            const nameEn = form.name_en.value;
            form.querySelector('#hiddenCategoryName').value = nameMk || nameEn || '';
            
            const descMk = form.description_mk.value;
            const descEn = form.description_en.value;
            form.querySelector('#hiddenCategoryDescription').value = descMk || descEn || '';
        });
        
        document.getElementById('categoryForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitButton = e.target.querySelector('button[type="submit"]');
            if (!this.preventDoubleSubmission('categoryForm', submitButton)) {
                return; // Prevent duplicate submission
            }
            
            try {
                await this.handleCategoryForm(e.target);
            } finally {
                this.restoreSubmissionState('categoryForm', submitButton);
            }
        });
    }

    async handleCategoryForm(form, isEdit = false, categoryId = null) {
        try {
            const formData = new FormData(form);
            const parentId = formData.get('parent_id');


            const isOnSale = formData.get('is_on_sale') === 'on';
            const saleType = isOnSale ? formData.get('sale_type') : null;
            const saleValue = isOnSale && formData.get('sale_value') ? parseFloat(formData.get('sale_value')) : null;

            const categoryData = {
                name: formData.get('name'),
                name_mk: formData.get('name_mk'),
                name_en: formData.get('name_en'),
                name_al: formData.get('name_al'),
                type: formData.get('type'),
                description: formData.get('description'),
                description_mk: formData.get('description_mk'),
                description_en: formData.get('description_en'),
                description_al: formData.get('description_al'),
                layout: formData.get('layout') || 'grid',
                parent_id: parentId ? parseInt(parentId) : null,
                display_order: parseInt(formData.get('display_order')) || 0,
                restaurant_id: this.currentRestaurantId,
                is_on_sale: isOnSale,
                sale_type: saleType,
                sale_value: saleValue
            };

            let response;
            if (isEdit) {
                response = await axios.put(`/api/admin/categories/${categoryId}`, categoryData);
            } else {
                response = await axios.post('/api/admin/categories', categoryData);
            }

            if (response.data.success) {
                this.closeModal();
                await this.loadRestaurantData(this.currentRestaurantId);
                this.render();

                this.showModal('Success', `
                    <div class="text-center">
                        <i class="fas fa-check-circle text-green-500 text-4xl mb-4"></i>
                        <p class="text-lg">Category ${isEdit ? 'updated' : 'created'} successfully!</p>
                        <button onclick="dashboard.closeModal()" 
                                class="mt-4 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                            OK
                        </button>
                    </div>
                `);
            }
        } catch (error) {
            console.error('Error saving category:', error);
            alert('Error saving category. Please try again.');
        }
    }

    showAddMenuItemForm() {
        const availableCategories = this.categories.filter(c => c.restaurant_id === this.currentRestaurantId);
        
        const content = `
            <form id="menuItemForm" enctype="multipart/form-data">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Menu Item Names</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div id="menuItemMacedonianNameField">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Item Name (Macedonian)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_mk" required 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div id="menuItemEnglishNameField">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Item Name (English)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_en" required 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div id="menuItemAlbanianNameField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Item Name (Albanian)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_al" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <input type="hidden" name="name" id="hiddenMenuItemName">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Type</label>
                        <select name="type" id="type-select" required onchange="dashboard.updateCategoriesForType(this.value)"
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Select Type</option>
                            ${this.categoryTypes.map(type => `
                                <option value="${type.name}">${type.name}</option>
                            `).join('')}
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Category</label>
                        <select name="category_id" id="category-select" required 
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">First select a type</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Price (ден)</label>
                        <input type="number" name="price" step="1" min="0" required 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Size (Optional)</label>
                        <input type="text" name="size_info" placeholder="e.g., 100g, 330ml, Large" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <!-- Sale Toggle -->
                    <div class="md:col-span-2 border-t pt-4 mt-4">
                        <label class="flex items-center mb-3">
                            <input type="checkbox" id="is_on_sale" name="is_on_sale" onchange="dashboard.toggleSaleFields()" 
                                   class="mr-2 text-red-600 focus:ring-red-500 border-gray-300 rounded">
                            <span class="text-sm font-medium text-gray-700">Put this item on sale</span>
                        </label>
                        
                        <!-- Sale Fields (hidden by default) -->
                        <div id="sale-fields" class="hidden grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Sale Type</label>
                                <select name="sale_type" id="sale_type" onchange="dashboard.handleSaleTypeChange()" 
                                        class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-red-500">
                                    <option value="">Select sale type</option>
                                    <option value="percentage">Percentage discount (%)</option>
                                    <option value="fixed_discount">Fixed discount (ден)</option>
                                    <option value="sale_price">Set sale price (ден)</option>
                                </select>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2" id="sale_value_label">Sale Value</label>
                                <input type="number" name="sale_value" id="sale_value" step="0.01" min="0" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-red-500"
                                       placeholder="Enter value">
                                <p class="text-sm text-gray-500 mt-1" id="sale_help_text">Select a sale type first</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Description</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div id="menuItemMacedonianDescField">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Description (Macedonian)</span>
                                    </span>
                                </label>
                                <textarea name="description_mk" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                            </div>
                            <div id="menuItemEnglishDescField">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Description (English)</span>
                                    </span>
                                </label>
                                <textarea name="description_en" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                            </div>
                            <div id="menuItemAlbanianDescField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Description (Albanian)</span>
                                    </span>
                                </label>
                                <textarea name="description_al" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                            </div>
                        </div>
                        <input type="hidden" name="description" id="hiddenMenuItemDescription">
                    </div>
                    
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Allergens (Optional)</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div id="menuItemMacedonianAllergensField">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Allergens (Macedonian)</span>
                                    </span>
                                </label>
                                <input type="text" name="allergens_mk" placeholder="e.g., Глутен, Млечни, Орев, Јајца" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <p class="text-sm text-gray-500 mt-1">List allergens separated by commas</p>
                            </div>
                            <div id="menuItemEnglishAllergensField">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Allergens (English)</span>
                                    </span>
                                </label>
                                <input type="text" name="allergens_en" placeholder="e.g., Gluten, Dairy, Nuts, Eggs" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <p class="text-sm text-gray-500 mt-1">List allergens separated by commas</p>
                            </div>
                            <div id="menuItemAlbanianAllergensField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Allergens (Albanian)</span>
                                    </span>
                                </label>
                                <input type="text" name="allergens_al" placeholder="e.g., Gluten, Qumësht, Arra" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <p class="text-sm text-gray-500 mt-1">List allergens separated by commas</p>
                            </div>
                        </div>
                        <input type="hidden" name="allergens" id="hiddenMenuItemAllergens">
                    </div>
                    
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Menu Item Image (Optional)</h3>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Upload Image</label>
                            <input type="file" id="menuItemImageInput" name="image" accept="image/*" 
                                   class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <p class="text-sm text-gray-500 mt-1">Supported formats: JPG, PNG, GIF. Maximum size: 5MB</p>
                            <div id="menuItemImagePreview" class="mt-3 hidden">
                                <div class="relative">
                                    <img id="menuItemPreviewImage" src="" alt="Preview" class="max-w-xs max-h-48 rounded-lg border border-gray-300">
                                    <button type="button" onclick="dashboard.clearMenuItemImagePreview()" 
                                            class="absolute -top-2 -right-2 bg-red-600 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm hover:bg-red-700">
                                        ×
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        Create Menu Item
                    </button>
                </div>
            </form>
        `;
        
        this.showModal('Add New Menu Item', content);
        
        // Check and display Albanian fields based on restaurant settings
        setTimeout(() => checkAndDisplayAlbanianFields(this.currentRestaurantId, this), 100);
        
        // Set up image preview
        const imageInput = document.getElementById('menuItemImageInput');
        if (imageInput) {
            imageInput.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        document.getElementById('menuItemPreviewImage').src = e.target.result;
                        document.getElementById('menuItemImagePreview').classList.remove('hidden');
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
        
        // Set up form handling to populate hidden fields
        const form = document.getElementById('menuItemForm');
        form.addEventListener('submit', (e) => {
            // Use Macedonian as primary fallback to English, then to empty
            const nameMk = form.name_mk.value;
            const nameEn = form.name_en.value;
            form.querySelector('#hiddenMenuItemName').value = nameMk || nameEn || '';
            
            const descMk = form.description_mk.value;
            const descEn = form.description_en.value;
            form.querySelector('#hiddenMenuItemDescription').value = descMk || descEn || '';
            
            const allergensMk = form.allergens_mk.value;
            const allergensEn = form.allergens_en.value;
            const allergensAl = form.allergens_al ? form.allergens_al.value : '';
            form.querySelector('#hiddenMenuItemAllergens').value = allergensMk || allergensEn || allergensAl || '';
        });
        
        document.getElementById('menuItemForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitButton = e.target.querySelector('button[type="submit"]');
            if (!this.preventDoubleSubmission('menuItemForm', submitButton)) {
                return; // Prevent duplicate submission
            }
            
            try {
                await this.handleMenuItemForm(e.target);
            } finally {
                this.restoreSubmissionState('menuItemForm', submitButton);
            }
        });
    }

    async handleMenuItemForm(form, isEdit = false, itemId = null) {
        try {
            const formData = new FormData(form);
            const isOnSale = formData.get('is_on_sale') === 'on';
            const saleType = isOnSale ? formData.get('sale_type') : null;
            const saleValue = isOnSale && formData.get('sale_value') ? parseFloat(formData.get('sale_value')) : null;
            const originalPrice = parseFloat(formData.get('price'));

            // Handle image upload if file is selected
            let imageUrl = formData.get('current_image_url') || null;
            const imageFile = formData.get('image');
            const deleteImage = formData.get('delete_image') === 'true';
            
            // If user wants to delete current image, set it to null
            if (deleteImage) {
                imageUrl = null;
            } else if (imageFile && imageFile.size > 0) {
                // Upload the image first
                const imageFormData = new FormData();
                imageFormData.append('image', imageFile);
                
                // Add item name_en for proper file naming
                const nameEn = formData.get('name_en');
                if (nameEn && nameEn.trim()) {
                    imageFormData.append('item_name_en', nameEn.trim());
                }
                
                try {
                    // Get restaurant slug for folder structure
                    const restaurantSlug = this.getCurrentRestaurantSlug();
                    if (!restaurantSlug) {
                        alert('Restaurant slug not found. Please try again.');
                        return;
                    }
                    
                    const uploadResponse = await axios.post(`/api/upload/menu-items/${restaurantSlug}`, imageFormData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    });
                    
                    if (uploadResponse.data.success) {
                        imageUrl = uploadResponse.data.data.url;
                    }
                } catch (uploadError) {
                    console.error('Error uploading image:', uploadError);
                    alert('Failed to upload image. Please try again.');
                    return;
                }
            }

            // Get display_order: preserve existing order when editing, use 0 for new items
            let displayOrder = 0;
            if (isEdit && itemId) {
                // When editing, preserve the original item's display order
                const originalItem = this.menuItems.find(i => i.id === itemId);
                if (originalItem) {
                    displayOrder = originalItem.display_order;
                }
            }

            const menuItemData = {
                name: formData.get('name'),
                name_mk: formData.get('name_mk'),
                name_en: formData.get('name_en'),
                name_al: formData.get('name_al'),
                description: formData.get('description'),
                description_mk: formData.get('description_mk'),
                description_en: formData.get('description_en'),
                description_al: formData.get('description_al'),
                price: originalPrice,
                size_info: formData.get('size_info') || null,
                allergens: formData.get('allergens') || null,
                allergens_mk: formData.get('allergens_mk'),
                allergens_en: formData.get('allergens_en'),
                allergens_al: formData.get('allergens_al'),
                image_url: imageUrl,
                category_id: parseInt(formData.get('category_id')),
                is_available: true, // Default to available since we removed the field
                display_order: displayOrder, // Preserve order when editing, use 0 for new items
                restaurant_id: this.currentRestaurantId,
                is_on_sale: isOnSale,
                sale_type: saleType,
                sale_value: saleValue,
                original_price: isOnSale ? originalPrice : null
            };

            let response;
            if (isEdit) {
                response = await axios.put(`/api/admin/menu-items/${itemId}`, menuItemData);
            } else {
                response = await axios.post('/api/admin/menu-items', menuItemData);
            }

            if (response.data.success) {
                this.closeModal();
                await this.loadRestaurantData(this.currentRestaurantId);
                this.render();
                
                this.showModal('Success', `
                    <div class="text-center">
                        <i class="fas fa-check-circle text-green-500 text-4xl mb-4"></i>
                        <p class="text-lg">Menu item ${isEdit ? 'updated' : 'created'} successfully!</p>
                        <button onclick="dashboard.closeModal()" 
                                class="mt-4 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                            OK
                        </button>
                    </div>
                `);
            }
        } catch (error) {
            console.error('Error saving menu item:', error);
            alert('Error saving menu item. Please try again.');
        }
    }

    async editRestaurant(id) {
        const restaurant = this.restaurants.find(r => r.id === id);
        if (!restaurant) return;
        if (this.user.role === 'restaurant_admin' && this.user.restaurant_id !== id) {
            alert('You can only edit your own restaurant information.');
            return;
        }

        const content = `
            <form id="restaurantForm" enctype="multipart/form-data">
                <input type="hidden" name="current_logo_url" value="${restaurant.logo_url || ''}">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Restaurant Name</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            <div class="lang-field lang-field-mk">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Name (Macedonian)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_mk" value="${restaurant.name_mk || ''}"
                                       placeholder="Внесете име на ресторан"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div class="lang-field lang-field-en">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Name (English)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_en" value="${restaurant.name_en || ''}"
                                       placeholder="Enter restaurant name"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div class="lang-field lang-field-al">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Name (Albanian)</span>
                                    </span>
                                </label>
                                <input type="text" name="name_al" value="${restaurant.name_al || ''}"
                                       placeholder="Vendosni emrin e restorantit"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <input type="hidden" name="name" id="hiddenName" value="${restaurant.name || ''}">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Slug (URL identifier)</label>
                        <input type="text" name="slug" value="${restaurant.slug || ''}" required 
                               placeholder="e.g., my-restaurant (letters, numbers, hyphens only)"
                               pattern="[a-z0-9-]+" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Email (Optional)</label>
                        <input type="email" name="email" value="${restaurant.email || ''}" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Phone</label>
                        <input type="tel" name="phone" value="${restaurant.phone || ''}" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Website (Optional)</label>
                        <input type="url" name="website" value="${restaurant.website || ''}" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Facebook (Optional)</label>
                        <input type="url" name="facebook" value="${restaurant.facebook || ''}" 
                               placeholder="e.g., https://facebook.com/restaurant"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Instagram (Optional)</label>
                        <input type="url" name="instagram" value="${restaurant.instagram || ''}" 
                               placeholder="e.g., https://instagram.com/restaurant"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Restaurant Description</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            <div class="lang-field lang-field-mk">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Description (Macedonian)</span>
                                    </span>
                                </label>
                                <textarea name="description_mk" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${restaurant.description_mk || ''}</textarea>
                            </div>
                            <div class="lang-field lang-field-en">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Description (English)</span>
                                    </span>
                                </label>
                                <textarea name="description_en" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${restaurant.description_en || ''}</textarea>
                            </div>
                            <div class="lang-field lang-field-al">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Description (Albanian)</span>
                                    </span>
                                </label>
                                <textarea name="description_al" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${restaurant.description_al || ''}</textarea>
                            </div>
                        </div>
                        <input type="hidden" name="description" id="hiddenDescription" value="${restaurant.description || ''}">
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Address</label>
                        <textarea name="address" rows="2" 
                                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${restaurant.address || ''}</textarea>
                    </div>
                    
                    ${this.user.role === 'super_admin' ? `
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Subscription Start</label>
                            <input type="date" name="subscription_start" value="${restaurant.subscription_start ? restaurant.subscription_start.split('T')[0] : ''}" 
                                   class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Subscription End</label>
                            <input type="date" name="subscription_end" value="${restaurant.subscription_end ? restaurant.subscription_end.split('T')[0] : ''}" 
                                   class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                    ` : ''}
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">WiFi Network Name</label>
                        <input type="text" name="wifi_name" value="${restaurant.wifi_name || ''}" 
                               placeholder="e.g., Restaurant_WiFi"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <p class="text-sm text-gray-500 mt-1">WiFi network name that customers can see</p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">WiFi Password</label>
                        <input type="text" name="wifi_password" value="${restaurant.wifi_password || ''}" 
                               placeholder="e.g., welcome123"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <p class="text-sm text-gray-500 mt-1">WiFi password for customers</p>
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-3">Supported Languages</label>
                        <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                            <label class="flex items-center space-x-2 p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                <input type="checkbox" name="supported_languages" value="mk" ${!restaurant.supported_languages || restaurant.supported_languages.includes('mk') ? 'checked' : ''} 
                                       class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 language-checkbox">
                                <span class="text-2xl">🇲🇰</span>
                                <span class="text-sm font-medium text-gray-700">Macedonian</span>
                            </label>
                            <label class="flex items-center space-x-2 p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                <input type="checkbox" name="supported_languages" value="en" ${!restaurant.supported_languages || restaurant.supported_languages.includes('en') ? 'checked' : ''} 
                                       class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 language-checkbox">
                                <span class="text-2xl">🇬🇧</span>
                                <span class="text-sm font-medium text-gray-700">English</span>
                            </label>
                            <label class="flex items-center space-x-2 p-3 border border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                <input type="checkbox" name="supported_languages" value="al" ${!restaurant.supported_languages || restaurant.supported_languages.includes('al') ? 'checked' : ''} 
                                       class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 language-checkbox">
                                <span class="text-2xl">🇦🇱</span>
                                <span class="text-sm font-medium text-gray-700">Albanian</span>
                            </label>
                        </div>
                        <p class="text-sm text-gray-500 mt-2">Select which languages this restaurant will use. Only selected language fields will appear in forms.</p>
                    </div>
                    
                    ${this.user.role === 'super_admin' ? `
                        <div class="md:col-span-2">
                            <label class="flex items-center space-x-3">
                                <input type="checkbox" name="has_infinite_subscription" 
                                       ${restaurant.has_infinite_subscription ? 'checked' : ''}
                                       class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                                <div>
                                    <span class="text-sm font-medium text-gray-700">Infinite Subscription</span>
                                    <p class="text-sm text-gray-500">Check this to prevent automatic deactivation of this restaurant</p>
                                </div>
                            </label>
                        </div>
                    ` : ''}
                    
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Color Theme</label>
                        <select name="selected_theme" id="themeSelector" data-selected="${restaurant.selected_theme || ''}"
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Loading themes...</option>
                        </select>
                        <p class="text-sm text-gray-500 mt-1">Choose a color scheme for the restaurant's live menu</p>
                    </div>
                    
                    <div class="md:col-span-2">
                        ${restaurant.logo_url ? `
                            <div class="mb-2" id="currentLogoContainer">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Current Logo</label>
                                <div class="relative inline-block">
                                    <img src="${restaurant.logo_url}" alt="Current logo" class="w-16 h-16 rounded object-cover">
                                    <button type="button" onclick="dashboard.deleteCurrentImage('restaurant', '${restaurant.id}')" 
                                            class="absolute -top-2 -right-2 bg-red-600 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm hover:bg-red-700 shadow-lg">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                                <input type="hidden" name="delete_logo" id="deleteLogoFlag" value="false">
                            </div>
                        ` : ''}
                        <label class="block text-sm font-medium text-gray-700 mb-2">Logo Image (Optional)</label>
                        <input type="file" name="logo" accept="image/*" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <p class="text-sm text-gray-500 mt-1">Upload a new logo image (max 5MB) or leave empty to keep current</p>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        Update Restaurant
                    </button>
                </div>
            </form>
        `;
        
        this.showModal('Edit Restaurant', content);
        
        // Load themes
        this.loadThemesForForm(restaurant.selected_theme);
        
        // Set up language field visibility toggle
        this.setupLanguageFieldToggle();
        
        // Set up form handling to populate hidden fields
        const form = document.getElementById('restaurantForm');
        form.addEventListener('submit', (e) => {
            const nameMk = form.name_mk.value;
            const nameEn = form.name_en.value;
            const nameAl = form.name_al.value;
            const descMk = form.description_mk.value;
            const descEn = form.description_en.value;
            const descAl = form.description_al.value;
            form.querySelector('#hiddenName').value = nameMk || nameEn || nameAl || '';
            form.querySelector('#hiddenDescription').value = descMk || descEn || descAl || '';
        });
        
        document.getElementById('restaurantForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitButton = e.target.querySelector('button[type="submit"]');
            if (!this.preventDoubleSubmission('restaurantForm', submitButton)) {
                return; // Prevent duplicate submission
            }
            
            try {
                await this.handleRestaurantForm(e.target, true, id);
            } finally {
                this.restoreSubmissionState('restaurantForm', submitButton);
            }
        });
    }

    async editCategory(id) {
        const category = this.categories.find(c => c.id === id);
        if (!category) return;

        const content = `
            <form id="categoryForm">
                <div class="grid grid-cols-1 gap-6">
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Category Names</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Category Name (Macedonian)</label>
                                <input type="text" name="name_mk" value="${this.escapeHtml(category.name_mk || '')}" required 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Category Name (English)</label>
                                <input type="text" name="name_en" value="${this.escapeHtml(category.name_en || '')}" required 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div id="categoryAlbanianNameField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Category Name (Albanian)</label>
                                <input type="text" name="name_al" value="${this.escapeHtml(category.name_al || '')}" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <input type="hidden" name="name" id="hiddenCategoryName" value="${this.escapeHtml(category.name || '')}">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Type</label>
                        <select name="type" required 
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            ${this.categoryTypes.map(type => `
                                <option value="${this.escapeHtml(type.name)}" ${category.type === type.name ? 'selected' : ''}>${this.escapeHtml(type.name)}</option>
                            `).join('')}
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Menu Layout</label>
                        <select name="layout" required 
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="grid" ${category.layout === 'grid' || !category.layout ? 'selected' : ''}>Grid Layout (Image on top, text below)</option>
                            <option value="horizontal" ${category.layout === 'horizontal' ? 'selected' : ''}>Horizontal Layout (Image on left, text on right)</option>
                        </select>
                        <p class="text-sm text-gray-500 mt-1">Choose how menu items in this category will be displayed</p>
                    </div>
                    
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Category Description</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Description (Macedonian)</label>
                                <textarea name="description_mk" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${this.escapeHtml(category.description_mk || '')}</textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Description (English)</label>
                                <textarea name="description_en" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${this.escapeHtml(category.description_en || '')}</textarea>
                            </div>
                            <div id="categoryAlbanianDescField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Description (Albanian)</label>
                                <textarea name="description_al" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${this.escapeHtml(category.description_al || '')}</textarea>
                            </div>
                        </div>
                        <input type="hidden" name="description" id="hiddenCategoryDescription" value="${this.escapeHtml(category.description || '')}">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Display Order</label>
                        <input type="number" name="display_order" value="${category.display_order || 0}" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        Update Category
                    </button>
                </div>
            </form>
        `;
        
        this.showModal('Edit Category', content);
        
        // Set up form handling to populate hidden fields
        const form = document.getElementById('categoryForm');
        form.addEventListener('submit', (e) => {
            // Use Macedonian as primary fallback to English, then to empty
            const nameMk = form.name_mk.value;
            const nameEn = form.name_en.value;
            form.querySelector('#hiddenCategoryName').value = nameMk || nameEn || '';
            
            const descMk = form.description_mk.value;
            const descEn = form.description_en.value;
            form.querySelector('#hiddenCategoryDescription').value = descMk || descEn || '';
        });
        
        document.getElementById('categoryForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitButton = e.target.querySelector('button[type="submit"]');
            if (!this.preventDoubleSubmission('categoryForm', submitButton)) {
                return; // Prevent duplicate submission
            }
            
            try {
                await this.handleCategoryForm(e.target, true, id);
            } finally {
                this.restoreSubmissionState('categoryForm', submitButton);
            }
        });
    }

    async editMenuItem(id) {
        const item = this.menuItems.find(i => i.id === id);
        if (!item) return;

        const availableCategories = this.categories.filter(c => c.restaurant_id === this.currentRestaurantId);
        
        const content = `
            <form id="menuItemForm" enctype="multipart/form-data">
                <input type="hidden" name="current_image_url" value="${item.image_url || ''}">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Menu Item Names</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Item Name (Macedonian)</label>
                                <input type="text" name="name_mk" value="${item.name_mk || ''}" required 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Item Name (English)</label>
                                <input type="text" name="name_en" value="${item.name_en || ''}" required 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div id="menuItemAlbanianNameField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Item Name (Albanian)</label>
                                <input type="text" name="name_al" value="${item.name_al || ''}" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <input type="hidden" name="name" id="hiddenMenuItemName" value="${item.name}">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Type</label>
                        <select name="type" id="type-select" required onchange="dashboard.updateCategoriesForType(this.value)"
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Select Type</option>
                            ${this.categoryTypes.map(type => {
                                const selectedCategory = availableCategories.find(c => c.id === item.category_id);
                                const isSelected = selectedCategory && selectedCategory.type === type.name;
                                return `<option value="${type.name}" ${isSelected ? 'selected' : ''}>${type.name}</option>`;
                            }).join('')}
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Category</label>
                        <select name="category_id" id="category-select" required 
                                class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Select Category</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Price (ден)</label>
                        <input type="number" name="price" step="1" min="0" value="${item.price}" required 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Size (Optional)</label>
                        <input type="text" name="size_info" value="${item.size_info || ''}" placeholder="e.g., 100g, 330ml, Large" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <!-- Sale Toggle -->
                    <div class="md:col-span-2 border-t pt-4 mt-4">
                        <label class="flex items-center mb-3">
                            <input type="checkbox" id="is_on_sale" name="is_on_sale" ${item.is_on_sale ? 'checked' : ''} onchange="dashboard.toggleSaleFields()" 
                                   class="mr-2 text-red-600 focus:ring-red-500 border-gray-300 rounded">
                            <span class="text-sm font-medium text-gray-700">Put this item on sale</span>
                        </label>
                        
                        <!-- Sale Fields -->
                        <div id="sale-fields" class="${item.is_on_sale ? '' : 'hidden'} grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Sale Type</label>
                                <select name="sale_type" id="sale_type" onchange="dashboard.handleSaleTypeChange()" 
                                        class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-red-500">
                                    <option value="">Select sale type</option>
                                    <option value="percentage" ${item.sale_type === 'percentage' ? 'selected' : ''}>Percentage discount (%)</option>
                                    <option value="fixed_discount" ${item.sale_type === 'fixed_discount' ? 'selected' : ''}>Fixed discount (ден)</option>
                                    <option value="sale_price" ${item.sale_type === 'sale_price' ? 'selected' : ''}>Set sale price (ден)</option>
                                </select>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2" id="sale_value_label">Sale Value</label>
                                <input type="number" name="sale_value" id="sale_value" step="0.01" min="0" value="${item.sale_value || ''}"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-red-500"
                                       placeholder="Enter value">
                                <p class="text-sm text-gray-500 mt-1" id="sale_help_text">Select a sale type first</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Description</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Description (Macedonian)</label>
                                <textarea name="description_mk" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${item.description_mk || ''}</textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Description (English)</label>
                                <textarea name="description_en" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${item.description_en || ''}</textarea>
                            </div>
                            <div id="menuItemAlbanianDescField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Description (Albanian)</label>
                                <textarea name="description_al" rows="3" 
                                          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${item.description_al || ''}</textarea>
                            </div>
                        </div>
                        <input type="hidden" name="description" id="hiddenMenuItemDescription" value="${item.description || ''}">
                    </div>
                    
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Allergens (Optional)</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Allergens (Macedonian)</label>
                                <input type="text" name="allergens_mk" value="${item.allergens_mk || ''}" placeholder="e.g., Глутен, Млечни, Орев, Јајца" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <p class="text-sm text-gray-500 mt-1">List allergens separated by commas</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Allergens (English)</label>
                                <input type="text" name="allergens_en" value="${item.allergens_en || ''}" placeholder="e.g., Gluten, Dairy, Nuts, Eggs" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <p class="text-sm text-gray-500 mt-1">List allergens separated by commas</p>
                            </div>
                            <div id="menuItemAlbanianAllergensField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Allergens (Albanian)</label>
                                <input type="text" name="allergens_al" value="${item.allergens_al || ''}" placeholder="e.g., Gluten, Qumësht, Arra" 
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <p class="text-sm text-gray-500 mt-1">List allergens separated by commas</p>
                            </div>
                        </div>
                        <input type="hidden" name="allergens" id="hiddenMenuItemAllergens" value="${item.allergens || ''}">
                    </div>
                    
                    <div class="md:col-span-2">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Menu Item Image (Optional)</h3>
                        ${item.image_url ? `
                            <div class="mb-3" id="currentImageContainer">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Current Image</label>
                                <div class="relative inline-block">
                                    <img src="${item.image_url}" alt="${item.name}" class="max-w-xs max-h-48 rounded-lg border border-gray-300">
                                    <button type="button" onclick="dashboard.deleteCurrentImage('menuItem', '${item.id}')" 
                                            class="absolute -top-2 -right-2 bg-red-600 text-white rounded-full w-8 h-8 flex items-center justify-center text-sm hover:bg-red-700 shadow-lg">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                                <input type="hidden" name="delete_image" id="deleteImageFlag" value="false">
                            </div>
                        ` : ''}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">${item.image_url ? 'Replace Image' : 'Upload Image'}</label>
                            <input type="file" id="menuItemImageInput" name="image" accept="image/*" 
                                   class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <p class="text-sm text-gray-500 mt-1">Supported formats: JPG, PNG, GIF. Maximum size: 5MB</p>
                            <div id="menuItemImagePreview" class="mt-3 hidden">
                                <div class="relative">
                                    <img id="menuItemPreviewImage" src="" alt="Preview" class="max-w-xs max-h-48 rounded-lg border border-gray-300">
                                    <button type="button" onclick="dashboard.clearMenuItemImagePreview()" 
                                            class="absolute -top-2 -right-2 bg-red-600 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm hover:bg-red-700">
                                        ×
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        Update Menu Item
                    </button>
                </div>
            </form>
        `;
        
        this.showModal('Edit Menu Item', content);
        
        // Set up image preview
        const imageInput = document.getElementById('menuItemImageInput');
        if (imageInput) {
            imageInput.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        document.getElementById('menuItemPreviewImage').src = e.target.result;
                        document.getElementById('menuItemImagePreview').classList.remove('hidden');
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
        
        // Set up form handling to populate hidden fields
        const form = document.getElementById('menuItemForm');
        form.addEventListener('submit', (e) => {
            // Use Macedonian as primary fallback to English, then to empty
            const nameMk = form.name_mk.value;
            const nameEn = form.name_en.value;
            form.querySelector('#hiddenMenuItemName').value = nameMk || nameEn || '';
            
            const descMk = form.description_mk.value;
            const descEn = form.description_en.value;
            form.querySelector('#hiddenMenuItemDescription').value = descMk || descEn || '';
            
            const allergensMk = form.allergens_mk.value;
            const allergensEn = form.allergens_en.value;
            const allergensAl = form.allergens_al ? form.allergens_al.value : '';
            form.querySelector('#hiddenMenuItemAllergens').value = allergensMk || allergensEn || allergensAl || '';
        });
        
        document.getElementById('menuItemForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitButton = e.target.querySelector('button[type="submit"]');
            if (!this.preventDoubleSubmission('menuItemForm', submitButton)) {
                return; // Prevent duplicate submission
            }
            
            try {
                await this.handleMenuItemForm(e.target, true, id);
            } finally {
                this.restoreSubmissionState('menuItemForm', submitButton);
            }
        });
        

        const selectedCategory = availableCategories.find(c => c.id === item.category_id);
        if (selectedCategory) {
            setTimeout(() => {

                this.updateCategoriesForType(selectedCategory.type);

                const categorySelect = document.getElementById('category-select');
                if (categorySelect) {
                    categorySelect.value = item.category_id;
                }

                this.handleSaleTypeChange();
            }, 100);
        }
    }

    async toggleRestaurantStatus(id, newStatus) {
        const restaurant = this.restaurants.find(r => r.id === id);
        if (!restaurant) return;

        const action = newStatus ? 'activate' : 'deactivate';
        let message = `Are you sure you want to ${action} "${restaurant.name}"?`;
        
        if (confirm(message)) {
            try {
                const response = await axios.put(`/api/admin/restaurants/${id}/status`, {
                    is_active: newStatus,
                    only_restaurant: true  // Flag to only update restaurant, not users
                });

                if (response.data.success) {
                    await this.loadData();
                    this.render();
                } else {
                    alert('Failed to update restaurant status. Please try again.');
                }
            } catch (error) {
                console.error('Error updating restaurant status:', error);
                alert('Error updating restaurant status. Please try again.');
            }
        }
    }

    async toggleUserStatus(id, newStatus) {
        const user = this.users.find(u => u.id === id);
        if (!user) return;

        const action = newStatus ? 'activate' : 'deactivate';
        if (confirm(`Are you sure you want to ${action} user "${user.name}"?`)) {
            try {
                const response = await axios.put(`/api/admin/users/${id}/status`, {
                    is_active: newStatus
                });

                if (response.data.success) {
                    await this.loadData();
                    this.render();
                } else {
                    alert('Failed to update user status. Please try again.');
                }
            } catch (error) {
                console.error('Error updating user status:', error);
                alert('Error updating user status. Please try again.');
            }
        }
    }

    async deleteRestaurant(id) {
        const restaurant = this.restaurants.find(r => r.id === id);
        if (!restaurant) return;

        if (confirm(`Are you sure you want to delete "${restaurant.name}"? This action cannot be undone.`)) {
            try {
                const response = await axios.delete(`/api/admin/restaurants/${id}`);
                if (response.data.success) {
                    await this.loadData();
                    this.render();
                }
            } catch (error) {
                console.error('Error deleting restaurant:', error);
                alert('Error deleting restaurant. Please try again.');
            }
        }
    }

    async deleteUser(id) {
        const user = this.users.find(u => u.id === id);
        if (!user) return;

        if (confirm(`Are you sure you want to delete user "${user.name}"? This action cannot be undone.`)) {
            try {
                const response = await axios.delete(`/api/admin/users/${id}`);
                if (response.data.success) {
                    await this.loadData();
                    this.render();
                }
            } catch (error) {
                console.error('Error deleting user:', error);
                alert('Error deleting user. Please try again.');
            }
        }
    }

    showAddCategoryTypeForm() {
        const content = `
            <form id="categoryTypeForm">
                <div class="grid grid-cols-1 gap-6">
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Category Type Names</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Type Name (Macedonian)</label>
                                <input type="text" name="name_mk" required 
                                       placeholder="e.g., Храна, Пијалоци"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Type Name (English)</label>
                                <input type="text" name="name_en" required 
                                       placeholder="e.g., Food, Beverages"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div id="typeAlbanianNameField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Type Name (Albanian)</label>
                                <input type="text" name="name_al" 
                                       placeholder="e.g., Ushqim, Pije"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <input type="hidden" name="name" id="hiddenTypeName">
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                        <i class="fas fa-plus mr-2"></i>Create Type
                    </button>
                </div>
            </form>
        `;

        this.showModal('Add Category Type', content);
        
        // Set up form handling to populate hidden fields
        const form = document.getElementById('categoryTypeForm');
        form.addEventListener('submit', (e) => {
            // Use Macedonian as primary fallback to English, then to empty
            const nameMk = form.name_mk.value;
            const nameEn = form.name_en.value;
            form.querySelector('#hiddenTypeName').value = nameMk || nameEn || '';
        });
        
        document.getElementById('categoryTypeForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitButton = e.target.querySelector('button[type="submit"]');
            if (!this.preventDoubleSubmission('categoryTypeForm', submitButton)) {
                return; // Prevent duplicate submission
            }
            
            try {
                await this.handleCategoryTypeForm(e.target);
            } finally {
                this.restoreSubmissionState('categoryTypeForm', submitButton);
            }
        });
    }

    async handleCategoryTypeForm(form) {
        try {
            const formData = new FormData(form);
            const typeData = {
                restaurant_id: this.currentRestaurantId,
                name: formData.get('name'),
                name_mk: formData.get('name_mk'),
                name_en: formData.get('name_en'),
                name_al: formData.get('name_al')
            };

            const response = await axios.post('/api/admin/category-types', typeData);

            if (response.data.success) {
                this.closeModal();
                await this.loadRestaurantData(this.currentRestaurantId);
                this.render();
            } else {
                alert('Failed to create category type. Please try again.');
            }
        } catch (error) {
            console.error('Error creating category type:', error);
            if (error.response?.status === 400) {
                alert(error.response.data.message || 'Category type already exists');
            } else {
                alert('Error creating category type. Please try again.');
            }
        }
    }

    async editCategoryType(id) {
        const categoryType = this.categoryTypes.find(t => t.id === id);
        if (!categoryType) return;

        const content = `
            <form id="editCategoryTypeForm">
                <div class="grid grid-cols-1 gap-6">
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Category Type Names</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Type Name (Macedonian)</label>
                                <input type="text" name="name_mk" value="${this.escapeHtml(categoryType.name_mk || '')}" required 
                                       placeholder="e.g., Храна, Пијалоци"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Type Name (English)</label>
                                <input type="text" name="name_en" value="${this.escapeHtml(categoryType.name_en || '')}" required 
                                       placeholder="e.g., Food, Beverages"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div id="typeAlbanianNameField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Type Name (Albanian)</label>
                                <input type="text" name="name_al" value="${this.escapeHtml(categoryType.name_al || '')}" 
                                       placeholder="e.g., Ushqim, Pije"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <input type="hidden" name="name" id="hiddenEditTypeName" value="${this.escapeHtml(categoryType.name || '')}">
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        <i class="fas fa-save mr-2"></i>Update Type
                    </button>
                </div>
            </form>
        `;

        this.showModal('Edit Category Type', content);
        
        // Set up form handling to populate hidden fields
        const form = document.getElementById('editCategoryTypeForm');
        form.addEventListener('submit', (e) => {
            // Use Macedonian as primary fallback to English, then to empty
            const nameMk = form.name_mk.value;
            const nameEn = form.name_en.value;
            form.querySelector('#hiddenEditTypeName').value = nameMk || nameEn || '';
        });
        
        document.getElementById('editCategoryTypeForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitButton = e.target.querySelector('button[type="submit"]');
            if (!this.preventDoubleSubmission('editCategoryTypeForm', submitButton)) {
                return; // Prevent duplicate submission
            }
            
            try {
                await this.handleCategoryTypeEdit(e.target, id);
            } finally {
                this.restoreSubmissionState('editCategoryTypeForm', submitButton);
            }
        });
    }

    async handleCategoryTypeEdit(form, id) {
        try {
            const formData = new FormData(form);
            const typeData = {
                name: formData.get('name'),
                name_mk: formData.get('name_mk'),
                name_en: formData.get('name_en'),
                name_al: formData.get('name_al')
            };

            const response = await axios.put(`/api/admin/category-types/${id}`, typeData);

            if (response.data.success) {
                this.closeModal();
                await this.loadRestaurantData(this.currentRestaurantId);
                this.render();
            } else {
                alert('Failed to update category type. Please try again.');
            }
        } catch (error) {
            console.error('Error updating category type:', error);
            if (error.response?.status === 400) {
                alert(error.response.data.message || 'Category type name already exists');
            } else {
                alert('Error updating category type. Please try again.');
            }
        }
    }

    async deleteCategoryType(id) {
        const categoryType = this.categoryTypes.find(t => t.id === id);
        if (!categoryType) return;

        const categoriesCount = this.categories.filter(c => c.type === categoryType.name).length;
        
        let message = `Are you sure you want to delete category type "${categoryType.name}"?`;
        if (categoriesCount > 0) {
            message += `\n\nThis will also delete ${categoriesCount} categories and all their menu items. This action cannot be undone.`;
        }

        if (confirm(message)) {
            try {
                const response = await axios.delete(`/api/admin/category-types/${id}`);
                if (response.data.success) {
                    await this.loadRestaurantData(this.currentRestaurantId);
                    this.render();
                }
            } catch (error) {
                console.error('Error deleting category type:', error);
                alert('Error deleting category type. Please try again.');
            }
        }
    }

    async deleteCategory(id) {
        const category = this.categories.find(c => c.id === id);
        if (!category) return;

        if (confirm(`Are you sure you want to delete category "${category.name}"? This action cannot be undone.`)) {
            try {
                const response = await axios.delete(`/api/admin/categories/${id}`);
                if (response.data.success) {
                    await this.loadRestaurantData(this.currentRestaurantId);
                    this.render();
                }
            } catch (error) {
                console.error('Error deleting category:', error);
                alert('Error deleting category. Please try again.');
            }
        }
    }

    async deleteMenuItem(id) {
        const item = this.menuItems.find(i => i.id === id);
        if (!item) return;

        if (confirm(`Are you sure you want to delete "${item.name}"? This action cannot be undone.`)) {
            try {
                const response = await axios.delete(`/api/admin/menu-items/${id}`);
                if (response.data.success) {
                    await this.loadRestaurantDataWithFilter();
                    this.render();
                }
            } catch (error) {
                console.error('Error deleting menu item:', error);
                alert('Error deleting menu item. Please try again.');
            }
        }
    }

    async duplicateMenuItem(id) {
        const item = this.menuItems.find(i => i.id === id);
        if (!item) return;

        if (confirm(`Do you want to duplicate "${item.name}"? This will create a copy of this menu item.`)) {
            try {
                const response = await axios.post(`/api/admin/menu-items/${id}/duplicate`);
                if (response.data.success) {
                    await this.loadRestaurantDataWithFilter();
                    this.render();
                    alert('Menu item duplicated successfully!');
                }
            } catch (error) {
                console.error('Error duplicating menu item:', error);
                alert('Error duplicating menu item. Please try again.');
            }
        }
    }

    async toggleItemVisibility(id, isVisible) {
        try {
            const response = await axios.put(`/api/admin/menu-items/${id}`, {
                is_visible: isVisible
            });
            
            if (response.data.success) {

                const item = this.menuItems.find(i => i.id === id);
                if (item) {
                    item.is_visible = isVisible;
                }
                

                this.render();
                

                await this.loadRestaurantDataWithFilter();
            }
        } catch (error) {
            console.error('Error toggling item visibility:', error);
            alert('Error updating item visibility. Please try again.');
        }
    }

    async toggleItemSale(id, enableSale) {
        try {
            const item = this.menuItems.find(i => i.id === id);
            if (!item) {
                alert('Menu item not found.');
                return;
            }

            let saleData;
            
            if (enableSale) {

                const saleConfig = await this.showSaleConfigModal(item);
                if (!saleConfig) return; // User cancelled
                
                saleData = {
                    is_on_sale: true,
                    sale_type: saleConfig.sale_type,
                    sale_value: parseFloat(saleConfig.sale_value),
                    original_price: parseFloat(item.price)
                };
            } else {

                saleData = {
                    is_on_sale: false,
                    sale_type: null,
                    sale_value: null,
                    original_price: null
                };
            }

            const response = await axios.put(`/api/admin/menu-items/${id}`, saleData);
            
            if (response.data.success) {

                Object.assign(item, saleData);
                

                this.render();
                

                await this.loadRestaurantDataWithFilter();
                
                const action = enableSale ? 'added' : 'removed';
                alert(`Sale ${action} successfully!`);
            }
        } catch (error) {
            console.error('Error toggling item sale:', error);
            alert('Error updating item sale. Please try again.');
        }
    }

    async toggleHotItem(id) {
        try {
            const item = this.menuItems.find(i => i.id === id);
            if (!item) {
                alert('Menu item not found.');
                return;
            }

            const response = await axios.put(`/api/admin/menu-items/${id}/toggle-hot`);
            
            if (response.data.success) {
                // Update the item's hot status
                item.is_hot_item = response.data.is_hot_item;
                
                // Re-render the view
                this.render();
                
                const status = item.is_hot_item ? 'marked as hot item' : 'removed from hot items';
                alert(`Item ${status} successfully!`);
            }
        } catch (error) {
            console.error('Error toggling hot item:', error);
            alert('Error updating hot item status. Please try again.');
        }
    }

    async showSaleConfigModal(item) {
        return new Promise((resolve) => {
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50';
            modal.innerHTML = `
                <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                    <div class="mt-3">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Configure Sale for "${item.name}"</h3>
                        <form id="saleConfigForm">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Sale Type:</label>
                                <select id="saleType" class="w-full border border-gray-300 rounded-md px-3 py-2" required>
                                    <option value="">Select sale type</option>
                                    <option value="percentage">Percentage Discount</option>
                                    <option value="fixed_discount">Fixed Amount Discount</option>
                                    <option value="sale_price">Direct Sale Price</option>
                                </select>
                            </div>
                            
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Sale Value:</label>
                                <input type="number" id="saleValue" step="0.01" min="0" 
                                       class="w-full border border-gray-300 rounded-md px-3 py-2" 
                                       placeholder="Enter value" required>
                                <div id="saleHelp" class="text-sm text-gray-500 mt-1"></div>
                            </div>
                            
                            <div class="mb-4 p-3 bg-blue-50 rounded-md">
                                <div class="text-sm">
                                    <strong>Original Price:</strong> ${parseFloat(item.price).toFixed(2)} ден<br>
                                    <strong>New Price:</strong> <span id="newPrice">-</span>
                                </div>
                            </div>
                            
                            <div class="flex justify-end space-x-2">
                                <button type="button" onclick="this.closest('.fixed').remove(); resolve(null);" 
                                        class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">
                                    Cancel
                                </button>
                                <button type="submit" 
                                        class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700">
                                    Add Sale
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            `;

            document.body.appendChild(modal);
            const form = document.getElementById('saleConfigForm');
            const saleTypeSelect = document.getElementById('saleType');
            const saleValueInput = document.getElementById('saleValue');
            const saleHelp = document.getElementById('saleHelp');
            const newPriceSpan = document.getElementById('newPrice');
            const originalPrice = parseFloat(item.price);

            function updateHelp() {
                const type = saleTypeSelect.value;
                switch (type) {
                    case 'percentage':
                        saleHelp.textContent = 'Enter percentage (e.g., 20 for 20% off)';
                        saleValueInput.max = '100';
                        break;
                    case 'fixed_discount':
                        saleHelp.textContent = 'Enter amount to discount (in денари)';
                        saleValueInput.max = originalPrice;
                        break;
                    case 'sale_price':
                        saleHelp.textContent = 'Enter new sale price (in денари)';
                        saleValueInput.max = originalPrice;
                        break;
                    default:
                        saleHelp.textContent = '';
                }
                calculateNewPrice();
            }

            function calculateNewPrice() {
                const type = saleTypeSelect.value;
                const value = parseFloat(saleValueInput.value) || 0;
                let newPrice = originalPrice;

                switch (type) {
                    case 'percentage':
                        newPrice = originalPrice - (originalPrice * value / 100);
                        break;
                    case 'fixed_discount':
                        newPrice = originalPrice - value;
                        break;
                    case 'sale_price':
                        newPrice = value;
                        break;
                }

                newPrice = Math.max(0, newPrice);
                newPriceSpan.textContent = newPrice.toFixed(2) + ' ден';
            }

            saleTypeSelect.addEventListener('change', updateHelp);
            saleValueInput.addEventListener('input', calculateNewPrice);

            form.addEventListener('submit', (e) => {
                e.preventDefault();
                const saleType = saleTypeSelect.value;
                const saleValue = parseFloat(saleValueInput.value);

                if (!saleType || !saleValue) {
                    alert('Please fill in all fields');
                    return;
                }

                modal.remove();
                resolve({ sale_type: saleType, sale_value: saleValue });
            });
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.remove();
                    resolve(null);
                }
            });
        });
    }

    async toggleCategoryVisibility(id, isVisible) {
        try {
            const response = await axios.put(`/api/admin/categories/${id}`, {
                is_visible: isVisible
            });
            
            if (response.data.success) {

                const category = this.categories.find(c => c.id === id);
                if (category) {
                    category.is_visible = isVisible;
                }
                

                this.render();
                

                await this.loadRestaurantData(this.currentRestaurantId);
                this.render();
            }
        } catch (error) {
            console.error('Error toggling category visibility:', error);
            alert('Error updating category visibility. Please try again.');
        }
    }

    async toggleCategoryTypeVisibility(id, isVisible) {
        try {
            const response = await axios.put(`/api/admin/category-types/${id}`, {
                is_visible: isVisible
            });
            
            if (response.data.success) {

                const categoryType = this.categoryTypes.find(ct => ct.id === id);
                if (categoryType) {
                    categoryType.is_visible = isVisible;
                }
                

                this.render();
                

                await this.loadRestaurantData(this.currentRestaurantId);
                this.render();
            }
        } catch (error) {
            console.error('Error toggling category type visibility:', error);
            alert('Error updating category type visibility. Please try again.');
        }
    }

    async toggleCategoryTypeSale(typeName, enableSale) {
        try {
            let saleData;
            
            if (enableSale) {

                const saleConfig = await this.showBulkSaleConfigModal('category type', typeName);
                if (!saleConfig) return; // User cancelled
                
                saleData = {
                    is_on_sale: true,
                    sale_type: saleConfig.sale_type,
                    sale_value: parseFloat(saleConfig.sale_value)
                };
            } else {
                if (!confirm(`Remove sale from all items in ${typeName} category type?`)) return;
                
                saleData = {
                    is_on_sale: false,
                    sale_type: null,
                    sale_value: null
                };
            }

            const response = await axios.post(`/api/admin/category-types/${this.currentRestaurantId}/${encodeURIComponent(typeName)}/sale`, saleData);
            
            if (response.data.success) {

                await this.loadRestaurantData(this.currentRestaurantId);
                this.render();
                
                const action = enableSale ? 'added' : 'removed';
                alert(`Sale ${action} successfully for all items in ${typeName} category type!`);
            }
        } catch (error) {
            console.error('Error toggling category type sale:', error);
            alert('Error updating category type sale. Please try again.');
        }
    }

    async toggleCategorySale(categoryId, enableSale) {
        try {
            const category = this.categories.find(c => c.id === categoryId);
            if (!category) {
                alert('Category not found.');
                return;
            }

            let saleData;
            
            if (enableSale) {

                const saleConfig = await this.showBulkSaleConfigModal('category', category.name);
                if (!saleConfig) return; // User cancelled
                
                saleData = {
                    is_on_sale: true,
                    sale_type: saleConfig.sale_type,
                    sale_value: parseFloat(saleConfig.sale_value)
                };
            } else {
                if (!confirm(`Remove sale from all items in "${category.name}" category?`)) return;
                
                saleData = {
                    is_on_sale: false,
                    sale_type: null,
                    sale_value: null
                };
            }

            const response = await axios.post(`/api/admin/categories/${categoryId}/sale`, saleData);
            
            if (response.data.success) {

                await this.loadRestaurantData(this.currentRestaurantId);
                this.render();
                
                const action = enableSale ? 'added' : 'removed';
                alert(`Sale ${action} successfully for all items in "${category.name}" category!`);
            }
        } catch (error) {
            console.error('Error toggling category sale:', error);
            alert('Error updating category sale. Please try again.');
        }
    }

    async showBulkSaleConfigModal(type, name) {
        return new Promise((resolve) => {
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50';
            modal.innerHTML = `
                <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                    <div class="mt-3">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Configure Sale for ${type}: "${name}"</h3>
                        <div class="mb-4 p-3 bg-orange-50 border border-orange-200 rounded-md">
                            <div class="flex items-start">
                                <i class="fas fa-exclamation-triangle text-orange-600 mt-0.5 mr-2"></i>
                                <div class="text-sm text-orange-700">
                                    This will apply the sale to <strong>all items</strong> in this ${type}. 
                                    Individual item prices will be automatically updated.
                                </div>
                            </div>
                        </div>
                        <form id="bulkSaleConfigForm">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Sale Type:</label>
                                <select id="bulkSaleType" class="w-full border border-gray-300 rounded-md px-3 py-2" required>
                                    <option value="">Select sale type</option>
                                    <option value="percentage">Percentage Discount</option>
                                    <option value="fixed_discount">Fixed Amount Discount</option>
                                </select>
                            </div>
                            
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Sale Value:</label>
                                <input type="number" id="bulkSaleValue" step="0.01" min="0" 
                                       class="w-full border border-gray-300 rounded-md px-3 py-2" 
                                       placeholder="Enter value" required>
                                <div id="bulkSaleHelp" class="text-sm text-gray-500 mt-1"></div>
                            </div>
                            
                            <div class="flex justify-end space-x-2">
                                <button type="button" onclick="this.closest('.fixed').remove(); resolve(null);" 
                                        class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">
                                    Cancel
                                </button>
                                <button type="submit" 
                                        class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700">
                                    Apply Sale to All Items
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            `;

            document.body.appendChild(modal);
            const form = document.getElementById('bulkSaleConfigForm');
            const saleTypeSelect = document.getElementById('bulkSaleType');
            const saleValueInput = document.getElementById('bulkSaleValue');
            const saleHelp = document.getElementById('bulkSaleHelp');

            function updateHelp() {
                const type = saleTypeSelect.value;
                switch (type) {
                    case 'percentage':
                        saleHelp.textContent = 'Enter percentage (e.g., 20 for 20% off all items)';
                        saleValueInput.max = '100';
                        break;
                    case 'fixed_discount':
                        saleHelp.textContent = 'Enter amount to discount from each item (in денари)';
                        saleValueInput.removeAttribute('max');
                        break;
                    default:
                        saleHelp.textContent = '';
                }
            }

            saleTypeSelect.addEventListener('change', updateHelp);

            form.addEventListener('submit', (e) => {
                e.preventDefault();
                const saleType = saleTypeSelect.value;
                const saleValue = parseFloat(saleValueInput.value);

                if (!saleType || !saleValue) {
                    alert('Please fill in all fields');
                    return;
                }

                modal.remove();
                resolve({ sale_type: saleType, sale_value: saleValue });
            });
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.remove();
                    resolve(null);
                }
            });
        });
    }

    async resetPassword(userId) {
        const user = this.users.find(u => u.id === userId);
        if (!user) return;

        const confirmReset = confirm(`Reset password for ${user.name}?\n\nThe password will be set to their email address (${user.email}) and they will be required to change it on first login.`);
        if (!confirmReset) return;

        try {
            const response = await axios.post('/api/auth/reset-password', {
                userId: userId
            });

            if (response.data.success) {
                alert(response.data.message);
            }
        } catch (error) {
            console.error('Error resetting password:', error);
            alert('Error resetting password. Please try again.');
        }
    }
    handleExcelFileChange(event) {
        const file = event.target.files[0];
        if (file) {

            if (!file.name.endsWith('.xlsx')) {
                alert('Please select an Excel file (.xlsx)');
                event.target.value = '';
                return;
            }
            

            console.log('Excel file selected:', file.name, 'Size:', file.size, 'bytes');
        }
    }
    async handleCSVUpload(event) {
        const file = event.target.files[0];
        if (!file) return;

        const uploadType = document.getElementById('csvUploadType').value;
        if (!uploadType) {
            alert('Please select a data type first.');
            return;
        }
        if (this.user.role === 'super_admin') {
            const restaurantId = document.getElementById('csvUploadRestaurant').value;
            if (!restaurantId) {
                alert('Please select a restaurant first.');
                return;
            }
        }

        const restaurantId = this.user.role === 'super_admin' 
            ? document.getElementById('csvUploadRestaurant').value
            : this.currentRestaurantId;

        if (!restaurantId) {
            alert('No restaurant selected.');
            return;
        }

        const formData = new FormData();
        formData.append('csvFile', file);
        formData.append('dataType', uploadType);
        formData.append('restaurantId', restaurantId);

        try {
            const response = await axios.post('/api/admin/upload-csv', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });

            if (response.data.success) {
                alert(`Successfully uploaded ${response.data.processedCount} ${uploadType.replace('_', ' ')}`);

                await this.loadData();
                this.render();
            }
        } catch (error) {
            console.error('Error uploading CSV:', error);
            alert('Error uploading CSV file: ' + (error.response?.data?.message || 'Please try again.'));
        }
        event.target.value = '';
    }

    async downloadTemplate(templateType) {
        try {
            const response = await axios.get(`/api/admin/download-template/${templateType}`, {
                responseType: 'blob'
            });
            
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `${templateType}_template.csv`);
            document.body.appendChild(link);
            link.click();
            link.remove();
        } catch (error) {
            console.error('Error downloading template:', error);
            alert('Error downloading template. Please try again.');
        }
    }
    async downloadExcelTemplate() {
        try {
            const response = await axios.get('/api/admin/download-excel-template', {
                responseType: 'blob'
            });
            
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'restaurant_data_template.xlsx');
            document.body.appendChild(link);
            link.click();
            link.remove();
            
            this.showToast('Excel template downloaded successfully', 'success');
        } catch (error) {
            console.error('Error downloading Excel template:', error);
            this.showToast('Error downloading template. Please try again.', 'error');
        }
    }
    async downloadUnifiedTemplate() {
        try {
            const response = await axios.get('/api/admin/download-template', {
                responseType: 'blob'
            });
            
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'restaurant_bulk_data_template.csv');
            document.body.appendChild(link);
            link.click();
            link.remove();
            
            this.showToast('Template downloaded successfully', 'success');
        } catch (error) {
            console.error('Error downloading unified template:', error);
            this.showToast('Error downloading template. Please try again.', 'error');
        }
    }

    showPasswordChangeModal() {
        const modal = document.createElement('div');
        modal.id = 'passwordChangeModal';
        modal.className = 'fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50';
        modal.innerHTML = `
            <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                <div class="mt-3 text-center">
                    <h3 class="text-lg font-medium text-gray-900">Change Password Required</h3>
                    <div class="mt-2 px-7 py-3">
                        <p class="text-sm text-gray-500">You must change your password before continuing.</p>
                    </div>
                    <form id="changePasswordForm" class="mt-4 space-y-4">
                        ${!this.user.must_change_password ? `
                            <div>
                                <input type="password" id="currentPassword" placeholder="Current Password" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" 
                                       required>
                            </div>
                        ` : ''}
                        <div>
                            <input type="password" id="newPassword" placeholder="New Password" 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" 
                                   required minlength="6">
                        </div>
                        <div>
                            <input type="password" id="confirmNewPassword" placeholder="Confirm New Password" 
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" 
                                   required minlength="6">
                        </div>
                    </form>
                    <div class="items-center px-4 py-3">
                        <button id="changePasswordBtn" 
                                class="px-4 py-2 bg-blue-600 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-300">
                            Change Password
                        </button>
                    </div>
                    <div id="passwordChangeMessage" class="mt-2 hidden"></div>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
        

        document.getElementById('changePasswordBtn').addEventListener('click', async () => {
            const submitButton = document.getElementById('changePasswordBtn');
            if (!this.preventDoubleSubmission('changePasswordForm', submitButton)) {
                return; // Prevent duplicate submission
            }
            
            try {
                await this.handlePasswordChange();
            } finally {
                this.restoreSubmissionState('changePasswordForm', submitButton);
            }
        });
        document.getElementById('newPassword').focus();
    }

    async handlePasswordChange() {
        const currentPassword = document.getElementById('currentPassword')?.value || '';
        const newPassword = document.getElementById('newPassword').value;
        const confirmNewPassword = document.getElementById('confirmNewPassword').value;
        const messageDiv = document.getElementById('passwordChangeMessage');
        const changeBtn = document.getElementById('changePasswordBtn');
        

        if (newPassword !== confirmNewPassword) {
            this.showPasswordChangeMessage('Passwords do not match', 'error');
            return;
        }
        
        if (newPassword.length < 6) {
            this.showPasswordChangeMessage('Password must be at least 6 characters', 'error');
            return;
        }
        const originalText = changeBtn.innerHTML;
        changeBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Changing...';
        changeBtn.disabled = true;

        try {
            const response = await axios.post('/api/auth/change-password', {
                currentPassword: currentPassword,
                newPassword: newPassword
            });

            if (response.data.success) {
                this.showPasswordChangeMessage('Password changed successfully!', 'success');
                

                this.user.must_change_password = false;
                localStorage.setItem('user', JSON.stringify(this.user));
                
                setTimeout(() => {
                    document.getElementById('passwordChangeModal').remove();

                    const url = new URL(window.location);
                    url.searchParams.delete('changePassword');
                    window.history.replaceState({}, document.title, url);
                }, 2000);
            } else {
                this.showPasswordChangeMessage(response.data.message || 'Password change failed', 'error');
            }
        } catch (error) {
            console.error('Password change error:', error);
            this.showPasswordChangeMessage(error.response?.data?.message || 'Password change failed. Please try again.', 'error');
        } finally {

            changeBtn.innerHTML = originalText;
            changeBtn.disabled = false;
        }
    }

    showPasswordChangeMessage(message, type) {
        const messageDiv = document.getElementById('passwordChangeMessage');
        messageDiv.className = `mt-2 p-3 rounded text-sm ${
            type === 'success' 
                ? 'bg-green-100 border border-green-400 text-green-700' 
                : 'bg-red-100 border border-red-400 text-red-700'
        }`;
        messageDiv.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} mr-2"></i>
            ${message}
        `;
        messageDiv.classList.remove('hidden');
    }

    setupCSVUploadEvents() {
        const form = document.getElementById('excelUploadForm');
        if (form) {
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleExcelUpload(e.target);
            });
        }
    }
    isMobileDevice() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) 
               || window.innerWidth <= 768;
    }

    async handleExcelUpload(form) {
        const restaurantId = this.user.role === 'super_admin' 
            ? document.getElementById('csvUploadRestaurant')?.value 
            : this.currentRestaurantId;

        if (this.user.role === 'super_admin' && !restaurantId) {
            alert('Please select a restaurant first.');
            return;
        }
        const excelFile = form.excelFile.files[0];
        if (!excelFile) {
            alert('Please select an Excel file to upload.');
            return;
        }

        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        
        try {
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing Excel...';
            submitBtn.disabled = true;

            const formData = new FormData();
            formData.append('excelFile', excelFile);
            formData.append('dataType', 'excel');
            formData.append('restaurantId', restaurantId);

            const response = await axios.post('/api/admin/upload-excel', formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });

            if (response.data.success) {
                let message = `Successfully processed ${response.data.processedCount} items.`;
                
                if (response.data.details && response.data.details.errors && response.data.details.errors.length > 0) {
                    const errorCount = response.data.details.errors.length;
                    message += `\n\nNote: ${errorCount} error${errorCount > 1 ? 's' : ''} encountered:`;
                    message += '\n' + response.data.details.errors.slice(0, 5).join('\n');
                    if (errorCount > 5) {
                        message += `\n... and ${errorCount - 5} more errors`;
                    }
                }
                
                alert(message);
                

                await this.loadRestaurantData(restaurantId);
                this.render();
                form.reset();
            } else {
                alert('Upload failed: ' + response.data.message);
            }

        } catch (error) {
            console.error('Error uploading Excel:', error);
            alert('Upload failed: ' + (error.response?.data?.message || 'Please try again.'));
        } finally {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    }

    async uploadSingleCSV(file, type, restaurantId) {
        try {
            const formData = new FormData();
            formData.append('csvFile', file);
            formData.append('restaurantId', restaurantId);

            const response = await axios.post(`/api/admin/upload-csv/${type}`, formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });

            return {
                success: response.data.success,
                message: response.data.message,
                processed: response.data.processed || 0,
                errors: response.data.errors || []
            };
        } catch (error) {
            return {
                success: false,
                message: error.response?.data?.message || 'Upload failed',
                errors: error.response?.data?.errors || []
            };
        }
    }

    showUploadResults(results) {
        const successCount = results.filter(r => r.success).length;
        const totalCount = results.length;
        
        let content = `
            <div class="space-y-4">
                <div class="text-center">
                    <h3 class="text-lg font-semibold mb-2">Upload Results</h3>
                    <p class="text-gray-600">${successCount} of ${totalCount} files uploaded successfully</p>
                </div>
        `;

        results.forEach(result => {
            const statusIcon = result.success ? 'check-circle text-green-600' : 'times-circle text-red-600';
            const statusBg = result.success ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200';
            
            content += `
                <div class="p-4 border rounded-lg ${statusBg}">
                    <div class="flex items-start">
                        <i class="fas fa-${statusIcon} mt-1 mr-3"></i>
                        <div class="flex-1">
                            <h4 class="font-medium">${result.type}</h4>
                            <p class="text-sm text-gray-600 mt-1">${result.message}</p>
                            ${result.processed ? `<p class="text-xs text-gray-500 mt-1">Processed: ${result.processed} records</p>` : ''}
                            ${result.errors && result.errors.length > 0 ? `
                                <div class="mt-2">
                                    <p class="text-xs font-medium text-red-700">Errors:</p>
                                    <ul class="text-xs text-red-600 list-disc list-inside mt-1">
                                        ${result.errors.slice(0, 5).map(error => `<li>${error}</li>`).join('')}
                                        ${result.errors.length > 5 ? `<li>... and ${result.errors.length - 5} more errors</li>` : ''}
                                    </ul>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                </div>
            `;
        });

        content += '</div>';
        this.showModal('Upload Results', content);
    }

    showUploadError(message) {
        const content = `
            <div class="text-center p-6">
                <i class="fas fa-exclamation-triangle text-red-600 text-4xl mb-4"></i>
                <h3 class="text-lg font-semibold text-red-800 mb-2">Upload Error</h3>
                <p class="text-red-700">${message}</p>
            </div>
        `;
        this.showModal('Error', content);
    }
    async moveMenuItem(itemId, direction) {
        const item = this.menuItems.find(item => item.id === itemId);
        if (!item) return;

        const categoryItems = this.menuItems
            .filter(mi => mi.category_id === item.category_id)
            .sort((a, b) => a.display_order - b.display_order);

        const currentIndex = categoryItems.findIndex(mi => mi.id === itemId);
        if (currentIndex === -1) return;

        let targetIndex;
        if (direction === 'up') {
            targetIndex = Math.max(0, currentIndex - 1);
        } else {
            targetIndex = Math.min(categoryItems.length - 1, currentIndex + 1);
        }
        if (currentIndex === targetIndex) return;

        const targetItem = categoryItems[targetIndex];
        await this.reorderMenuItems(itemId, targetItem.id);
    }
    async moveCategoryType(typeId, direction) {
        const sortedTypes = [...this.categoryTypes].sort((a, b) => a.display_order - b.display_order);
        const currentIndex = sortedTypes.findIndex(t => t.id === typeId);
        if (currentIndex === -1) return;

        let targetIndex;
        if (direction === 'up') {
            targetIndex = Math.max(0, currentIndex - 1);
        } else {
            targetIndex = Math.min(sortedTypes.length - 1, currentIndex + 1);
        }
        if (currentIndex === targetIndex) return;

        const targetType = sortedTypes[targetIndex];
        await this.reorderCategoryTypes(typeId, targetType.id);
    }
    async moveCategory(categoryId, typeName, direction) {
        const categoriesOfType = this.categories
            .filter(c => c.type === typeName)
            .sort((a, b) => a.display_order - b.display_order);

        const currentIndex = categoriesOfType.findIndex(c => c.id === categoryId);
        if (currentIndex === -1) return;

        let targetIndex;
        if (direction === 'up') {
            targetIndex = Math.max(0, currentIndex - 1);
        } else {
            targetIndex = Math.min(categoriesOfType.length - 1, currentIndex + 1);
        }
        if (currentIndex === targetIndex) return;

        const targetCategory = categoriesOfType[targetIndex];
        await this.reorderCategories(categoryId, targetCategory.id, typeName);
    }

    updateCategoriesForType(typeName) {
        const categorySelect = document.getElementById('category-select');
        if (!categorySelect) return;
        

        categorySelect.innerHTML = '<option value="">Select Category</option>';
        
        if (!typeName) {
            categorySelect.innerHTML = '<option value="">First select a type</option>';
            return;
        }
        

        const categoriesOfType = this.categories.filter(c => 
            c.restaurant_id === this.currentRestaurantId && c.type === typeName
        );
        
        if (categoriesOfType.length === 0) {
            categorySelect.innerHTML = '<option value="">No categories available for this type</option>';
            return;
        }
        

        categoriesOfType.forEach(category => {
            const option = document.createElement('option');
            option.value = category.id;
            option.textContent = category.name;
            categorySelect.appendChild(option);
        });
    }
    toggleSaleFields() {
        const saleCheckbox = document.getElementById('is_on_sale');
        const saleFields = document.getElementById('sale-fields');
        
        if (saleCheckbox && saleFields) {
            if (saleCheckbox.checked) {
                saleFields.classList.remove('hidden');
            } else {
                saleFields.classList.add('hidden');

                const saleType = document.getElementById('sale_type');
                const saleValue = document.getElementById('sale_value');
                if (saleType) saleType.value = '';
                if (saleValue) saleValue.value = '';
                this.handleSaleTypeChange();
            }
        }
    }

    handleSaleTypeChange() {
        const saleType = document.getElementById('sale_type');
        const saleValueLabel = document.getElementById('sale_value_label');
        const saleValue = document.getElementById('sale_value');
        const saleHelpText = document.getElementById('sale_help_text');
        
        if (!saleType || !saleValueLabel || !saleValue || !saleHelpText) return;
        
        const type = saleType.value;
        
        if (type === 'percentage') {
            saleValueLabel.textContent = 'Discount Percentage (%)';
            saleValue.placeholder = 'e.g., 15 (for 15% off)';
            saleValue.max = '100';
            saleHelpText.textContent = 'Enter percentage (1-100)';
        } else if (type === 'fixed_discount') {
            saleValueLabel.textContent = 'Discount Amount (ден)';
            saleValue.placeholder = 'e.g., 50 (50 denars off)';
            saleValue.removeAttribute('max');
            saleHelpText.textContent = 'Enter fixed discount amount';
        } else if (type === 'sale_price') {
            saleValueLabel.textContent = 'Sale Price (ден)';
            saleValue.placeholder = 'e.g., 199.99';
            saleValue.removeAttribute('max');
            saleHelpText.textContent = 'Enter the new sale price';
        } else {
            saleValueLabel.textContent = 'Sale Value';
            saleValue.placeholder = 'Enter value';
            saleValue.removeAttribute('max');
            saleHelpText.textContent = 'Select a sale type first';
        }
    }
    toggleCategorySaleFields() {
        const saleCheckbox = document.getElementById('category_is_on_sale');
        const saleFields = document.getElementById('category-sale-fields');
        
        if (saleCheckbox && saleFields) {
            if (saleCheckbox.checked) {
                saleFields.classList.remove('hidden');
            } else {
                saleFields.classList.add('hidden');

                const saleType = document.getElementById('category_sale_type');
                const saleValue = document.getElementById('category_sale_value');
                if (saleType) saleType.value = '';
                if (saleValue) saleValue.value = '';
                this.handleCategorySaleTypeChange();
            }
        }
    }

    handleCategorySaleTypeChange() {
        const saleType = document.getElementById('category_sale_type');
        const saleValueLabel = document.getElementById('category_sale_value_label');
        const saleValue = document.getElementById('category_sale_value');
        const saleHelpText = document.getElementById('category_sale_help_text');
        
        if (!saleType || !saleValueLabel || !saleValue || !saleHelpText) return;
        
        const type = saleType.value;
        
        if (type === 'percentage') {
            saleValueLabel.textContent = 'Discount Percentage (%)';
            saleValue.placeholder = 'e.g., 15 (for 15% off)';
            saleValue.max = '100';
            saleHelpText.textContent = 'Enter percentage (1-100)';
        } else if (type === 'fixed_discount') {
            saleValueLabel.textContent = 'Discount Amount (ден)';
            saleValue.placeholder = 'e.g., 50 (50 denars off)';
            saleValue.removeAttribute('max');
            saleHelpText.textContent = 'Enter fixed discount amount';
        } else {
            saleValueLabel.textContent = 'Sale Value';
            saleValue.placeholder = 'Enter value';
            saleValue.removeAttribute('max');
            saleHelpText.textContent = 'Select a sale type first';
        }
    }
    
    async loadQRCode() {
        try {
            const restaurantId = this.user.role === 'super_admin' ? this.currentRestaurantId : this.user.restaurant_id;
            if (!restaurantId) return;

            const response = await axios.get(`/api/admin/qrcode/${restaurantId}`);
            if (response.data.success) {
                const qrData = response.data.data;
                this.displayQRCode(qrData.qr_code_url);
            }
        } catch (error) {
            console.error('Error loading QR code:', error);
        }
    }

    displayQRCode(qrUrl) {
        const container = document.getElementById('qr-image-container');
        if (container && qrUrl) {

            container.innerHTML = `
                <div class="flex flex-col items-center justify-center space-y-2">
                    <i class="fas fa-spinner fa-spin text-4xl text-blue-600"></i>
                    <p class="text-sm text-gray-600">Loading QR code...</p>
                </div>
            `;
            

            const img = new Image();
            img.onload = () => {
                container.innerHTML = `<img src="${qrUrl}?t=${Date.now()}" alt="QR Code" class="w-64 h-64 object-contain">`;
            };
            img.onerror = () => {

                console.warn('QR code failed to load, attempting regeneration...');
                this.regenerateQRCodeSilently();
            };
            img.src = qrUrl + '?t=' + Date.now();
        }
    }

    async regenerateQRCodeSilently() {
        try {
            const restaurantId = this.user.role === 'super_admin' ? this.currentRestaurantId : this.user.restaurant_id;
            if (!restaurantId) return;

            const response = await axios.post(`/api/admin/qrcode/regenerate/${restaurantId}`, {
                options: {}
            });
            
            if (response.data.success) {

                setTimeout(() => {
                    this.displayQRCode(response.data.data.qr_code_url);
                }, 500);
            } else {

                const container = document.getElementById('qr-image-container');
                if (container) {
                    container.innerHTML = `
                        <div class="flex flex-col items-center justify-center space-y-2 text-center">
                            <i class="fas fa-exclamation-triangle text-4xl text-orange-500"></i>
                            <p class="text-sm text-gray-600">Unable to load QR code</p>
                            <button onclick="dashboard.regenerateQRCode()" class="text-xs bg-blue-600 text-white px-2 py-1 rounded hover:bg-blue-700">
                                Try Again
                            </button>
                        </div>
                    `;
                }
            }
        } catch (error) {
            console.error('Silent QR regeneration failed:', error);
            const container = document.getElementById('qr-image-container');
            if (container) {
                container.innerHTML = `
                    <div class="flex flex-col items-center justify-center space-y-2 text-center">
                        <i class="fas fa-exclamation-triangle text-4xl text-orange-500"></i>
                        <p class="text-sm text-gray-600">Unable to load QR code</p>
                        <button onclick="dashboard.regenerateQRCode()" class="text-xs bg-blue-600 text-white px-2 py-1 rounded hover:bg-blue-700">
                            Try Again
                        </button>
                    </div>
                `;
            }
        }
    }

    async previewQRCode() {
        try {
            const options = this.getQRCodeOptions();
            const restaurantId = this.user.role === 'super_admin' ? this.currentRestaurantId : this.user.restaurant_id;
            
            if (!restaurantId) {
                this.showToast('Please select a restaurant first', 'error');
                return;
            }
            
            this.showLoadingState('Generating preview...');
            

            if (!window.QRCode) {
                const script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js';
                document.head.appendChild(script);
                await new Promise((resolve, reject) => {
                    script.onload = () => {
                        console.log('QR Code library loaded successfully');
                        resolve();
                    };
                    script.onerror = (error) => {
                        console.error('Failed to load QR Code library:', error);
                        reject(new Error('Failed to load QR Code library'));
                    };
                    setTimeout(() => {
                        console.error('QR Code library load timeout');
                        reject(new Error('QR library load timeout - please check your internet connection'));
                    }, 15000); // Increased timeout to 15 seconds
                });
            }
            
            const currentRestaurant = this.user.role === 'super_admin' 
                ? this.restaurants.find(r => r.id === this.currentRestaurantId)
                : this.restaurants.find(r => r.id === this.user.restaurant_id);
            
            if (currentRestaurant) {
                const qrUrl = `${window.location.origin}/menu/${currentRestaurant.slug}`;
                

                const qrOptions = {
                    width: Math.min(parseInt(options.width) || 512, 512),
                    margin: parseInt(options.margin) || 1,
                    errorCorrectionLevel: options.errorCorrectionLevel || 'M',
                    color: {
                        dark: options.qrOptions?.color?.dark || '#000000',
                        light: options.qrOptions?.color?.light || '#FFFFFF'
                    }
                };
                

                
                const canvas = document.createElement('canvas');
                await QRCode.toCanvas(canvas, qrUrl, qrOptions);
                
                const container = document.getElementById('qr-image-container');
                if (container) {
                    container.innerHTML = '';
                    

                    const wrapper = document.createElement('div');
                    wrapper.className = 'inline-block';
                    wrapper.appendChild(canvas);
                    container.appendChild(wrapper);
                    

                    canvas.style.width = '100%';
                    canvas.style.height = 'auto';
                    canvas.style.maxWidth = '256px';
                    canvas.style.maxHeight = '256px';
                }
                
                this.showToast('Preview updated successfully', 'success');
            } else {
                throw new Error('Restaurant not found');
            }
            
            this.hideLoadingState();
        } catch (error) {
            console.error('Error previewing QR code:', error);
            this.hideLoadingState();
            this.showToast('Error generating preview: ' + error.message, 'error');
        }
    }

    async regenerateQRCode() {
        try {
            const options = this.getQRCodeOptions();
            const restaurantId = this.user.role === 'super_admin' ? this.currentRestaurantId : this.user.restaurant_id;
            
            if (!restaurantId) {
                this.showToast('No restaurant selected', 'error');
                return;
            }

            this.showLoadingState('Regenerating QR code...');
            
            const response = await axios.post(`/api/admin/qrcode/regenerate/${restaurantId}`, {
                options: options
            });
            
            if (response.data.success) {
                this.displayQRCode(response.data.data.qr_code_url);
                this.showToast('QR code regenerated successfully', 'success');
                

                const restaurant = this.restaurants.find(r => r.id === restaurantId);
                if (restaurant) {
                    restaurant.qr_code_url = response.data.data.qr_code_url;
                }
            } else {
                this.showToast(response.data.message || 'Failed to regenerate QR code', 'error');
            }
            
            this.hideLoadingState();
        } catch (error) {
            console.error('Error regenerating QR code:', error);
            this.hideLoadingState();
            this.showToast('Failed to regenerate QR code', 'error');
        }
    }

    async downloadQRCode(format = 'png', resolution = 512) {
        try {
            const restaurantId = this.user.role === 'super_admin' ? this.currentRestaurantId : this.user.restaurant_id;
            
            if (!restaurantId) {
                this.showToast('No restaurant selected', 'error');
                return;
            }

            const currentRestaurant = this.user.role === 'super_admin' 
                ? this.restaurants.find(r => r.id === this.currentRestaurantId)
                : this.restaurants.find(r => r.id === this.user.restaurant_id);

            if (!currentRestaurant) {
                this.showToast('Restaurant not found', 'error');
                return;
            }
            const options = this.getQRCodeOptions();
            options.width = resolution;
            options.height = resolution;
            
            this.showLoadingState(`Generating ${resolution}x${resolution} PNG QR code...`);
            
            try {
                const response = await axios.post(`/api/admin/qrcode/regenerate/${restaurantId}`, {
                    options: options
                });
                
                if (!response.data.success) {
                    this.showToast('Failed to generate QR code', 'error');
                    this.hideLoadingState();
                    return;
                }
                
                this.hideLoadingState();
            } catch (regenerateError) {
                console.error('Error regenerating QR code:', regenerateError);
                this.showToast('Failed to generate QR code', 'error');
                this.hideLoadingState();
                return;
            }
            const downloadUrl = `/api/admin/qrcode/download/${restaurantId}?format=png&t=${Date.now()}`;
            const filename = `${currentRestaurant.slug}-qrcode-${resolution}px.png`;

            try {

                const response = await fetch(downloadUrl, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${this.token}`
                    }
                });

                if (!response.ok) {
                    throw new Error(`Download failed: ${response.status} ${response.statusText}`);
                }
                const blob = await response.blob();
                const blobUrl = window.URL.createObjectURL(blob);
                
                const link = document.createElement('a');
                link.href = blobUrl;
                link.download = filename;
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                

                window.URL.revokeObjectURL(blobUrl);
                
                this.showToast(`PNG download completed (${resolution}x${resolution})`, 'success');
            } catch (downloadError) {
                console.error('Error downloading QR code:', downloadError);
                this.showToast('Download failed: ' + downloadError.message, 'error');
            }
            
        } catch (error) {
            console.error('Error downloading QR code:', error);
            this.hideLoadingState();
            this.showToast('Failed to download QR code', 'error');
        }
    }

    getQRCodeOptions() {
        const size = document.getElementById('qr-size')?.value || '512';
        const errorCorrection = document.getElementById('qr-error-correction')?.value || 'M';
        const margin = document.getElementById('qr-margin')?.value || '1';
        const colorMode = document.getElementById('qr-color-mode')?.value || 'solid';
        const includeLogo = document.getElementById('qr-include-logo')?.checked || false;
        

        const darkColor = document.getElementById('qr-color-dark')?.value || '#000000';
        const lightColor = document.getElementById('qr-color-light')?.value || '#FFFFFF';
        let colorOptions = {
            dark: darkColor,
            light: lightColor
        };
        

        const dotStyle = this.currentDotStyle || 'square';
        const cornerStyle = this.currentCornerStyle || 'square';
        

        const logoSize = document.getElementById('qr-logo-size')?.value || '20';
        const logoBackground = document.getElementById('qr-logo-background')?.checked || false;
        const logoBgColor = document.getElementById('qr-logo-bg-color')?.value || '#ffffff';
        const logoBorderRadius = document.getElementById('qr-logo-border-radius')?.value || '8';
        
        return {
            width: parseInt(size),
            height: parseInt(size),
            margin: parseInt(margin),
            errorCorrectionLevel: errorCorrection,
            includeLogo: includeLogo,
            qrOptions: {
                color: colorOptions,
                dotStyle: dotStyle,
                cornerStyle: cornerStyle,
                logo: includeLogo ? {
                    size: parseInt(logoSize),
                    background: logoBackground,
                    backgroundColor: logoBgColor,
                    borderRadius: parseInt(logoBorderRadius)
                } : null
            }
        };
    }

    switchQRTab(tabName) {

        document.querySelectorAll('[id^="tab-"]').forEach(tab => {
            tab.className = tab.className.replace('border-blue-600 text-blue-600', 'border-transparent text-gray-500 hover:text-gray-700');
        });
        document.getElementById(`tab-${tabName}`).className = document.getElementById(`tab-${tabName}`).className.replace('border-transparent text-gray-500 hover:text-gray-700', 'border-blue-600 text-blue-600');
        

        document.querySelectorAll('[id^="qr-tab-"]').forEach(content => {
            content.classList.add('hidden');
        });
        document.getElementById(`qr-tab-${tabName}`).classList.remove('hidden');
    }

    setDotStyle(style) {
        this.currentDotStyle = style;
        

        document.querySelectorAll('[id^="dot-"]').forEach(btn => {
            btn.className = btn.className
                .replace('border-blue-600', 'border-gray-300')
                .replace('bg-blue-50', '');
            if (!btn.className.includes('hover:border-blue-600')) {
                btn.className += ' hover:border-blue-600';
            }
        });
        

        const selectedBtn = document.getElementById(`dot-${style}`);
        if (selectedBtn) {
            selectedBtn.className = selectedBtn.className
                .replace('border-gray-300', 'border-blue-600')
                .replace('hover:border-blue-600', '') + ' bg-blue-50';
        }
        
        this.showToast(`Dot style set to ${style}`, 'success');
    }

    setCornerStyle(style) {
        this.currentCornerStyle = style;
        

        document.querySelectorAll('[id^="corner-"]').forEach(btn => {
            btn.className = btn.className
                .replace('border-blue-600', 'border-gray-300')
                .replace('bg-blue-50', '');
            if (!btn.className.includes('hover:border-blue-600')) {
                btn.className += ' hover:border-blue-600';
            }
        });
        

        const selectedBtn = document.getElementById(`corner-${style}`);
        if (selectedBtn) {
            selectedBtn.className = selectedBtn.className
                .replace('border-gray-300', 'border-blue-600')
                .replace('hover:border-blue-600', '') + ' bg-blue-50';
        }
        
        this.showToast(`Corner style set to ${style}`, 'success');
    }

    applyColorPreset(darkColor, lightColor) {
        document.getElementById('qr-color-dark').value = darkColor;
        document.getElementById('qr-color-dark-text').value = darkColor;
        document.getElementById('qr-color-light').value = lightColor;
        document.getElementById('qr-color-light-text').value = lightColor;
        

        document.getElementById('qr-color-mode').value = 'solid';
    }

    showLoadingState(message) {
        const container = document.getElementById('qr-image-container');
        if (container) {
            container.innerHTML = `
                <div class="flex flex-col items-center justify-center space-y-2">
                    <i class="fas fa-spinner fa-spin text-4xl text-blue-600"></i>
                    <p class="text-sm text-gray-600">${message}</p>
                </div>
            `;
        }
    }

    hideLoadingState() {

        const container = document.getElementById('qr-image-container');
        if (container && container.innerHTML.includes('fa-spinner')) {
            container.innerHTML = `
                <div class="flex flex-col items-center justify-center space-y-2">
                    <i class="fas fa-qrcode text-4xl text-gray-400"></i>
                    <p class="text-sm text-gray-600">Ready for preview</p>
                </div>
            `;
        }
    }
    async exportCSV() {
        try {
            const restaurantId = this.user.role === 'super_admin' 
                ? document.getElementById('export-restaurant-select')?.value || this.currentRestaurantId
                : this.user.restaurant_id;
            
            if (!restaurantId) {
                this.showToast('Please select a restaurant to export', 'error');
                return;
            }

            const response = await axios.get(`/api/admin/export/csv/${restaurantId}`, {
                responseType: 'blob'
            });
            

            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            

            const contentDisposition = response.headers['content-disposition'];
            let filename = 'restaurant-data.xlsx';
            if (contentDisposition) {
                const filenameMatch = contentDisposition.match(/filename="(.+)"/);
                if (filenameMatch) {
                    filename = filenameMatch[1];
                }
            }
            
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            
            this.showToast('XLSX export started', 'success');
        } catch (error) {
            console.error('Error exporting CSV:', error);
            this.showToast('Failed to export CSV', 'error');
        }
    }

    async loadRestaurantsForExport() {
        if (this.user.role === 'super_admin') {
            try {
                const response = await axios.get('/api/admin/restaurants-for-export');
                if (response.data.success) {
                    return response.data.restaurants;
                }
            } catch (error) {
                console.error('Error loading restaurants for export:', error);
            }
        }
        return [];
    }
    
    
    
    
    
    

    showConfirmDialog(title, message, confirmText = 'Confirm', cancelText = 'Cancel', type = 'warning') {
        return new Promise((resolve) => {
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
            
            const typeColors = {
                danger: 'bg-red-600 hover:bg-red-700',
                warning: 'bg-yellow-600 hover:bg-yellow-700',
                info: 'bg-blue-600 hover:bg-blue-700'
            };
            
            modal.innerHTML = `
                <div class="bg-white rounded-2xl shadow-2xl max-w-lg mx-4 overflow-hidden">
                    <div class="p-6">
                        <div class="flex items-start mb-4">
                            <div class="flex-shrink-0 w-12 h-12 flex items-center justify-center rounded-full ${type === 'danger' ? 'bg-red-100' : 'bg-yellow-100'} mr-4">
                                <i class="fas ${type === 'danger' ? 'fa-exclamation-triangle text-red-600' : 'fa-question-circle text-yellow-600'} text-xl"></i>
                            </div>
                            <div class="flex-1">
                                <h3 class="text-xl font-bold text-gray-900 mb-2">${title}</h3>
                                <p class="text-gray-600 text-sm leading-relaxed">${message}</p>
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-6 py-4 flex flex-col sm:flex-row-reverse gap-3">
                        <button type="button" class="confirm-btn flex-1 sm:flex-none px-6 py-3 text-sm font-semibold text-white ${typeColors[type] || typeColors.warning} rounded-lg hover:shadow-lg transition-all duration-200 transform hover:scale-105">
                            <i class="fas ${type === 'danger' ? 'fa-trash' : 'fa-check'} mr-2"></i>${confirmText}
                        </button>
                        <button type="button" class="cancel-btn flex-1 sm:flex-none px-6 py-3 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 hover:shadow-md transition-all duration-200">
                            <i class="fas fa-times mr-2"></i>${cancelText}
                        </button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            const confirmBtn = modal.querySelector('.confirm-btn');
            const cancelBtn = modal.querySelector('.cancel-btn');
            
            confirmBtn.addEventListener('click', () => {
                modal.remove();
                resolve(true);
            });
            
            cancelBtn.addEventListener('click', () => {
                modal.remove();
                resolve(false);
            });
            

            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.remove();
                    resolve(false);
                }
            });
        });
    }
    
    showAddPromotionForm() {
        const availableMenuItems = this.menuItems.filter(item => 
            item.restaurant_id === this.currentRestaurantId && item.is_active
        );
        
        const content = `
            <form id="promotionForm">
                <div class="grid grid-cols-1 gap-6">
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Promotion Names</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Promotion Name (MK)*</label>
                                <input type="text" name="name_mk" required 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                       placeholder="Внесете име на промоција">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Promotion Name (EN)*</label>
                                <input type="text" name="name_en" required 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                       placeholder="Enter promotion name">
                            </div>
                            <div id="promotionAlbanianNameField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Promotion Name (AL)</label>
                                <input type="text" name="name_al" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                       placeholder="Vendos emrin e promovimit">
                            </div>
                        </div>
                        <input type="hidden" name="name" id="hiddenPromotionName">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Price*</label>
                        <input type="number" name="price" step="0.01" min="0" required 
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                               placeholder="Enter promotion price">
                    </div>
                    
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Promotion Description</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Description (Macedonian)</label>
                                <textarea name="description_mk" rows="3" 
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                          placeholder="Внесете опис (опционално)"></textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Description (English)</label>
                                <textarea name="description_en" rows="3" 
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                          placeholder="Enter description (optional)"></textarea>
                            </div>
                            <div id="promotionAlbanianDescField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Description (Albanian)</label>
                                <textarea name="description_al" rows="3" 
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                          placeholder="Vendos përshkrimin (opsionale)"></textarea>
                            </div>
                        </div>
                        <input type="hidden" name="description" id="hiddenPromotionDescription">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Select Menu Items & Quantities</label>
                        <div class="border border-gray-300 rounded-lg max-h-64 overflow-y-auto p-4">
                            ${availableMenuItems.length === 0 ? `
                                <p class="text-gray-500 text-sm">No menu items available. Please create menu items first.</p>
                            ` : `
                                ${availableMenuItems.map(item => `
                                    <div class="flex items-center space-x-3 py-2 border-b border-gray-100 last:border-b-0" data-item-id="${item.id}" data-item-price="${item.price}">
                                        <input type="checkbox" name="menu_items" value="${item.id}" 
                                               class="rounded border-gray-300 text-blue-600 focus:ring-blue-500 item-checkbox"
                                               onchange="dashboard.toggleMenuItemQuantity(this)">
                                        <div class="flex-1">
                                            <div class="text-sm font-medium text-gray-900">${item.name}</div>
                                            <div class="text-xs text-gray-500">${item.price} ден • ${this.categories.find(c => c.id === item.category_id)?.name || 'Unknown Category'}</div>
                                        </div>
                                        <div class="flex items-center space-x-2">
                                            <label class="text-sm text-gray-600">Qty:</label>
                                            <input type="number" name="quantity_${item.id}" min="1" value="1" 
                                                   class="w-16 px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 item-quantity"
                                                   disabled onchange="dashboard.updatePromotionItemsTotal()">
                                        </div>
                                    </div>
                                `).join('')}
                            `}
                        </div>
                        <div class="mt-2 p-2 bg-gray-50 rounded-lg">
                            <div class="flex justify-between items-center">
                                <span class="text-sm text-gray-600">Selected items total:</span>
                                <span id="selectedItemsTotal" class="text-lg font-bold text-orange-600">0 ден</span>
                            </div>
                        </div>
                        <p class="text-xs text-gray-500 mt-1">Select menu items and specify quantities. You can add the same item multiple times by increasing the quantity.</p>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Display Order</label>
                            <input type="number" name="display_order" min="0" 
                                   value="${this.promotions.length + 1}"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div class="flex items-center">
                            <label class="flex items-center">
                                <input type="checkbox" name="is_visible" checked 
                                       class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                <span class="ml-2 text-sm text-gray-700">Active (visible in menu)</span>
                            </label>
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        Create Promotion
                    </button>
                </div>
            </form>
        `;
        
        this.showModal('Add Promotion', content);
        

        this.updatePromotionItemsTotal();
        
        // Set up form handling to populate hidden fields
        const form = document.getElementById('promotionForm');
        form.addEventListener('submit', (e) => {
            // Use Macedonian as primary fallback to English, then to empty
            const nameMk = form.name_mk.value;
            const nameEn = form.name_en.value;
            form.querySelector('#hiddenPromotionName').value = nameMk || nameEn || '';
            
            const descMk = form.description_mk.value;
            const descEn = form.description_en.value;
            form.querySelector('#hiddenPromotionDescription').value = descMk || descEn || '';
        });

        document.getElementById('promotionForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitBtn = e.target.querySelector('button[type="submit"]');
            
            if (!this.preventDoubleSubmission('promotionForm', submitBtn)) {
                return;
            }
            
            try {
                const formData = new FormData(e.target);
                

                const selectedItemsWithQuantities = Array.from(document.querySelectorAll('input[name="menu_items"]:checked'))
                    .map(checkbox => {
                        const itemId = parseInt(checkbox.value);
                        const quantityInput = document.querySelector(`input[name="quantity_${itemId}"]`);
                        const quantity = quantityInput ? parseInt(quantityInput.value) || 1 : 1;
                        return { menu_item_id: itemId, quantity: quantity };
                    });
                
                const promotionData = {
                    restaurant_id: this.currentRestaurantId,
                    name: formData.get('name'),
                    name_mk: formData.get('name_mk'),
                    name_en: formData.get('name_en'),
                    name_al: formData.get('name_al'),
                    description: formData.get('description'),
                    description_mk: formData.get('description_mk'),
                    description_en: formData.get('description_en'),
                    description_al: formData.get('description_al'),
                    price: parseFloat(formData.get('price')),
                    display_order: parseInt(formData.get('display_order')) || 0,
                    is_visible: formData.get('is_visible') === 'on',
                    menu_items_with_quantities: selectedItemsWithQuantities
                };
                
                const response = await axios.post('/api/admin/promotions', promotionData);
                
                if (response.data.success) {
                    await this.loadRestaurantData(this.currentRestaurantId);
                    this.render();
                    this.closeModal();
                } else {
                    alert('Error: ' + response.data.message);
                }
            } catch (error) {
                console.error('Error creating promotion:', error);
                alert('Failed to create promotion. Please try again.');
            } finally {
                this.restoreSubmissionState('promotionForm', submitBtn);
            }
        });
    }
    
    async editPromotion(id) {
        try {
            const response = await axios.get(`/api/admin/promotions/${id}`);
            if (!response.data.success) {
                alert('Promotion not found');
                return;
            }
            
            const promotion = response.data.data;
            const availableMenuItems = this.menuItems.filter(item => 
                item.restaurant_id === this.currentRestaurantId && item.is_active
            );
            
            const content = `
                <form id="editPromotionForm">
                    <div class="grid grid-cols-1 gap-6">
                        <div>
                            <h3 class="text-lg font-medium text-gray-900 mb-4">Promotion Names</h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Promotion Name (Macedonian)*</label>
                                    <input type="text" name="name_mk" required value="${this.escapeHtml(promotion.name_mk || '')}"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                           placeholder="Внесете име на промоција">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Promotion Name (English)*</label>
                                    <input type="text" name="name_en" required value="${this.escapeHtml(promotion.name_en || '')}"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                           placeholder="Enter promotion name">
                                </div>
                            </div>
                            <input type="hidden" name="name" id="hiddenEditPromotionName" value="${this.escapeHtml(promotion.name || '')}">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Price*</label>
                            <input type="number" name="price" step="0.01" min="0" required value="${promotion.price}"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                   placeholder="Enter promotion price">
                        </div>
                        
                        <div>
                            <h3 class="text-lg font-medium text-gray-900 mb-4">Promotion Description</h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Description (Macedonian)</label>
                                    <textarea name="description_mk" rows="3" 
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                              placeholder="Внесете опис (опционално)">${this.escapeHtml(promotion.description_mk || '')}</textarea>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Description (English)</label>
                                    <textarea name="description_en" rows="3" 
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                              placeholder="Enter description (optional)">${this.escapeHtml(promotion.description_en || '')}</textarea>
                                </div>
                            </div>
                            <input type="hidden" name="description" id="hiddenEditPromotionDescription" value="${this.escapeHtml(promotion.description || '')}">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Select Menu Items & Quantities</label>
                            <div class="border border-gray-300 rounded-lg max-h-64 overflow-y-auto p-4">
                                ${availableMenuItems.length === 0 ? `
                                    <p class="text-gray-500 text-sm">No menu items available. Please create menu items first.</p>
                                ` : `
                                    ${availableMenuItems.map(item => {
                                        const promotionItem = promotion.menu_items && promotion.menu_items.find(pi => pi.id === item.id);
                                        const isSelected = !!promotionItem;
                                        const quantity = promotionItem ? promotionItem.quantity || 1 : 1;
                                        return `
                                            <div class="flex items-center space-x-3 py-2 border-b border-gray-100 last:border-b-0" data-item-id="${item.id}" data-item-price="${item.price}">
                                                <input type="checkbox" name="menu_items" value="${item.id}" 
                                                       ${isSelected ? 'checked' : ''}
                                                       class="rounded border-gray-300 text-blue-600 focus:ring-blue-500 item-checkbox"
                                                       onchange="dashboard.toggleMenuItemQuantity(this)">
                                                <div class="flex-1">
                                                    <div class="text-sm font-medium text-gray-900">${item.name}</div>
                                                    <div class="text-xs text-gray-500">${item.price} ден • ${this.categories.find(c => c.id === item.category_id)?.name || 'Unknown Category'}</div>
                                                </div>
                                                <div class="flex items-center space-x-2">
                                                    <label class="text-sm text-gray-600">Qty:</label>
                                                    <input type="number" name="quantity_${item.id}" min="1" value="${quantity}" 
                                                           class="w-16 px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 item-quantity"
                                                           ${!isSelected ? 'disabled' : ''} onchange="dashboard.updatePromotionItemsTotal()">
                                                </div>
                                            </div>
                                        `;
                                    }).join('')}
                                `}
                            </div>
                        <div class="mt-2 p-2 bg-gray-50 rounded-lg">
                            <div class="flex justify-between items-center">
                                <span class="text-sm text-gray-600">Selected items total:</span>
                                <span id="selectedItemsTotal" class="text-lg font-bold text-orange-600">0 ден</span>
                            </div>
                        </div>
                        <p class="text-xs text-gray-500 mt-1">Select the menu items that are included in this promotion.</p>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Display Order</label>
                                <input type="number" name="display_order" min="0" value="${promotion.display_order || 0}"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            
                            <div class="flex items-center">
                                <label class="flex items-center">
                                    <input type="checkbox" name="is_visible" ${promotion.is_visible ? 'checked' : ''}
                                           class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                    <span class="ml-2 text-sm text-gray-700">Active (visible in menu)</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="flex justify-end space-x-3 mt-6">
                        <button type="button" onclick="dashboard.closeModal()" 
                                class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                            Cancel
                        </button>
                        <button type="submit" 
                                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                            Update Promotion
                        </button>
                    </div>
                </form>
            `;
            
            this.showModal('Edit Promotion', content);
            

            this.updatePromotionItemsTotal();
            
            // Set up form handling to populate hidden fields
            const form = document.getElementById('editPromotionForm');
            form.addEventListener('submit', (e) => {
                // Use Macedonian as primary fallback to English, then to empty
                const nameMk = form.name_mk.value;
                const nameEn = form.name_en.value;
                form.querySelector('#hiddenEditPromotionName').value = nameMk || nameEn || '';
                
                const descMk = form.description_mk.value;
                const descEn = form.description_en.value;
                form.querySelector('#hiddenEditPromotionDescription').value = descMk || descEn || '';
            });

            document.getElementById('editPromotionForm').addEventListener('submit', async (e) => {
                e.preventDefault();
                
                const submitBtn = e.target.querySelector('button[type="submit"]');
                
                if (!this.preventDoubleSubmission('editPromotionForm', submitBtn)) {
                    return;
                }
                
                try {
                    const formData = new FormData(e.target);
                    

                    const selectedItemsWithQuantities = Array.from(document.querySelectorAll('input[name="menu_items"]:checked'))
                        .map(checkbox => {
                            const itemId = parseInt(checkbox.value);
                            const quantityInput = document.querySelector(`input[name="quantity_${itemId}"]`);
                            const quantity = quantityInput ? parseInt(quantityInput.value) || 1 : 1;
                            return { menu_item_id: itemId, quantity: quantity };
                        });
                    
                    const promotionData = {
                        name: formData.get('name'),
                        name_mk: formData.get('name_mk'),
                        name_en: formData.get('name_en'),
                        description: formData.get('description'),
                        description_mk: formData.get('description_mk'),
                        description_en: formData.get('description_en'),
                        price: parseFloat(formData.get('price')),
                        display_order: parseInt(formData.get('display_order')) || 0,
                        is_visible: formData.get('is_visible') === 'on',
                        menu_items_with_quantities: selectedItemsWithQuantities
                    };
                    
                    const response = await axios.put(`/api/admin/promotions/${id}`, promotionData);
                    
                    if (response.data.success) {
                        await this.loadRestaurantData(this.currentRestaurantId);
                        this.render();
                        this.closeModal();
                    } else {
                        alert('Error: ' + response.data.message);
                    }
                } catch (error) {
                    console.error('Error updating promotion:', error);
                    alert('Failed to update promotion. Please try again.');
                } finally {
                    this.restoreSubmissionState('editPromotionForm', submitBtn);
                }
            });
        } catch (error) {
            console.error('Error fetching promotion:', error);
            alert('Failed to load promotion data.');
        }
    }
    
    async deletePromotion(id) {
        const promotion = this.promotions.find(p => p.id === id);
        if (!promotion) return;

        if (confirm(`Are you sure you want to delete "${promotion.name}"? This action cannot be undone.`)) {
            try {
                const response = await axios.delete(`/api/admin/promotions/${id}`);
                if (response.data.success) {
                    await this.loadRestaurantData(this.currentRestaurantId);
                    this.render();
                }
            } catch (error) {
                console.error('Error deleting promotion:', error);
                alert('Failed to delete promotion. Please try again.');
            }
        }
    }
    
    async togglePromotionVisibility(id, isVisible) {
        try {
            const promotion = this.promotions.find(p => p.id === id);
            if (!promotion) return;
            
            const response = await axios.put(`/api/admin/promotions/${id}`, {
                ...promotion,
                is_visible: isVisible
            });
            
            if (response.data.success) {

                const promotionIndex = this.promotions.findIndex(p => p.id === id);
                if (promotionIndex !== -1) {
                    this.promotions[promotionIndex].is_visible = isVisible;
                }
                

                this.render();
                

                await this.loadRestaurantData(this.currentRestaurantId);
            }
        } catch (error) {
            console.error('Error toggling promotion visibility:', error);
            alert('Failed to update promotion visibility.');
        }
    }
    
    async movePromotion(promotionId, direction) {
        const promotion = this.promotions.find(p => p.id === promotionId);
        if (!promotion) return;

        const sortedPromotions = this.promotions
            .sort((a, b) => (a.display_order || 0) - (b.display_order || 0));

        const currentIndex = sortedPromotions.findIndex(p => p.id === promotionId);
        if (currentIndex === -1) return;

        let targetIndex;
        if (direction === 'up' && currentIndex > 0) {
            targetIndex = currentIndex - 1;
        } else if (direction === 'down' && currentIndex < sortedPromotions.length - 1) {
            targetIndex = currentIndex + 1;
        } else {
            return; // Can't move further in that direction
        }
        const targetPromotion = sortedPromotions[targetIndex];
        const tempOrder = promotion.display_order || 0;
        
        try {
            await axios.put(`/api/admin/promotions/${promotion.id}/order`, {
                display_order: targetPromotion.display_order || 0
            });
            
            await axios.put(`/api/admin/promotions/${targetPromotion.id}/order`, {
                display_order: tempOrder
            });
            

            await this.loadRestaurantData(this.currentRestaurantId);
            this.render();
        } catch (error) {
            console.error('Error reordering promotions:', error);
            alert('Failed to reorder promotions.');
        }
    }

    // Helper function to escape HTML to prevent XSS
    escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Helper function to clear menu item image preview
    clearMenuItemImagePreview() {
        document.getElementById('menuItemImageInput').value = '';
        document.getElementById('menuItemImagePreview').classList.add('hidden');
        document.getElementById('menuItemPreviewImage').src = '';
    }

    // Helper function to delete current image
    deleteCurrentImage(type, id) {
        if (!confirm(`Are you sure you want to delete the current ${type === 'menuItem' ? 'menu item image' : 'restaurant logo'}?`)) {
            return;
        }

        if (type === 'menuItem') {
            // Hide current image container and set delete flag
            document.getElementById('currentImageContainer').style.display = 'none';
            document.getElementById('deleteImageFlag').value = 'true';
        } else if (type === 'restaurant') {
            // Hide current logo container and set delete flag
            document.getElementById('currentLogoContainer').style.display = 'none';
            document.getElementById('deleteLogoFlag').value = 'true';
        }
    }

    // Celebration Menu Management Functions
    showAddCelebrationMenuForm() {
        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
        modal.innerHTML = `
            <div class="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
                <div class="flex justify-between items-center p-6 border-b">
                    <h2 class="text-xl font-bold">Add Celebration Menu</h2>
                    <button onclick="this.closest('.fixed').remove()" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                <form id="addCelebrationMenuForm" class="p-6">
                    <div class="space-y-4">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Name (Macedonian)</label>
                                <input type="text" id="celebrationMenuNameMk" required
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Name (English)</label>
                                <input type="text" id="celebrationMenuNameEn"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Name (Albanian)</label>
                                <input type="text" id="celebrationMenuNameAl"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Price Per Person (ден)</label>
                            <input type="number" id="celebrationMenuPrice" required step="0.01" min="0"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div class="border-t pt-4">
                            <div class="flex justify-between items-center mb-3">
                                <label class="block text-sm font-medium text-gray-700">Menu Sections</label>
                                <button type="button" onclick="dashboard.addCelebrationMenuSection()" 
                                        class="text-blue-600 hover:text-blue-700 text-sm">
                                    <i class="fas fa-plus mr-1"></i>Add Section
                                </button>
                            </div>
                            <div id="celebrationMenuSections" class="space-y-4">
                                <!-- Sections will be added here dynamically -->
                            </div>
                        </div>

                        <div class="border-t pt-4">
                            <label class="block text-sm font-medium text-gray-700 mb-3">Disclaimer (Optional)</label>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label class="block text-xs font-medium text-gray-600 mb-1">
                                        <span class="inline-flex items-center gap-1">
                                            <span>🇲🇰</span>
                                            <span>Macedonian</span>
                                        </span>
                                    </label>
                                    <textarea id="celebrationMenuDisclaimerMk" rows="2"
                                              placeholder="Напомена..."
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"></textarea>
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-600 mb-1">
                                        <span class="inline-flex items-center gap-1">
                                            <span>🇬🇧</span>
                                            <span>English</span>
                                        </span>
                                    </label>
                                    <textarea id="celebrationMenuDisclaimerEn" rows="2"
                                              placeholder="Disclaimer..."
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"></textarea>
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-600 mb-1">
                                        <span class="inline-flex items-center gap-1">
                                            <span>🇦🇱</span>
                                            <span>Albanian</span>
                                        </span>
                                    </label>
                                    <textarea id="celebrationMenuDisclaimerAl" rows="2"
                                              placeholder="Shënim..."
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"></textarea>
                                </div>
                            </div>
                            <p class="text-xs text-gray-500 mt-2">Disclaimers will be displayed with an asterisk (*) prefix at the bottom of the menu based on the selected language</p>
                        </div>

                        <div class="flex items-center">
                            <input type="checkbox" id="celebrationMenuActive" checked class="mr-2">
                            <label for="celebrationMenuActive" class="text-sm text-gray-700">Active</label>
                        </div>
                        <div class="flex items-center">
                            <input type="checkbox" id="celebrationMenuVisible" checked class="mr-2">
                            <label for="celebrationMenuVisible" class="text-sm text-gray-700">Visible on Menu</label>
                        </div>
                    </div>
                    <div class="flex justify-end gap-3 mt-6">
                        <button type="button" onclick="this.closest('.fixed').remove()" 
                                class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                            Cancel
                        </button>
                        <button type="submit" id="submitCelebrationMenuBtn"
                                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                            Create Menu
                        </button>
                    </div>
                </form>
            </div>
        `;
        document.body.appendChild(modal);

        // Add first section by default
        this.addCelebrationMenuSection();

        // Handle form submission
        document.getElementById('addCelebrationMenuForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const submitBtn = document.getElementById('submitCelebrationMenuBtn');

            if (!this.preventDoubleSubmission('addCelebrationMenuForm', submitBtn)) {
                return;
            }

            try {
                const sections = this.getCelebrationMenuSectionsData();
                
                const nameMk = document.getElementById('celebrationMenuNameMk').value;
                const nameAlField = document.getElementById('celebrationMenuNameAl');
                const disclaimerMk = document.getElementById('celebrationMenuDisclaimerMk').value || null;
                const disclaimerEn = document.getElementById('celebrationMenuDisclaimerEn').value || null;
                const disclaimerAl = document.getElementById('celebrationMenuDisclaimerAl').value || null;
                
                const data = {
                    restaurant_id: this.currentRestaurantId,
                    name: nameMk,
                    name_mk: nameMk,
                    name_en: document.getElementById('celebrationMenuNameEn').value,
                    name_al: nameAlField ? nameAlField.value : null,
                    price_per_person: parseFloat(document.getElementById('celebrationMenuPrice').value),
                    disclaimer: disclaimerMk || disclaimerEn || disclaimerAl || null,
                    disclaimer_mk: disclaimerMk,
                    disclaimer_en: disclaimerEn,
                    disclaimer_al: disclaimerAl,
                    is_active: document.getElementById('celebrationMenuActive').checked,
                    is_visible: document.getElementById('celebrationMenuVisible').checked,
                    display_order: 0,
                    sections: sections
                };

                const response = await axios.post('/api/admin/celebration-menus', data);
                
                if (response.data.success) {
                    await this.loadRestaurantData(this.currentRestaurantId);
                    this.render();
                    modal.remove();
                    alert('Celebration menu created successfully!');
                }
            } catch (error) {
                console.error('Error creating celebration menu:', error);
                alert('Failed to create celebration menu. Please try again.');
                this.restoreSubmissionState('addCelebrationMenuForm', submitBtn);
            }
        });
    }

    addCelebrationMenuSection() {
        const sectionsContainer = document.getElementById('celebrationMenuSections');
        const sectionIndex = sectionsContainer.children.length;
        
        const sectionDiv = document.createElement('div');
        sectionDiv.className = 'border border-gray-200 rounded-lg p-4 celebration-menu-section';
        sectionDiv.innerHTML = `
            <div class="flex justify-between items-center mb-3">
                <h4 class="font-medium text-gray-700">Section ${sectionIndex + 1}</h4>
                <button type="button" onclick="this.closest('.celebration-menu-section').remove()" 
                        class="text-red-600 hover:text-red-700 text-sm">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
            <div class="space-y-3">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">Title (Macedonian)</label>
                        <input type="text" class="section-title-mk w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">Title (English)</label>
                        <input type="text" class="section-title-en w-full px-3 py-2 border border-gray-300 rounded-lg">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">Title (Albanian)</label>
                        <input type="text" class="section-title-al w-full px-3 py-2 border border-gray-300 rounded-lg">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">Description (Macedonian)</label>
                        <textarea class="section-description-mk w-full px-3 py-2 border border-gray-300 rounded-lg" rows="2"></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">Description (English)</label>
                        <textarea class="section-description-en w-full px-3 py-2 border border-gray-300 rounded-lg" rows="2"></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">Description (Albanian)</label>
                        <textarea class="section-description-al w-full px-3 py-2 border border-gray-300 rounded-lg" rows="2"></textarea>
                    </div>
                </div>
            </div>
        `;
        sectionsContainer.appendChild(sectionDiv);
    }

    getCelebrationMenuSectionsData() {
        const sections = [];
        const sectionElements = document.querySelectorAll('.celebration-menu-section');
        
        sectionElements.forEach(element => {
            const titleMk = element.querySelector('.section-title-mk').value;
            const descriptionMk = element.querySelector('.section-description-mk').value;
            sections.push({
                title: titleMk,
                title_mk: titleMk,
                title_en: element.querySelector('.section-title-en').value,
                title_al: element.querySelector('.section-title-al').value,
                description: descriptionMk,
                description_mk: descriptionMk,
                description_en: element.querySelector('.section-description-en').value,
                description_al: element.querySelector('.section-description-al').value
            });
        });
        
        return sections;
    }

    async editCelebrationMenu(id) {
        const menu = this.celebrationMenus.find(m => m.id === id);
        if (!menu) return;

        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
        modal.innerHTML = `
            <div class="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
                <div class="flex justify-between items-center p-6 border-b">
                    <h2 class="text-xl font-bold">Edit Celebration Menu</h2>
                    <button onclick="this.closest('.fixed').remove()" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                <form id="editCelebrationMenuForm" class="p-6">
                    <div class="space-y-4">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Name (Macedonian)</label>
                                <input type="text" id="editCelebrationMenuNameMk" value="${menu.name_mk || ''}" required
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Name (English)</label>
                                <input type="text" id="editCelebrationMenuNameEn" value="${menu.name_en || ''}"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div id="celebrationMenuAlbanianNameField" style="display:none;">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Name (Albanian)</label>
                                <input type="text" id="editCelebrationMenuNameAl" value="${menu.name_al || ''}"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Price Per Person (ден)</label>
                            <input type="number" id="editCelebrationMenuPrice" value="${menu.price_per_person}" required step="0.01" min="0"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        </div>
                        
                        <div class="border-t pt-4">
                            <div class="flex justify-between items-center mb-3">
                                <label class="block text-sm font-medium text-gray-700">Menu Sections</label>
                                <button type="button" onclick="dashboard.addCelebrationMenuSection()" 
                                        class="text-blue-600 hover:text-blue-700 text-sm">
                                    <i class="fas fa-plus mr-1"></i>Add Section
                                </button>
                            </div>
                            <div id="celebrationMenuSections" class="space-y-4">
                                <!-- Sections will be added here dynamically -->
                            </div>
                        </div>

                        <div class="border-t pt-4">
                            <label class="block text-sm font-medium text-gray-700 mb-3">Disclaimer (Optional)</label>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label class="block text-xs font-medium text-gray-600 mb-1">
                                        <span class="inline-flex items-center gap-1">
                                            <span>🇲🇰</span>
                                            <span>Macedonian</span>
                                        </span>
                                    </label>
                                    <textarea id="editCelebrationMenuDisclaimerMk" rows="2"
                                              placeholder="Напомена..."
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm">${menu.disclaimer_mk || ''}</textarea>
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-600 mb-1">
                                        <span class="inline-flex items-center gap-1">
                                            <span>🇬🇧</span>
                                            <span>English</span>
                                        </span>
                                    </label>
                                    <textarea id="editCelebrationMenuDisclaimerEn" rows="2"
                                              placeholder="Disclaimer..."
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm">${menu.disclaimer_en || ''}</textarea>
                                </div>
                                <div>
                                    <label class="block text-xs font-medium text-gray-600 mb-1">
                                        <span class="inline-flex items-center gap-1">
                                            <span>🇦🇱</span>
                                            <span>Albanian</span>
                                        </span>
                                    </label>
                                    <textarea id="editCelebrationMenuDisclaimerAl" rows="2"
                                              placeholder="Shënim..."
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm">${menu.disclaimer_al || ''}</textarea>
                                </div>
                            </div>
                            <p class="text-xs text-gray-500 mt-2">Disclaimers will be displayed with an asterisk (*) prefix at the bottom of the menu based on the selected language</p>
                        </div>

                        <div class="flex items-center">
                            <input type="checkbox" id="editCelebrationMenuActive" ${menu.is_active ? 'checked' : ''} class="mr-2">
                            <label for="editCelebrationMenuActive" class="text-sm text-gray-700">Active</label>
                        </div>
                        <div class="flex items-center">
                            <input type="checkbox" id="editCelebrationMenuVisible" ${menu.is_visible ? 'checked' : ''} class="mr-2">
                            <label for="editCelebrationMenuVisible" class="text-sm text-gray-700">Visible on Menu</label>
                        </div>
                    </div>
                    <div class="flex justify-end gap-3 mt-6">
                        <button type="button" onclick="this.closest('.fixed').remove()" 
                                class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                            Cancel
                        </button>
                        <button type="submit" id="submitEditCelebrationMenuBtn"
                                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                            Update Menu
                        </button>
                    </div>
                </form>
            </div>
        `;
        document.body.appendChild(modal);

        // Load existing sections
        if (menu.sections && menu.sections.length > 0) {
            menu.sections.forEach(section => {
                this.addCelebrationMenuSection();
                const sectionElements = document.querySelectorAll('.celebration-menu-section');
                const lastSection = sectionElements[sectionElements.length - 1];
                lastSection.querySelector('.section-title-mk').value = section.title_mk || '';
                lastSection.querySelector('.section-title-en').value = section.title_en || '';
                lastSection.querySelector('.section-title-al').value = section.title_al || '';
                lastSection.querySelector('.section-description-mk').value = section.description_mk || '';
                lastSection.querySelector('.section-description-en').value = section.description_en || '';
                lastSection.querySelector('.section-description-al').value = section.description_al || '';
            });
        } else {
            this.addCelebrationMenuSection();
        }

        // Handle form submission
        document.getElementById('editCelebrationMenuForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const submitBtn = document.getElementById('submitEditCelebrationMenuBtn');

            if (!this.preventDoubleSubmission('editCelebrationMenuForm', submitBtn)) {
                return;
            }

            try {
                const sections = this.getCelebrationMenuSectionsData();
                
                const nameMk = document.getElementById('editCelebrationMenuNameMk').value;
                const nameAlField = document.getElementById('editCelebrationMenuNameAl');
                const disclaimerMk = document.getElementById('editCelebrationMenuDisclaimerMk').value || null;
                const disclaimerEn = document.getElementById('editCelebrationMenuDisclaimerEn').value || null;
                const disclaimerAl = document.getElementById('editCelebrationMenuDisclaimerAl').value || null;
                
                const data = {
                    name: nameMk,
                    name_mk: nameMk,
                    name_en: document.getElementById('editCelebrationMenuNameEn').value,
                    name_al: nameAlField ? nameAlField.value : null,
                    price_per_person: parseFloat(document.getElementById('editCelebrationMenuPrice').value),
                    disclaimer: disclaimerMk || disclaimerEn || disclaimerAl || null,
                    disclaimer_mk: disclaimerMk,
                    disclaimer_en: disclaimerEn,
                    disclaimer_al: disclaimerAl,
                    is_active: document.getElementById('editCelebrationMenuActive').checked,
                    is_visible: document.getElementById('editCelebrationMenuVisible').checked,
                    display_order: menu.display_order || 0,
                    sections: sections
                };

                const response = await axios.put(`/api/admin/celebration-menus/${id}`, data);
                
                if (response.data.success) {
                    await this.loadRestaurantData(this.currentRestaurantId);
                    this.render();
                    modal.remove();
                    alert('Celebration menu updated successfully!');
                }
            } catch (error) {
                console.error('Error updating celebration menu:', error);
                alert('Failed to update celebration menu. Please try again.');
                this.restoreSubmissionState('editCelebrationMenuForm', submitBtn);
            }
        });
    }

    async deleteCelebrationMenu(id) {
        const menu = this.celebrationMenus.find(m => m.id === id);
        if (!menu) return;

        if (confirm(`Are you sure you want to delete "${menu.name || menu.name_en || menu.name_mk}"? This action cannot be undone.`)) {
            try {
                const response = await axios.delete(`/api/admin/celebration-menus/${id}`);
                if (response.data.success) {
                    await this.loadRestaurantData(this.currentRestaurantId);
                    this.render();
                    alert('Celebration menu deleted successfully!');
                }
            } catch (error) {
                console.error('Error deleting celebration menu:', error);
                alert('Failed to delete celebration menu. Please try again.');
            }
        }
    }

    async toggleCelebrationMenuVisibility(id, isVisible) {
        try {
            const menu = this.celebrationMenus.find(m => m.id === id);
            if (!menu) return;
            
            const response = await axios.put(`/api/admin/celebration-menus/${id}`, {
                ...menu,
                is_visible: isVisible,
                sections: menu.sections || []
            });
            
            if (response.data.success) {
                menu.is_visible = isVisible;
                this.render();
            }
        } catch (error) {
            console.error('Error toggling celebration menu visibility:', error);
            alert('Error updating celebration menu visibility. Please try again.');
        }
    }

    // Hot Items Management Functions
    showAddHotItemForm() {
        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
        modal.innerHTML = `
            <div class="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                <div class="sticky top-0 bg-white border-b px-6 py-4">
                    <h2 class="text-xl font-bold text-gray-900">Add Hot Item</h2>
                </div>
                <form id="addHotItemForm" class="p-6" enctype="multipart/form-data">
                    <div class="space-y-4">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Name (Macedonian) *</label>
                                <input type="text" id="hotItemNameMk" required
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Name (English)</label>
                                <input type="text" id="hotItemNameEn"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Name (Albanian)</label>
                                <input type="text" id="hotItemNameAl"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Price (MKD) *</label>
                                <input type="number" id="hotItemPrice" required step="0.01" min="0"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Size Info</label>
                                <input type="text" id="hotItemSizeInfo"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg"
                                       placeholder="e.g., 300g, 500ml">
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Description (Macedonian)</label>
                                <textarea id="hotItemDescriptionMk" rows="3"
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg"></textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Description (English)</label>
                                <textarea id="hotItemDescriptionEn" rows="3"
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg"></textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Description (Albanian)</label>
                                <textarea id="hotItemDescriptionAl" rows="3"
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg"></textarea>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Allergens (Macedonian)</label>
                                <textarea id="hotItemAllergensMk" rows="2"
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg"></textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Allergens (English)</label>
                                <textarea id="hotItemAllergensEn" rows="2"
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg"></textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Allergens (Albanian)</label>
                                <textarea id="hotItemAllergensAl" rows="2"
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg"></textarea>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Image</label>
                            <input type="file" id="hotItemImage" accept="image/*"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                        </div>

                        <div class="flex items-center space-x-4">
                            <label class="flex items-center">
                                <input type="checkbox" id="hotItemActive" checked class="mr-2">
                                <span class="text-sm text-gray-700">Active</span>
                            </label>
                            <label class="flex items-center">
                                <input type="checkbox" id="hotItemVisible" checked class="mr-2">
                                <span class="text-sm text-gray-700">Visible on Menu</span>
                            </label>
                        </div>
                    </div>

                    <div class="flex justify-end space-x-3 mt-6">
                        <button type="button" onclick="this.closest('.fixed').remove()"
                                class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                            Cancel
                        </button>
                        <button type="submit" id="submitHotItemBtn"
                                class="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700">
                            Create Hot Item
                        </button>
                    </div>
                </form>
            </div>
        `;
        document.body.appendChild(modal);

        // Handle form submission
        document.getElementById('addHotItemForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const submitBtn = document.getElementById('submitHotItemBtn');

            if (!this.preventDoubleSubmission('addHotItemForm', submitBtn)) {
                return;
            }

            try {
                const formData = new FormData();
                formData.append('restaurant_id', this.currentRestaurantId);
                formData.append('name', document.getElementById('hotItemNameMk').value);
                formData.append('name_mk', document.getElementById('hotItemNameMk').value);
                formData.append('name_en', document.getElementById('hotItemNameEn').value);
                formData.append('name_al', document.getElementById('hotItemNameAl').value);
                formData.append('description', document.getElementById('hotItemDescriptionMk').value);
                formData.append('description_mk', document.getElementById('hotItemDescriptionMk').value);
                formData.append('description_en', document.getElementById('hotItemDescriptionEn').value);
                formData.append('description_al', document.getElementById('hotItemDescriptionAl').value);
                formData.append('price', document.getElementById('hotItemPrice').value);
                formData.append('size_info', document.getElementById('hotItemSizeInfo').value);
                formData.append('allergens', document.getElementById('hotItemAllergensMk').value);
                formData.append('allergens_mk', document.getElementById('hotItemAllergensMk').value);
                formData.append('allergens_en', document.getElementById('hotItemAllergensEn').value);
                formData.append('allergens_al', document.getElementById('hotItemAllergensAl').value);
                formData.append('is_active', document.getElementById('hotItemActive').checked);
                formData.append('is_visible', document.getElementById('hotItemVisible').checked);
                
                const imageFile = document.getElementById('hotItemImage').files[0];
                if (imageFile) {
                    formData.append('image', imageFile);
                }

                const response = await axios.post('/api/admin/hot-items', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                });
                
                if (response.data.success) {
                    await this.loadRestaurantData(this.currentRestaurantId);
                    this.render();
                    modal.remove();
                    alert('Hot item created successfully!');
                }
            } catch (error) {
                console.error('Error creating hot item:', error);
                alert('Failed to create hot item. Please try again.');
                this.restoreSubmissionState('addHotItemForm', submitBtn);
            }
        });
    }

    async editHotItem(id) {
        try {
            const response = await axios.get(`/api/admin/hot-items/${id}`);
            const item = response.data.data;
            
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4 overflow-y-auto';
            modal.innerHTML = `
                <div class="bg-white rounded-lg max-w-4xl w-full my-8 mx-auto shadow-xl">
                    <div class="sticky top-0 bg-white border-b px-4 sm:px-6 py-4 rounded-t-lg z-10">
                        <div class="flex justify-between items-center">
                            <h2 class="text-lg sm:text-xl font-bold text-gray-900">Edit Hot Item</h2>
                            <button type="button" onclick="this.closest('.fixed').remove()" class="text-gray-500 hover:text-gray-700">
                                <i class="fas fa-times text-xl"></i>
                            </button>
                        </div>
                    </div>
                    <form id="editHotItemForm" class="p-4 sm:p-6 max-h-[calc(90vh-80px)] overflow-y-auto" enctype="multipart/form-data">
                        <div class="space-y-4">
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Name (Macedonian) *</label>
                                    <input type="text" id="hotItemNameMk" value="${item.name_mk || ''}" required
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Name (English)</label>
                                    <input type="text" id="hotItemNameEn" value="${item.name_en || ''}"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Name (Albanian)</label>
                                    <input type="text" id="hotItemNameAl" value="${item.name_al || ''}"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                </div>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Price (MKD) *</label>
                                    <input type="number" id="hotItemPrice" value="${item.price}" required step="0.01" min="0"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Size Info</label>
                                    <input type="text" id="hotItemSizeInfo" value="${item.size_info || ''}"
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                </div>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Description (Macedonian)</label>
                                    <textarea id="hotItemDescriptionMk" rows="3"
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg">${item.description_mk || ''}</textarea>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Description (English)</label>
                                    <textarea id="hotItemDescriptionEn" rows="3"
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg">${item.description_en || ''}</textarea>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Description (Albanian)</label>
                                    <textarea id="hotItemDescriptionAl" rows="3"
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg">${item.description_al || ''}</textarea>
                                </div>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Allergens (Macedonian)</label>
                                    <textarea id="hotItemAllergensMk" rows="2"
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg">${item.allergens_mk || ''}</textarea>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Allergens (English)</label>
                                    <textarea id="hotItemAllergensEn" rows="2"
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg">${item.allergens_en || ''}</textarea>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Allergens (Albanian)</label>
                                    <textarea id="hotItemAllergensAl" rows="2"
                                              class="w-full px-3 py-2 border border-gray-300 rounded-lg">${item.allergens_al || ''}</textarea>
                                </div>
                            </div>

                            ${item.image_url ? `
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Current Image</label>
                                    <div class="flex flex-col sm:flex-row items-start sm:items-center gap-4">
                                        <img src="${item.image_url}" alt="${item.name}" class="w-32 h-32 object-cover rounded border border-gray-300">
                                        <button type="button" id="deletePhotoBtn" 
                                                class="px-4 py-2 bg-red-600 text-white text-sm rounded-lg hover:bg-red-700 transition-colors flex items-center gap-2">
                                            <i class="fas fa-trash"></i>
                                            <span>Delete Photo</span>
                                        </button>
                                    </div>
                                </div>
                            ` : ''}

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">${item.image_url ? 'Replace Image (optional)' : 'Upload Image (optional)'}</label>
                                <input type="file" id="hotItemImage" accept="image/*"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm">
                            </div>

                            <div class="flex flex-col sm:flex-row items-start sm:items-center gap-3 sm:gap-4">
                                <label class="flex items-center cursor-pointer">
                                    <input type="checkbox" id="hotItemActive" ${item.is_active ? 'checked' : ''} class="mr-2 w-4 h-4">
                                    <span class="text-sm text-gray-700">Active</span>
                                </label>
                                <label class="flex items-center cursor-pointer">
                                    <input type="checkbox" id="hotItemVisible" ${item.is_visible ? 'checked' : ''} class="mr-2 w-4 h-4">
                                    <span class="text-sm text-gray-700">Visible on Menu</span>
                                </label>
                            </div>
                        </div>

                        <div class="flex flex-col sm:flex-row justify-end gap-3 mt-6 pt-4 border-t">
                            <button type="button" onclick="this.closest('.fixed').remove()"
                                    class="w-full sm:w-auto px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
                                Cancel
                            </button>
                            <button type="submit" id="submitHotItemBtn"
                                    class="w-full sm:w-auto px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors">
                                Update Hot Item
                            </button>
                        </div>
                    </form>
                </div>
            `;
            document.body.appendChild(modal);

            // Handle delete photo button
            const deletePhotoBtn = document.getElementById('deletePhotoBtn');
            if (deletePhotoBtn) {
                deletePhotoBtn.addEventListener('click', async () => {
                    if (confirm('Are you sure you want to delete this photo? This action cannot be undone.')) {
                        try {
                            const formData = new FormData();
                            formData.append('delete_photo', 'true');
                            formData.append('name', item.name_mk || item.name);
                            formData.append('name_mk', item.name_mk || '');
                            formData.append('name_en', item.name_en || '');
                            formData.append('name_al', item.name_al || '');
                            formData.append('description', item.description_mk || '');
                            formData.append('description_mk', item.description_mk || '');
                            formData.append('description_en', item.description_en || '');
                            formData.append('description_al', item.description_al || '');
                            formData.append('price', item.price);
                            formData.append('size_info', item.size_info || '');
                            formData.append('allergens', item.allergens_mk || '');
                            formData.append('allergens_mk', item.allergens_mk || '');
                            formData.append('allergens_en', item.allergens_en || '');
                            formData.append('allergens_al', item.allergens_al || '');
                            formData.append('is_active', item.is_active);
                            formData.append('is_visible', item.is_visible);

                            const response = await axios.put(`/api/admin/hot-items/${id}`, formData, {
                                headers: { 'Content-Type': 'multipart/form-data' }
                            });
                            
                            if (response.data.success) {
                                await this.loadRestaurantData(this.currentRestaurantId);
                                this.render();
                                modal.remove();
                                alert('Photo deleted successfully!');
                            }
                        } catch (error) {
                            console.error('Error deleting photo:', error);
                            alert('Failed to delete photo. Please try again.');
                        }
                    }
                });
            }

            // Handle form submission
            document.getElementById('editHotItemForm').addEventListener('submit', async (e) => {
                e.preventDefault();
                const submitBtn = document.getElementById('submitHotItemBtn');

                if (!this.preventDoubleSubmission('editHotItemForm', submitBtn)) {
                    return;
                }

                try {
                    const formData = new FormData();
                    formData.append('name', document.getElementById('hotItemNameMk').value);
                    formData.append('name_mk', document.getElementById('hotItemNameMk').value);
                    formData.append('name_en', document.getElementById('hotItemNameEn').value);
                    formData.append('name_al', document.getElementById('hotItemNameAl').value);
                    formData.append('description', document.getElementById('hotItemDescriptionMk').value);
                    formData.append('description_mk', document.getElementById('hotItemDescriptionMk').value);
                    formData.append('description_en', document.getElementById('hotItemDescriptionEn').value);
                    formData.append('description_al', document.getElementById('hotItemDescriptionAl').value);
                    formData.append('price', document.getElementById('hotItemPrice').value);
                    formData.append('size_info', document.getElementById('hotItemSizeInfo').value);
                    formData.append('allergens', document.getElementById('hotItemAllergensMk').value);
                    formData.append('allergens_mk', document.getElementById('hotItemAllergensMk').value);
                    formData.append('allergens_en', document.getElementById('hotItemAllergensEn').value);
                    formData.append('allergens_al', document.getElementById('hotItemAllergensAl').value);
                    formData.append('is_active', document.getElementById('hotItemActive').checked);
                    formData.append('is_visible', document.getElementById('hotItemVisible').checked);
                    
                    const imageFile = document.getElementById('hotItemImage').files[0];
                    if (imageFile) {
                        formData.append('image', imageFile);
                    }

                    const response = await axios.put(`/api/admin/hot-items/${id}`, formData, {
                        headers: { 'Content-Type': 'multipart/form-data' }
                    });
                    
                    if (response.data.success) {
                        await this.loadRestaurantData(this.currentRestaurantId);
                        this.render();
                        modal.remove();
                        alert('Hot item updated successfully!');
                    }
                } catch (error) {
                    console.error('Error updating hot item:', error);
                    alert('Failed to update hot item. Please try again.');
                    this.restoreSubmissionState('editHotItemForm', submitBtn);
                }
            });
        } catch (error) {
            console.error('Error fetching hot item:', error);
            alert('Failed to load hot item data.');
        }
    }

    async deleteHotItem(id) {
        const item = this.hotItems.find(i => i.id === id);
        if (!item) return;

        if (confirm(`Are you sure you want to delete "${item.name || item.name_mk}"? This action cannot be undone.`)) {
            try {
                const response = await axios.delete(`/api/admin/hot-items/${id}`);
                if (response.data.success) {
                    await this.loadRestaurantData(this.currentRestaurantId);
                    this.render();
                    alert('Hot item deleted successfully!');
                }
            } catch (error) {
                console.error('Error deleting hot item:', error);
                alert('Failed to delete hot item. Please try again.');
            }
        }
    }

    async toggleHotItemVisibility(id, isVisible) {
        try {
            const item = this.hotItems.find(i => i.id === id);
            if (!item) return;
            
            const response = await axios.put(`/api/admin/hot-items/${id}`, {
                ...item,
                is_visible: isVisible
            });
            
            if (response.data.success) {
                const itemIndex = this.hotItems.findIndex(i => i.id === id);
                if (itemIndex !== -1) {
                    this.hotItems[itemIndex].is_visible = isVisible;
                }
                this.render();
                await this.loadRestaurantData(this.currentRestaurantId);
            }
        } catch (error) {
            console.error('Error toggling hot item visibility:', error);
            alert('Failed to update hot item visibility.');
        }
    }

    showEditHotItemsSettings() {
        const restaurant = this.restaurants.find(r => r.id === this.currentRestaurantId);
        if (!restaurant) return;

        // Get restaurant supported languages
        const supportedLanguages = Array.isArray(restaurant.supported_languages) 
            ? restaurant.supported_languages 
            : ['mk', 'en', 'al'];

        const content = `
            <form id="hotItemsSettingsForm" class="space-y-6">
                <div class="grid grid-cols-1 gap-6">
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Hot Items Label</h3>
                        <div class="grid grid-cols-1 gap-4">
                            ${supportedLanguages.includes('mk') ? `
                            <div class="lang-field lang-field-mk">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Hot Items Label (Macedonian)</span>
                                    </span>
                                </label>
                                <input type="text" name="hot_items_label_mk" value="${restaurant.hot_items_label_mk || ''}"
                                       placeholder="Внесете име за популарни јадења"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            ` : ''}
                            ${supportedLanguages.includes('en') ? `
                            <div class="lang-field lang-field-en">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Hot Items Label (English)</span>
                                    </span>
                                </label>
                                <input type="text" name="hot_items_label_en" value="${restaurant.hot_items_label_en || ''}"
                                       placeholder="Enter hot items label"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            ` : ''}
                            ${supportedLanguages.includes('al') ? `
                            <div class="lang-field lang-field-al">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Hot Items Label (Albanian)</span>
                                    </span>
                                </label>
                                <input type="text" name="hot_items_label_al" value="${restaurant.hot_items_label_al || ''}"
                                       placeholder="Vendosni etiketën e artikujve të nxehtë"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            ` : ''}
                        </div>
                        <p class="text-sm text-gray-500 mt-2">Customize the label shown above hot items section in the live menu</p>
                    </div>
                    
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Hot Items Description</h3>
                        <div class="grid grid-cols-1 gap-4">
                            ${supportedLanguages.includes('mk') ? `
                            <div class="lang-field lang-field-mk">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇲🇰</span>
                                        <span>Hot Items Description (Macedonian)</span>
                                    </span>
                                </label>
                                <textarea name="hot_items_description_mk" rows="3"
                                       placeholder="Внесете опис за популарни јадења"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${restaurant.hot_items_description_mk || ''}</textarea>
                            </div>
                            ` : ''}
                            ${supportedLanguages.includes('en') ? `
                            <div class="lang-field lang-field-en">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇬🇧</span>
                                        <span>Hot Items Description (English)</span>
                                    </span>
                                </label>
                                <textarea name="hot_items_description_en" rows="3"
                                       placeholder="Enter hot items description"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${restaurant.hot_items_description_en || ''}</textarea>
                            </div>
                            ` : ''}
                            ${supportedLanguages.includes('al') ? `
                            <div class="lang-field lang-field-al">
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <span class="inline-flex items-center gap-1">
                                        <span>🇦🇱</span>
                                        <span>Hot Items Description (Albanian)</span>
                                    </span>
                                </label>
                                <textarea name="hot_items_description_al" rows="3"
                                       placeholder="Vendosni përshkrimin e artikujve të nxehtë"
                                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">${restaurant.hot_items_description_al || ''}</textarea>
                            </div>
                            ` : ''}
                        </div>
                        <p class="text-sm text-gray-500 mt-2">Add a description that will be shown above the hot items (optional)</p>
                    </div>
                </div>
                
                <div class="flex flex-col sm:flex-row justify-end gap-3 mt-6 pt-4 border-t">
                    <button type="button" onclick="dashboard.closeModal()" 
                            class="w-full sm:w-auto px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="w-full sm:w-auto px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                        Save Settings
                    </button>
                </div>
            </form>
        `;
        
        this.showModal('Edit Hot Items Settings', content);
        
        document.getElementById('hotItemsSettingsForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const submitButton = e.target.querySelector('button[type="submit"]');
            if (!this.preventDoubleSubmission('hotItemsSettingsForm', submitButton)) {
                return;
            }
            
            try {
                const formData = new FormData(e.target);
                const settingsData = {
                    hot_items_label_mk: formData.get('hot_items_label_mk') || '',
                    hot_items_label_en: formData.get('hot_items_label_en') || '',
                    hot_items_label_al: formData.get('hot_items_label_al') || '',
                    hot_items_description_mk: formData.get('hot_items_description_mk') || '',
                    hot_items_description_en: formData.get('hot_items_description_en') || '',
                    hot_items_description_al: formData.get('hot_items_description_al') || ''
                };

                const response = await axios.put(`/api/admin/restaurants/${this.currentRestaurantId}/hot-items-settings`, settingsData);

                if (response.data.success) {
                    this.closeModal();
                    await this.loadRestaurantData(this.currentRestaurantId);
                    this.render();
                    alert('Hot Items settings updated successfully!');
                }
            } catch (error) {
                console.error('Error saving hot items settings:', error);
                alert('Error saving settings. Please try again.');
            } finally {
                this.restoreSubmissionState('hotItemsSettingsForm', submitButton);
            }
        });
    }

    // Load themes for restaurant form
    async loadThemesForForm(selectedThemeId = null) {
        try {
            const response = await axios.get('/api/themes');
            const themes = response.data.data;
            
            const themeSelector = document.getElementById('themeSelector');
            if (!themeSelector) return;
            
            // Build options HTML
            let optionsHTML = '<option value="">Default Theme</option>';
            themes.forEach(theme => {
                const selected = (selectedThemeId && selectedThemeId == theme.id) ? 'selected' : '';
                optionsHTML += `<option value="${theme.id}" ${selected}>${theme.name}</option>`;
            });
            
            themeSelector.innerHTML = optionsHTML;
        } catch (error) {
            console.error('Error loading themes:', error);
            const themeSelector = document.getElementById('themeSelector');
            if (themeSelector) {
                themeSelector.innerHTML = '<option value="">Error loading themes</option>';
            }
        }
    }

    setupLanguageFieldToggle() {
        // Get all language checkboxes
        const languageCheckboxes = document.querySelectorAll('.language-checkbox');
        const updateFieldVisibility = () => {
            // Get selected languages
            const selectedLanguages = Array.from(languageCheckboxes)
                .filter(cb => cb.checked)
                .map(cb => cb.value);
            
            // Show/hide language fields based on selection
            const allLangFields = document.querySelectorAll('.lang-field');
            allLangFields.forEach(field => {
                const langCode = field.className.match(/lang-field-(\w+)/)?.[1];
                if (langCode) {
                    if (selectedLanguages.includes(langCode)) {
                        field.style.display = '';
                        // Remove required attribute if hidden
                        const inputs = field.querySelectorAll('input, textarea');
                        inputs.forEach(input => {
                            if (input.dataset.originalRequired !== undefined) {
                                input.required = input.dataset.originalRequired === 'true';
                            }
                        });
                    } else {
                        field.style.display = 'none';
                        // Store original required state and remove required
                        const inputs = field.querySelectorAll('input, textarea');
                        inputs.forEach(input => {
                            if (input.dataset.originalRequired === undefined) {
                                input.dataset.originalRequired = input.required.toString();
                            }
                            input.required = false;
                        });
                    }
                }
            });

            // Ensure at least one language is selected
            if (selectedLanguages.length === 0) {
                // Default to showing all fields if none selected
                allLangFields.forEach(field => {
                    field.style.display = '';
                });
            }
        };

        // Add event listeners to checkboxes
        languageCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', updateFieldVisibility);
        });

        // Initial update
        updateFieldVisibility();
    }
}

// Helper function to show/hide language fields based on restaurant's supported languages
function checkAndDisplayAlbanianFields(restaurantId, dashboard) {
    if (!dashboard || !dashboard.restaurants || !restaurantId) return;
    
    const restaurant = dashboard.restaurants.find(r => r.id === restaurantId);
    if (!restaurant || !restaurant.supported_languages) return;
    
    const supportedLanguages = Array.isArray(restaurant.supported_languages) 
        ? restaurant.supported_languages 
        : ['mk', 'en', 'al']; // Default to all languages if not specified
    
    // Define field mappings for each language
    const languageFields = {
        'mk': [
            'menuItemMacedonianNameField',
            'menuItemMacedonianDescField',
            'menuItemMacedonianAllergensField',
            'typeMacedonianNameField',
            'categoryMacedonianNameField',
            'categoryMacedonianDescField',
            'promotionMacedonianNameField',
            'promotionMacedonianDescField',
            'celebrationMenuMacedonianNameField',
            'editCelebrationMenuNameMk',
            'editCelebrationMenuDescMk'
        ],
        'en': [
            'menuItemEnglishNameField',
            'menuItemEnglishDescField',
            'menuItemEnglishAllergensField',
            'typeEnglishNameField',
            'categoryEnglishNameField',
            'categoryEnglishDescField',
            'promotionEnglishNameField',
            'promotionEnglishDescField',
            'celebrationMenuEnglishNameField',
            'editCelebrationMenuNameEn',
            'editCelebrationMenuDescEn'
        ],
        'al': [
            'menuItemAlbanianNameField',
            'menuItemAlbanianDescField',
            'menuItemAlbanianAllergensField',
            'typeAlbanianNameField',
            'categoryAlbanianNameField',
            'categoryAlbanianDescField',
            'promotionAlbanianNameField',
            'promotionAlbanianDescField',
            'celebrationMenuAlbanianNameField',
            'editCelebrationMenuNameAl',
            'editCelebrationMenuDescAl'
        ]
    };
    
    // Also handle fields with lang-field-* classes
    const langFieldClasses = ['lang-field-mk', 'lang-field-en', 'lang-field-al'];
    const langCodes = ['mk', 'en', 'al'];
    
    langFieldClasses.forEach((className, index) => {
        const langCode = langCodes[index];
        const shouldShow = supportedLanguages.includes(langCode);
        
        const fields = document.querySelectorAll(`.${className}`);
        fields.forEach(field => {
            if (field) {
                field.style.display = shouldShow ? '' : 'none';
                // Remove required attribute if hidden
                if (!shouldShow) {
                    const inputs = field.querySelectorAll('input, textarea');
                    inputs.forEach(input => {
                        input.required = false;
                        // Also clear the value to prevent validation issues
                        if (!input.value || input.value.trim() === '') {
                            input.value = '';
                        }
                    });
                }
            }
        });
    });
    
    // Handle individual field IDs
    Object.keys(languageFields).forEach(langCode => {
        const shouldShow = supportedLanguages.includes(langCode);
        const fields = languageFields[langCode];
        
        fields.forEach(fieldId => {
            const field = document.getElementById(fieldId);
            if (field) {
                field.style.display = shouldShow ? '' : 'none';
                // Remove required attribute if hidden
                if (!shouldShow) {
                    const inputs = field.querySelectorAll('input, textarea');
                    inputs.forEach(input => {
                        input.required = false;
                        // Also clear the value to prevent validation issues
                        if (!input.value || input.value.trim() === '') {
                            input.value = '';
                        }
                    });
                }
            }
        });
    });
}

document.addEventListener('DOMContentLoaded', () => {
    window.dashboard = new AdminDashboard();
    window.checkAndDisplayAlbanianFields = checkAndDisplayAlbanianFields;
});