/**
 * Orders Management JavaScript
 * Handles loading, displaying, and managing dental orders with advanced filtering and pagination
 */

class OrdersManager {
    constructor() {
        this.orders = [];
        this.isLoading = false;
        this.currentPage = 0;
        this.hasMore = true;
        this.currentFilters = {
            search: '',
            service_types: '',
            status: '',
            // date_from: '',
            // date_to: ''
        };
        this.currentSort = {
            field: 'created_at',
            order: 'DESC'
        };
        this.searchTimeout = null;
        this.init();
    }

    init() {
        // Check if localization is available
        if (typeof ordersLocalization === 'undefined') {
            return;
        }
        
        // Check if we're on the orders page
        const ordersTable = document.getElementById('orders-table');
        if (!ordersTable) {
            return;
        }
        
        this.bindEvents();
        
        // Initialize active filters display (should be empty initially)
        this.updateActiveFilters();
        this.updateClearFiltersButton();
        

        
        // Only load orders if we're on the orders section
        const ordersSection = document.getElementById('orders-section');
        if (ordersSection && ordersSection.classList.contains('active')) {
            this.loadOrders(true); // Initial load
        }
        
        // Watch for changes to the orders section
        this.observeOrdersSection();
        
        // Initialize sort indicators
        this.updateSortIndicators();
    }
    
