/**
 * Recora Admin Panel JavaScript
 */

document.addEventListener('DOMContentLoaded', function() {
    // Initialize all components
    initializeSidebar();
    initializeToasts();
    initializeModals();
    initializeDataTables();
    initializeCharts();
});

/**
 * Sidebar functionality
 */
function initializeSidebar() {
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    const sidebar = document.querySelector('.sidebar');
    
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('active');
        });
        
        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function(e) {
            if (window.innerWidth <= 1024) {
                if (!sidebar.contains(e.target) && !sidebarToggle.contains(e.target)) {
                    sidebar.classList.remove('active');
                }
            }
        });
    }
}

/**
 * Toast notification system
 */
function initializeToasts() {
    window.showToast = function(message, type = 'info', duration = 5000) {
        const container = document.getElementById('toastContainer') || createToastContainer();
        
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        
        const icon = getToastIcon(type);
        
        toast.innerHTML = `
            <div class="toast-icon">${icon}</div>
            <div class="toast-content">
                <p>${message}</p>
            </div>
            <button class="toast-close" onclick="this.parentElement.remove()">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        container.appendChild(toast);
        
        // Auto remove
        setTimeout(() => {
            if (toast.parentElement) {
                toast.remove();
            }
        }, duration);
    };
    
    function createToastContainer() {
        const container = document.createElement('div');
        container.id = 'toastContainer';
        container.className = 'toast-container';
        document.body.appendChild(container);
        return container;
    }
    
    function getToastIcon(type) {
        const icons = {
            success: '<i class="fas fa-check-circle" style="color: #059669;"></i>',
            error: '<i class="fas fa-exclamation-circle" style="color: #dc2626;"></i>',
            warning: '<i class="fas fa-exclamation-triangle" style="color: #f59e0b;"></i>',
            info: '<i class="fas fa-info-circle" style="color: #3b82f6;"></i>'
        };
        return icons[type] || icons.info;
    }
}

/**
 * Modal functionality
 */
function initializeModals() {
    // Modal open/close functionality
    window.openModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
    };
    
    window.closeModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.style.display = 'none';
            document.body.style.overflow = 'auto';
        }
    };
    
    // Close modal when clicking outside
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal-overlay')) {
            e.target.style.display = 'none';
            document.body.style.overflow = 'auto';
        }
    });
    
    // Close modal with escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const modals = document.querySelectorAll('.modal-overlay[style*="flex"]');
            modals.forEach(modal => {
                modal.style.display = 'none';
            });
            document.body.style.overflow = 'auto';
        }
    });
}

/**
 * Data table functionality
 */
function initializeDataTables() {
    // Search functionality
    const searchInputs = document.querySelectorAll('.search-input');
    searchInputs.forEach(input => {
        input.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const table = this.closest('.table-container').querySelector('table');
            const rows = table.querySelectorAll('tbody tr');
            
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(searchTerm) ? '' : 'none';
            });
        });
    });
    
    // Filter functionality
    const filterSelects = document.querySelectorAll('.filter-select');
    filterSelects.forEach(select => {
        select.addEventListener('change', function() {
            const filterValue = this.value;
            const table = this.closest('.table-container').querySelector('table');
            const rows = table.querySelectorAll('tbody tr');
            
            rows.forEach(row => {
                if (!filterValue) {
                    row.style.display = '';
                } else {
                    const text = row.textContent.toLowerCase();
                    row.style.display = text.includes(filterValue.toLowerCase()) ? '' : 'none';
                }
            });
        });
    });
    
    // Sort functionality
    const sortableHeaders = document.querySelectorAll('th[data-sort]');
    sortableHeaders.forEach(header => {
        header.style.cursor = 'pointer';
        header.innerHTML += ' <i class="fas fa-sort sort-icon"></i>';
        
        header.addEventListener('click', function() {
            const column = this.dataset.sort;
            const table = this.closest('table');
            const tbody = table.querySelector('tbody');
            const rows = Array.from(tbody.querySelectorAll('tr'));
            
            const isAscending = !this.classList.contains('sort-asc');
            
            // Remove sort classes from all headers
            sortableHeaders.forEach(h => h.classList.remove('sort-asc', 'sort-desc'));
            
            // Add sort class to current header
            this.classList.add(isAscending ? 'sort-asc' : 'sort-desc');
            
            rows.sort((a, b) => {
                const aValue = a.children[this.cellIndex].textContent.trim();
                const bValue = b.children[this.cellIndex].textContent.trim();
                
                return isAscending ? 
                    aValue.localeCompare(bValue, undefined, {numeric: true}) :
                    bValue.localeCompare(aValue, undefined, {numeric: true});
            });
            
            rows.forEach(row => tbody.appendChild(row));
        });
    });
}

/**
 * Chart initialization
 */
function initializeCharts() {
    // Set default Chart.js configuration
    if (typeof Chart !== 'undefined') {
        Chart.defaults.font.family = 'Inter';
        Chart.defaults.color = '#6b7280';
    }
}

/**
 * Loading overlay
 */
function showLoading() {
    const overlay = document.getElementById('loadingOverlay');
    if (overlay) {
        overlay.style.display = 'flex';
    }
}

function hideLoading() {
    const overlay = document.getElementById('loadingOverlay');
    if (overlay) {
        overlay.style.display = 'none';
    }
}

/**
 * API Helper functions
 */
class AdminAPI {
    static async request(url, options = {}) {
        const defaults = {
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        };
        
        const config = { ...defaults, ...options };
        
        try {
            showLoading();
            const response = await fetch(url, config);
            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.message || 'Request failed');
            }
            
            return data;
        } catch (error) {
            showToast(error.message, 'error');
            throw error;
        } finally {
            hideLoading();
        }
    }
    
    static async get(url) {
        return this.request(url, { method: 'GET' });
    }
    
    static async post(url, data) {
        return this.request(url, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }
    
    static async put(url, data) {
        return this.request(url, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }
    
    static async delete(url) {
        return this.request(url, { method: 'DELETE' });
    }
}

/**
 * Form handling
 */
function initializeForms() {
    const forms = document.querySelectorAll('form[data-ajax]');
    
    forms.forEach(form => {
        form.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = Object.fromEntries(formData.entries());
            const url = this.action || this.dataset.url;
            const method = this.method || 'POST';
            
            try {
                const response = await AdminAPI.request(url, {
                    method: method.toUpperCase(),
                    body: JSON.stringify(data)
                });
                
                if (response.success) {
                    showToast(response.message || 'Operation completed successfully', 'success');
                    
                    // Close modal if form is in modal
                    const modal = this.closest('.modal-overlay');
                    if (modal) {
                        closeModal(modal.id);
                    }
                    
                    // Refresh page or redirect
                    if (response.redirect) {
                        window.location.href = response.redirect;
                    } else if (response.refresh) {
                        window.location.reload();
                    }
                } else {
                    showToast(response.message || 'Operation failed', 'error');
                }
            } catch (error) {
                showToast(error.message, 'error');
            }
        });
    });
}

/**
 * Confirmation dialogs
 */
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

/**
 * Delete action handler
 */
function handleDelete(url, itemName) {
    confirmAction(`Are you sure you want to delete ${itemName}? This action cannot be undone.`, async () => {
        try {
            const response = await AdminAPI.delete(url);
            if (response.success) {
                showToast(response.message || 'Item deleted successfully', 'success');
                window.location.reload();
            }
        } catch (error) {
            showToast(error.message, 'error');
        }
    });
}

/**
 * Utility functions
 */
function formatNumber(num) {
    if (num >= 1000000000) {
        return (num / 1000000000).toFixed(1) + 'B';
    } else if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
}

function formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

/**
 * Real-time updates
 */
function startRealTimeUpdates() {
    // Update every 30 seconds
    setInterval(async () => {
        try {
            const response = await AdminAPI.get('api/realtime-stats.php');
            if (response.success) {
                updateDashboardStats(response.data);
            }
        } catch (error) {
            console.error('Real-time update failed:', error);
        }
    }, 30000);
}

function updateDashboardStats(data) {
    // Update stat cards if they exist
    if (data.stats) {
        Object.keys(data.stats).forEach(key => {
            const element = document.querySelector(`[data-stat="${key}"]`);
            if (element) {
                element.textContent = formatNumber(data.stats[key]);
            }
        });
    }
}

/**
 * Export functionality
 */
function exportData(format, endpoint) {
    const url = `api/export.php?format=${format}&endpoint=${endpoint}`;
    window.open(url, '_blank');
}

// Initialize everything when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    initializeForms();
    
    // Start real-time updates if on dashboard
    if (window.location.search.includes('page=dashboard') || !window.location.search.includes('page=')) {
        startRealTimeUpdates();
    }
});

// Global error handler
window.addEventListener('error', function(e) {
    console.error('JavaScript error:', e.error);
    showToast('An unexpected error occurred. Please refresh the page.', 'error');
});

// Expose API to global scope for use in other scripts
window.AdminAPI = AdminAPI;
window.showToast = showToast;
window.showLoading = showLoading;
window.hideLoading = hideLoading;