    /**
     * Observe orders section for changes
     */
    observeOrdersSection() {
        const ordersSection = document.getElementById('orders-section');
        if (!ordersSection) return;
        
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                    if (ordersSection.classList.contains('active')) {
                        this.loadOrders(true);
                    }
                }
            });
        });
        
        observer.observe(ordersSection, {
            attributes: true,
            attributeFilter: ['class']
        });
    }

    bindEvents() {
        // Navigation to orders section
        const ordersNavLink = document.querySelector('a[data-section="orders"]');
        if (ordersNavLink) {
            ordersNavLink.addEventListener('click', () => {
                this.loadOrders(true);
            });
        }
        
        // Filter toggle functionality
        const filterToggle = document.getElementById('filter-toggle');
        if (filterToggle) {
            filterToggle.addEventListener('click', () => this.toggleFilter());
        }
        
        // Clear filters button
        const clearFilters = document.getElementById('clear-filters');
        if (clearFilters) {
            clearFilters.addEventListener('click', () => this.clearAllFilters());
        }

        // Search filter with debouncing
        const searchFilter = document.getElementById('search-filter');
        if (searchFilter) {
            searchFilter.addEventListener('input', (e) => this.handleSearchInput(e.target.value));
        }

        // Service type filter
        const serviceTypeFilter = document.getElementById('service-type-filter');
        if (serviceTypeFilter) {
            serviceTypeFilter.addEventListener('change', () => this.handleServiceTypeChange());
        }

        // Status filter
        const statusFilter = document.getElementById('status-filter');
        if (statusFilter) {
            statusFilter.addEventListener('change', () => this.handleStatusChange());
        }

        // Sortable table headers
        const sortableHeaders = document.querySelectorAll('th.sortable');
        sortableHeaders.forEach(header => {
            header.addEventListener('click', () => this.handleSort(header.dataset.sort));
        });

        // Infinite scroll
        window.addEventListener('scroll', () => this.handleScroll());
        
    }

    /**
     * Handle search input with debouncing
     */
    handleSearchInput(value) {
        // Clear previous timeout
        if (this.searchTimeout) {
            clearTimeout(this.searchTimeout);
        }

        // Set new timeout for search
        this.searchTimeout = setTimeout(() => {
            this.currentFilters.search = value;
            this.loadOrders(true);
        }, 500); // 500ms delay
    }

    /**
     * Handle service type filter changes
     */
    handleServiceTypeChange() {
        const serviceTypeFilter = document.getElementById('service-type-filter');
        const selectedValue = serviceTypeFilter.value;
        
        this.currentFilters.service_types = selectedValue || '';
        
        this.loadOrders(true);
    }

    /**
     * Handle status filter changes
     */
    handleStatusChange() {
        const statusFilter = document.getElementById('status-filter');
        this.currentFilters.status = statusFilter.value;
        this.loadOrders(true);
    }

    /**
     * Handle table sorting
     */
    handleSort(field) {
        // Toggle sort order if same field
        if (this.currentSort.field === field) {
            this.currentSort.order = this.currentSort.order === 'ASC' ? 'DESC' : 'ASC';
        } else {
            this.currentSort.field = field;
            this.currentSort.order = 'ASC'; // Start with ASC for new fields
        }

        // Update sort indicators
        this.updateSortIndicators();

        // Reload orders with new sorting
        this.loadOrders(true);
    }

    /**
     * Update sort indicators in table headers
     */
    updateSortIndicators() {
        const sortableHeaders = document.querySelectorAll('th.sortable');
        sortableHeaders.forEach(header => {
            const field = header.dataset.sort;
            const icon = header.querySelector('.sort-icon');
            
            // Remove all sort state classes
            header.classList.remove('asc', 'desc');
            
            // Reset icon to default sort state
            if (icon) {
                icon.className = 'sort-icon fi-tr-sort-alt';
            }
            
            // Add current sort state
            if (field === this.currentSort.field) {
                header.classList.add(this.currentSort.order.toLowerCase());
                
                // Update icon based on sort direction
                if (icon) {
                    if (this.currentSort.order === 'ASC') {
                        icon.className = 'sort-icon fi-tr-sort-alpha-down';
                    } else {
                        icon.className = 'sort-icon fi-tr-sort-alpha-up-alt';
                    }
                }
            }
        });
    }

    /**
     * Handle infinite scroll
     */
    handleScroll() {
        if (this.isLoading || !this.hasMore) return;

        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const windowHeight = window.innerHeight;
        const documentHeight = document.documentElement.scrollHeight;

        // Load more when user is near bottom
        if (scrollTop + windowHeight >= documentHeight - 100) {
            this.loadOrders(false); // Load more without resetting
        }
    }

    /**
     * Load orders from server
     */
    async loadOrders(reset = false) {
        if (this.isLoading) return;

        if (reset) {
            this.currentPage = 0;
            this.orders = [];
            this.hasMore = true;
        }

        this.setLoadingState(true);
        
        try {
            const response = await this.fetchOrders();
            
            if (response.success) {
                if (reset) {
                    this.orders = response.data || [];
                } else {
                    this.orders = [...this.orders, ...(response.data || [])];
                }
                
                this.hasMore = response.has_more;
                this.currentPage++;
                
                this.displayOrders();
                this.updateActiveFilters();
                this.updateClearFiltersButton();
            } else {
                this.showError('خطا در بارگذاری سفارشات: ' + (response.message || 'خطای نامشخص'));
            }
        } catch (error) {
            console.error('Error loading orders:', error);
            this.showError('خطا در ارتباط با سرور: ' + error.message);
        } finally {
            this.setLoadingState(false);
        }
    }

    /**
     * Fetch orders from server via AJAX
     */
    async fetchOrders() {
        try {
            const formData = new FormData();
            formData.append('action', 'get_user_dental_orders');
            formData.append('nonce', ordersLocalization.nonce);
            formData.append('limit', 15);
            formData.append('offset', this.currentPage * 15);
            formData.append('search', this.currentFilters.search);
            formData.append('service_types', this.currentFilters.service_types);
            formData.append('status', this.currentFilters.status);
            // ! formData.append('date_from', this.currentFilters.date_from);
            // ! formData.append('date_to', this.currentFilters.date_to);
            formData.append('sort_by', this.currentSort.field);
            formData.append('sort_order', this.currentSort.order);

            const response = await fetch(ordersLocalization.ajaxUrl, {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const responseData = await response.json();
            return responseData;
        } catch (error) {
            console.error('Error in fetchOrders:', error);
            throw error;
        }
    }

    /**
     * Display orders in the table
     */
    displayOrders() {
        const tableBody = document.getElementById('orders-table-body');
        const emptyState = document.getElementById('orders-empty');
        const table = document.getElementById('orders-table');

        if (!tableBody) return;

        // Clear existing content
        tableBody.innerHTML = '';

        if (this.orders.length === 0) {
            this.showEmptyState();
            return;
        }

        // Hide empty state and show table
        if (emptyState) emptyState.style.display = 'none';
        if (table) table.style.display = 'table';

        // Create table rows
        this.orders.forEach(order => {
            const row = this.createOrderRow(order);
            tableBody.appendChild(row);
        });
    }

    /**
     * Create a table row for an order
     */
    createOrderRow(order) {
        const row = document.createElement('tr');
        row.className = 'order-row';
        row.setAttribute('data-order-id', order.dental_id);

        // Order ID column
        const idCell = document.createElement('td');
        idCell.className = 'order-id';
        idCell.textContent = order.dental_id;

        // Patient column
        const patientCell = document.createElement('td');
        patientCell.className = 'order-patient';
        patientCell.innerHTML = `<span class="patient-name">${order.patient_name}</span>`;

        // Service column
        const serviceCell = document.createElement('td');
        serviceCell.className = 'order-service';
        
        // Use translated service type from PHP if available, otherwise translate client-side
        const serviceTypeDisplay = order.service_type_display || this.getServiceTypeName(order.service_type || '');
        
        // Create service type with optional info icon
        let serviceTypeHtml = `<div class="service-type">${serviceTypeDisplay}</div>`;
        
        // Add info icon if order_note exists and has value
        if (order.order_note && order.order_note.trim() !== '') {
            serviceTypeHtml += `<i class="fi-tr-info order-note-icon" data-tooltip="${this.escapeHtml(order.order_note)}"></i>`;
        }
        
        // Use translated sub-services from PHP if available, otherwise format client-side
        let subServicesHtml = '';
        if (order.sub_services_display && Array.isArray(order.sub_services_display) && order.sub_services_display.length > 0) {
            // Use PHP-translated sub-services
            subServicesHtml = `<div class="sub-services">${order.sub_services_display.join(', ')}</div>`;
        } else if (order.sub_services && order.sub_services !== '[]' && order.sub_services !== 'null') {
            // Fallback to client-side formatting
            subServicesHtml = `<div class="sub-services">${this.formatSubServices(order.sub_services)}</div>`;
        }
        
        serviceCell.innerHTML = `
            ${serviceTypeHtml}
            ${subServicesHtml}
        `;

        // Date column
        const dateCell = document.createElement('td');
        dateCell.className = 'order-date';
        
        // Convert timestamp to Jalali/Shamsi using PersianDate library
        const jalaliDate = this.formatJalaliDate(order.timestamp);
        
        dateCell.innerHTML = `
            <div class="order-date-date">${jalaliDate}</div>
        `;

        // Status column
        const statusCell = document.createElement('td');
        statusCell.className = 'order-status';
        statusCell.innerHTML = `<span class="status-badge status-${order.status_class || 'pending'}">${order.status_display || 'نامشخص'}</span>`;

        // Append all cells to row
        row.appendChild(idCell);
        row.appendChild(patientCell);
        row.appendChild(serviceCell);
        row.appendChild(dateCell);
        row.appendChild(statusCell);

        // Add tooltip functionality for order note icons
        const noteIcon = serviceCell.querySelector('.order-note-icon');
        if (noteIcon) {
            this.setupTooltip(noteIcon);
        }

        return row;
    }

    /**
     * Update active filters display
     */
    updateActiveFilters() {
        const activeFiltersContainer = document.getElementById('active-filters');
        const activeFiltersList = document.getElementById('active-filters-list');
        
        if (!activeFiltersContainer || !activeFiltersList) return;

        // Clear existing active filters
        activeFiltersList.innerHTML = '';

        let hasActiveFilters = false;
        
        // Helper function to check if a filter has a meaningful value
        const hasValue = (value) => value && value.toString().trim() !== '';

        // Search filter
        if (hasValue(this.currentFilters.search)) {
            this.addActiveFilterTag('جستجو', this.currentFilters.search, 'search');
            hasActiveFilters = true;
        }

        // Service type filter
        if (hasValue(this.currentFilters.service_types)) {
            const serviceName = this.getServiceTypeName(this.currentFilters.service_types);
            this.addActiveFilterTag('نوع خدمات', serviceName, 'service_types');
            hasActiveFilters = true;
        }

        // Status filter
        if (hasValue(this.currentFilters.status)) {
            const statusName = this.getStatusDisplayName(this.currentFilters.status);
            this.addActiveFilterTag('وضعیت', statusName, 'status');
            hasActiveFilters = true;
        }

        // Date filters
        // ! Date filters are disabled for now
        // if (hasValue(this.currentFilters.date_from) || hasValue(this.currentFilters.date_to)) {
        //     let dateText = '';
        //     if (hasValue(this.currentFilters.date_from) && hasValue(this.currentFilters.date_to)) {
        //         dateText = `${this.currentFilters.date_from} تا ${this.currentFilters.date_to}`;
        //     } else if (hasValue(this.currentFilters.date_from)) {
        //         dateText = `از ${this.currentFilters.date_from}`;
        //     } else if (hasValue(this.currentFilters.date_to)) {
        //         dateText = `تا ${this.currentFilters.date_to}`;
        //     }
        //     this.addActiveFilterTag('تاریخ', dateText, 'date');
        //     hasActiveFilters = true;
        // }

        // Sorting filter (only show if not default)
        if (this.currentSort.field !== 'created_at' || this.currentSort.order !== 'DESC') {
            const sortFieldName = this.getSortFieldDisplayName(this.currentSort.field);
            const sortDirectionName = this.currentSort.order === 'ASC' ? 'صعودی' : 'نزولی';
            this.addActiveFilterTag('مرتب‌سازی', `${sortFieldName} (${sortDirectionName})`, 'sort');
            hasActiveFilters = true;
        }

        // Show/hide active filters container
        activeFiltersContainer.style.display = hasActiveFilters ? 'block' : 'none';
    }

    /**
     * Add an active filter tag
     */
    addActiveFilterTag(label, value, filterType) {
        const activeFiltersList = document.getElementById('active-filters-list');
        if (!activeFiltersList) return;

        const filterTag = document.createElement('div');
        filterTag.className = 'active-filter-tag';
        filterTag.innerHTML = `
            <span class="filter-label">${label}:</span>
            <span class="filter-value" data-filter-type="${filterType}">
                ${value}
                <span class="remove-icon">×</span>
            </span>
        `;

        // Add click event to remove filter (clicking on the value)
        const filterValue = filterTag.querySelector('.filter-value');
        filterValue.addEventListener('click', (e) => {
            e.stopPropagation();
            this.removeFilter(filterType);
        });

        activeFiltersList.appendChild(filterTag);
    }

    /**
     * Remove a specific filter
     */
    removeFilter(filterType) {
        switch (filterType) {
            case 'search':
                this.currentFilters.search = '';
                document.getElementById('search-filter').value = '';
                break;
            case 'service_types':
                this.currentFilters.service_types = '';
                const serviceTypeFilter = document.getElementById('service-type-filter');
                if (serviceTypeFilter) serviceTypeFilter.value = '';
                break;
            case 'status':
                this.currentFilters.status = '';
                document.getElementById('status-filter').value = '';
                break;
            case 'date':
                // this.currentFilters.date_from = '';
                // this.currentFilters.date_to = '';
                break;
            case 'sort':
                // Reset to default sorting
                this.currentSort.field = 'created_at';
                this.currentSort.order = 'DESC';
                this.updateSortIndicators();
                break;
        }

        this.loadOrders(true);
    }

    /**
     * Clear all filters
     */
    clearAllFilters() {
        // Reset search
        this.currentFilters.search = '';
        const searchFilter = document.getElementById('search-filter');
        if (searchFilter) searchFilter.value = '';

        // Reset service types
        this.currentFilters.service_types = '';
        const serviceTypeFilter = document.getElementById('service-type-filter');
        if (serviceTypeFilter) serviceTypeFilter.value = '';

        // Reset status
        this.currentFilters.status = '';
        const statusFilter = document.getElementById('status-filter');
        if (statusFilter) statusFilter.value = '';

        // Reset dates
        // ! Date filters are disabled for now
        // this.currentFilters.date_from = '';
        // this.currentFilters.date_to = '';
        
        // Clear date input
        // ! Date filters are disabled for now
        // const dateInput = document.getElementById('date-range-input');
        // if (dateInput) {
        //     dateInput.value = '';
        // }

        // Reset sorting
        this.currentSort.field = 'created_at';
        this.currentSort.order = 'DESC';
        this.updateSortIndicators();

        // Reload orders
        this.loadOrders(true);
    }

    /**
     * Update clear filters button visibility
     */
    updateClearFiltersButton() {
        const clearBtn = document.getElementById('clear-filters');
        if (!clearBtn) return;

        // Helper function to check if a filter has a meaningful value
        const hasValue = (value) => value && value.toString().trim() !== '';
        
        const hasActiveFilters = hasValue(this.currentFilters.search) || 
                               hasValue(this.currentFilters.service_types) || 
                               hasValue(this.currentFilters.status) || 
                            // !   hasValue(this.currentFilters.date_from) || 
                            // !  hasValue(this.currentFilters.date_to) ||
                               (this.currentSort.field !== 'created_at' || this.currentSort.order !== 'DESC');

        clearBtn.style.display = hasActiveFilters ? 'inline-flex' : 'none';
    }

    /**
     * Get service type display name
     */
    getServiceTypeName(serviceType) {
        const serviceNames = {
            'orthodontics': 'ارتودنسی',
            'fixed_prosthesis': 'پروتز ثابت',
            'removable_prosthesis': 'پروتز متحرک'
        };
        return serviceNames[serviceType] || serviceType;
    }

    /**
     * Get status display name
     */
    getStatusDisplayName(status) {
        const statusNames = {
            'pending': 'در انتظار تأیید',
            'in_progress': 'در حال انجام',
            'completed': 'تکمیل شده',
            'cancelled': 'لغو شده'
        };
        return statusNames[status] || status;
    }

    /**
     * Get sort field display name
     */
    getSortFieldDisplayName(field) {
        const fieldNames = {
            'dental_id': 'شماره سفارش',
            'service_type': 'نوع خدمات',
            'created_at': 'تاریخ ایجاد',
            'patient_name': 'نام بیمار',
            'author_id': 'کاربر'
        };
        return fieldNames[field] || field;
    }

    /**
     * Escape HTML for safe tooltip display
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * Setup tooltip for order note icons
     */
    setupTooltip(icon) {
        const tooltipText = icon.dataset.tooltip;
        if (!tooltipText) return;

        // Create tooltip element
        const tooltip = document.createElement('div');
        tooltip.className = 'custom-tooltip';
        tooltip.textContent = tooltipText;
        document.body.appendChild(tooltip);

        // Show tooltip on mouse enter
        icon.addEventListener('mouseenter', (e) => {
            this.showTooltip(tooltip, e);
        });

        // Hide tooltip on mouse leave
        icon.addEventListener('mouseleave', () => {
            this.hideTooltip(tooltip);
        });

        // Store tooltip reference
        icon.tooltip = tooltip;
    }

    /**
     * Show tooltip at the correct position
     */
    showTooltip(tooltip, event) {
        const icon = event.target;
        const iconRect = icon.getBoundingClientRect();
        const tooltipRect = tooltip.getBoundingClientRect();
        
        // Position tooltip above the icon
        let left = iconRect.left + (iconRect.width / 2) - (tooltipRect.width / 2);
        let top = iconRect.top - tooltipRect.height - 10;
        
        // Ensure tooltip doesn't go off-screen
        if (left < 10) left = 10;
        if (left + tooltipRect.width > window.innerWidth - 10) {
            left = window.innerWidth - tooltipRect.width - 10;
        }
        if (top < 10) {
            // If above doesn't fit, show below
            top = iconRect.bottom + 10;
        }
        
        tooltip.style.left = left + 'px';
        tooltip.style.top = top + 'px';
        tooltip.style.opacity = '1';
        tooltip.style.visibility = 'visible';
    }

    /**
     * Hide tooltip
     */
    hideTooltip(tooltip) {
        tooltip.style.opacity = '0';
        tooltip.style.visibility = 'hidden';
    }

    /**
     * Format sub-services for display
     * Note: This function is kept for backward compatibility and fallback cases.
     * The PHP backend now provides translated sub_services_display array.
     */
    formatSubServices(subServices) {
        try {
            const services = JSON.parse(subServices);
            if (Array.isArray(services)) {
                // Try to translate each service (fallback for cases where PHP translation wasn't available)
                const translatedServices = services.map(service => {
                    // Use a simple mapping for common sub-services (fallback only)
                    const subServiceNames = {
                        'clear_aligner': 'ارتودنسی شفاف',
                        'orthodontic_retainer': 'پلاک ارتودنسی',
                        'orthognathic_surgery': 'ارتو سرجری',
                        'diagnosis_analysis': 'آنالیز و تشخیص',
                        'crown': 'روکش',
                        'abutment': 'اباتمنت',
                        'laminate': 'لمینت',
                        'substructure': 'ساب استراکچر فیکس',
                        'composite_restoration': 'ایندایرکت کامپوزیت رستوریشن',
                        'smile_design': 'طراحی لبخند',
                        'denture': 'دنچر',
                        'partial': 'پارسیل',
                        // Add more as needed, but prefer PHP translations
                    };
                    return subServiceNames[service] || service;
                });
                return translatedServices.join(', ');
            }
        } catch (e) {
            // Silent fail - return original value
        }
        return subServices || '';
    }

    /**
     * Convert timestamp to Jalali/Shamsi date
     */
    formatJalaliDate(timestamp) {
        if (!timestamp) return 'نامشخص';
        
        // Check if persianDate library is available
        if (typeof persianDate === 'undefined') {
            try {
                const georgianDate = new Date(timestamp * 1000);
                if (isNaN(georgianDate.getTime())) {
                    return 'نامشخص';
                }
                return georgianDate.toLocaleDateString('fa-IR');
            } catch (e) {
                return 'نامشخص';
            }
        }
        
        try {
            // Convert timestamp to Date object (multiply by 1000 if it's Unix timestamp)
            const georgianDate = new Date(timestamp * 1000);
            if (isNaN(georgianDate.getTime())) {
                return 'نامشخص';
            }
            
            const persianDateObj = new persianDate(georgianDate);
            return persianDateObj.format('YYYY/MM/DD');
        } catch (e) {
            return 'نامشخص';
        }
    }

    /**
     * Convert timestamp to Jalali/Shamsi date with time
     */
    formatJalaliDateTime(timestamp) {
        if (!timestamp) return 'نامشخص';
        
        // Check if persianDate library is available
        if (typeof persianDate === 'undefined') {
            try {
                const georgianDate = new Date(timestamp * 1000);
                if (isNaN(georgianDate.getTime())) {
                    return 'نامشخص';
                }
                return georgianDate.toLocaleDateString('fa-IR') + ' ' + georgianDate.toLocaleTimeString('fa-IR');
            } catch (e) {
                return 'نامشخص';
            }
        }
        
        try {
            // Convert timestamp to Date object (multiply by 1000 if it's Unix timestamp)
            const georgianDate = new Date(timestamp * 1000);
            if (isNaN(georgianDate.getTime())) {
                return 'نامشخص';
            }
            
            const persianDateObj = new persianDate(georgianDate);
            return persianDateObj.format('YYYY/MM/DD HH:mm');
        } catch (e) {
            return 'نامشخص';
        }
    }

    /**
     * Set loading state
     */
    setLoadingState(loading) {
        this.isLoading = loading;
        
        const loadingEl = document.getElementById('orders-loading');
        const table = document.getElementById('orders-table');
        const emptyState = document.getElementById('orders-empty');

        if (loading) {
            if (loadingEl) loadingEl.style.display = 'flex';
            if (table) table.style.display = 'none';
            if (emptyState) emptyState.style.display = 'none';
        } else {
            if (loadingEl) loadingEl.style.display = 'none';
        }
    }

    /**
     * Show empty state
     */
    showEmptyState() {
        const table = document.getElementById('orders-table');
        const emptyState = document.getElementById('orders-empty');
        
        if (table) table.style.display = 'none';
        if (emptyState) emptyState.style.display = 'flex';
    }

    /**
     * Show error message
     */
    showError(message) {
        const emptyState = document.getElementById('orders-empty');
        if (emptyState) {
            emptyState.innerHTML = `
                <i class="bi bi-exclamation-triangle" style="color: #f44336;"></i>
                <p style="color: #f44336;">${message}</p>
                <button type="button" class="btn btn-primary" onclick="ordersManager.loadOrders(true)">
                    تلاش مجدد
                </button>
            `;
            emptyState.style.display = 'flex';
        }
    }

    /**
     * Toggle filter section visibility
     */
    toggleFilter() {
        const filterToggle = document.getElementById('filter-toggle');
        const filterContent = document.getElementById('filter-content');
        
        if (filterContent.classList.contains('expanded')) {
            // Collapse filter
            filterContent.classList.remove('expanded');
            filterToggle.classList.remove('active');
            filterToggle.querySelector('.filter-text').textContent = 'نمایش فیلتر';
        } else {
            // Expand filter
            filterContent.classList.add('expanded');
            filterToggle.classList.add('active');
            filterToggle.querySelector('.filter-text').textContent = 'مخفی کردن فیلتر';
        }
    }

    /**
     * Get order by ID
     */
    getOrderById(orderId) {
        return this.orders.find(order => order.dental_id === orderId);
    }

    /**
     * Update order status (for future use)
     */
    updateOrderStatus(orderId, newStatus) {
        const order = this.getOrderById(orderId);
        if (order) {
            order.dental_status = newStatus;
            order.status_display = this.getStatusDisplayName(newStatus);
            this.displayOrders();
        }
    }

    /**
     * Cleanup tooltips when component is destroyed
     */
    cleanup() {
        // Remove all tooltips from DOM
        const tooltips = document.querySelectorAll('.custom-tooltip');
        tooltips.forEach(tooltip => tooltip.remove());
    }


}

// Initialize orders manager when DOM is ready
let ordersManager;

document.addEventListener('DOMContentLoaded', function() {
    // Check if we're on the dashboard page
    if (document.getElementById('orders-table')) {
        ordersManager = new OrdersManager();
    }
});

// Export for global access
if (typeof window !== 'undefined') {
    window.ordersManager = ordersManager;
}
