/**
 * Admin Dashboard JavaScript
 */

document.addEventListener('DOMContentLoaded', function() {
    initAdminFeatures();
});

/**
 * Initialize admin features
 */
function initAdminFeatures() {
    initMobileMenu();
    initSidebarToggle();
    initDataTables();
    initFormValidation();
    initConfirmDialogs();
    initAutoRefresh();
}

/**
 * Initialize mobile menu
 */
function initMobileMenu() {
    const mobileToggle = document.querySelector('.mobile-menu-toggle');
    const sidebar = document.querySelector('.admin-sidebar');
    
    if (mobileToggle && sidebar) {
        mobileToggle.addEventListener('click', function() {
            sidebar.classList.toggle('open');
        });
        
        // Close sidebar when clicking outside
        document.addEventListener('click', function(e) {
            if (!sidebar.contains(e.target) && !mobileToggle.contains(e.target)) {
                sidebar.classList.remove('open');
            }
        });
    }
}

/**
 * Initialize sidebar toggle functionality
 */
function initSidebarToggle() {
    const sidebar = document.querySelector('.admin-sidebar');
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    
    if (!sidebar || !sidebarToggle) return;
    
    // Load saved sidebar state
    loadSidebarState();
    
    // Add toggle button click handler
    sidebarToggle.addEventListener('click', function() {
        toggleSidebar();
    });
    
    // Add tooltips to nav items
    addTooltipsToNavItems();
    
    // Initialize user menu
    initUserMenu();
}

/**
 * Toggle sidebar collapsed state
 */
function toggleSidebar() {
    const sidebar = document.querySelector('.admin-sidebar');
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    
    if (!sidebar || !sidebarToggle) return;
    
    sidebar.classList.toggle('collapsed');
    
    // Update toggle button icon
    const icon = sidebarToggle.querySelector('i');
    if (sidebar.classList.contains('collapsed')) {
        icon.className = 'fas fa-chevron-right';
    } else {
        icon.className = 'fas fa-chevron-left';
    }
    
    // Save state
    saveSidebarState(sidebar.classList.contains('collapsed'));
}

/**
 * Save sidebar state to localStorage and server
 */
function saveSidebarState(isCollapsed) {
    // Save to localStorage for immediate use
    localStorage.setItem('sidebar_collapsed', isCollapsed ? 'true' : 'false');
    
    // Save to server for persistence across devices
    const userId = getCurrentUserId();
    if (userId) {
        fetch('api/save_sidebar_preference.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                user_id: userId,
                sidebar_collapsed: isCollapsed
            })
        }).catch(error => {
            console.error('Error saving sidebar preference:', error);
        });
    }
}

/**
 * Load sidebar state from localStorage
 */
function loadSidebarState() {
    const sidebar = document.querySelector('.admin-sidebar');
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    
    if (!sidebar || !sidebarToggle) return;
    
    // Check localStorage first
    const savedState = localStorage.getItem('sidebar_collapsed');
    const isCollapsed = savedState === 'true';
    
    if (isCollapsed) {
        sidebar.classList.add('collapsed');
        const icon = sidebarToggle.querySelector('i');
        if (icon) {
            icon.className = 'fas fa-chevron-right';
        }
    }
    
    // Load from server to sync across devices
    const userId = getCurrentUserId();
    if (userId) {
        fetch(`api/get_sidebar_preference.php?user_id=${userId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.sidebar_collapsed !== undefined) {
                    const serverCollapsed = data.sidebar_collapsed;
                    const currentCollapsed = sidebar.classList.contains('collapsed');
                    
                    if (serverCollapsed !== currentCollapsed) {
                        toggleSidebar();
                    }
                }
            })
            .catch(error => {
                console.error('Error loading sidebar preference:', error);
            });
    }
}

/**
 * Add tooltips to navigation items
 */
function addTooltipsToNavItems() {
    const navItems = document.querySelectorAll('.nav-item');
    
    navItems.forEach(item => {
        const span = item.querySelector('span');
        if (span) {
            item.setAttribute('data-tooltip', span.textContent.trim());
        }
    });
}

/**
 * Get current user ID from session or data attribute
 */
function getCurrentUserId() {
    // Try to get from data attribute on body
    const body = document.body;
    if (body && body.dataset.userId) {
        return body.dataset.userId;
    }
    
    // Try to get from global variable if available
    if (typeof window.currentUserId !== 'undefined') {
        return window.currentUserId;
    }
    
    return null;
}

/**
 * Initialize user menu functionality
 */
function initUserMenu() {
    const userMenuToggle = document.querySelector('.user-menu-toggle');
    const userMenu = document.querySelector('.user-menu');
    
    if (!userMenuToggle || !userMenu) return;
    
    userMenuToggle.addEventListener('click', function(e) {
        e.stopPropagation();
        userMenu.classList.toggle('open');
    });
    
    // Close user menu when clicking outside
    document.addEventListener('click', function(e) {
        if (!userMenu.contains(e.target)) {
            userMenu.classList.remove('open');
        }
    });
    
    // Close user menu when clicking on dropdown items
    const dropdownItems = userMenu.querySelectorAll('.user-dropdown-item');
    dropdownItems.forEach(item => {
        item.addEventListener('click', function() {
            userMenu.classList.remove('open');
        });
    });
}

/**
 * Initialize data tables
 */
function initDataTables() {
    const tables = document.querySelectorAll('table');
    
    tables.forEach(table => {
        // Add sorting functionality
        const headers = table.querySelectorAll('th[data-sort]');
        headers.forEach(header => {
            header.style.cursor = 'pointer';
            header.addEventListener('click', function() {
                sortTable(table, this.dataset.sort);
            });
        });
    });
}

/**
 * Sort table by column
 */
function sortTable(table, column) {
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const columnIndex = Array.from(table.querySelectorAll('th')).findIndex(th => th.dataset.sort === column);
    
    rows.sort((a, b) => {
        const aValue = a.cells[columnIndex].textContent.trim();
        const bValue = b.cells[columnIndex].textContent.trim();
        
        // Try to parse as numbers
        const aNum = parseFloat(aValue);
        const bNum = parseFloat(bValue);
        
        if (!isNaN(aNum) && !isNaN(bNum)) {
            return aNum - bNum;
        }
        
        return aValue.localeCompare(bValue);
    });
    
    rows.forEach(row => tbody.appendChild(row));
}

/**
 * Initialize form validation
 */
function initFormValidation() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!validateAdminForm(this)) {
                e.preventDefault();
            }
        });
    });
}

/**
 * Validate admin form
 */
function validateAdminForm(form) {
    let isValid = true;
    const requiredFields = form.querySelectorAll('[required]');
    
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            showFieldError(field, 'Dieses Feld ist erforderlich');
            isValid = false;
        } else {
            clearFieldError(field);
        }
    });
    
    // Validate email fields
    const emailFields = form.querySelectorAll('input[type="email"]');
    emailFields.forEach(field => {
        if (field.value && !isValidEmail(field.value)) {
            showFieldError(field, 'Bitte geben Sie eine gültige E-Mail-Adresse ein');
            isValid = false;
        }
    });
    
    // Validate password confirmation
    const password = form.querySelector('input[name="password"]');
    const confirmPassword = form.querySelector('input[name="confirm_password"]');
    
    if (password && confirmPassword && password.value !== confirmPassword.value) {
        showFieldError(confirmPassword, 'Passwörter stimmen nicht überein');
        isValid = false;
    }
    
    return isValid;
}

/**
 * Show field error
 */
function showFieldError(field, message) {
    clearFieldError(field);
    
    field.classList.add('error');
    
    const errorDiv = document.createElement('div');
    errorDiv.className = 'field-error';
    errorDiv.textContent = message;
    
    field.parentNode.insertBefore(errorDiv, field.nextSibling);
}

/**
 * Clear field error
 */
function clearFieldError(field) {
    field.classList.remove('error');
    
    const existingError = field.parentNode.querySelector('.field-error');
    if (existingError) {
        existingError.remove();
    }
}

/**
 * Validate email
 */
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

/**
 * Initialize confirm dialogs
 */
function initConfirmDialogs() {
    const deleteButtons = document.querySelectorAll('a[href*="delete"], button[data-action="delete"]');
    
    deleteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            if (!confirm('Sind Sie sicher, dass Sie diesen Eintrag löschen möchten?')) {
                e.preventDefault();
            }
        });
    });
}

/**
 * Initialize auto refresh for dashboard
 */
function initAutoRefresh() {
    // Only refresh if we're on the dashboard
    if (window.location.pathname.includes('admin/index.php')) {
        setInterval(function() {
            refreshDashboardStats();
        }, 30000); // Refresh every 30 seconds
    }
}

/**
 * Refresh dashboard statistics
 */
function refreshDashboardStats() {
    fetch('api/dashboard-stats.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateStatsCards(data.stats);
            }
        })
        .catch(error => {
            console.error('Error refreshing stats:', error);
        });
}

/**
 * Update statistics cards
 */
function updateStatsCards(stats) {
    const statCards = document.querySelectorAll('.stat-card');
    
    statCards.forEach(card => {
        const statNumber = card.querySelector('.stat-content h3');
        if (statNumber) {
            const statType = statNumber.textContent.trim();
            const newValue = getStatValue(stats, statType);
            if (newValue !== null) {
                statNumber.textContent = newValue;
            }
        }
    });
}

/**
 * Get stat value by type
 */
function getStatValue(stats, statType) {
    const statMap = {
        'Aktive Events': stats.total_events,
        'Gesamte Termine': stats.total_appointments,
        'Heute': stats.today_appointments,
        'Diesen Monat': stats.month_appointments
    };
    
    return statMap[statType] || null;
}

/**
 * Show notification
 */
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
            <span>${message}</span>
            <button class="notification-close" onclick="this.parentElement.parentElement.remove()">
                <i class="fas fa-times"></i>
            </button>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // Auto remove after 5 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 5000);
}

/**
 * Format date for display
 */
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('de-DE', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric'
    });
}

/**
 * Format time for display
 */
function formatTime(timeString) {
    const time = new Date(`2000-01-01T${timeString}`);
    return time.toLocaleTimeString('de-DE', {
        hour: '2-digit',
        minute: '2-digit'
    });
}

/**
 * Export data to CSV
 */
function exportToCSV(data, filename) {
    const csv = convertToCSV(data);
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    
    if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

/**
 * Convert data to CSV format
 */
function convertToCSV(data) {
    if (!data || data.length === 0) return '';
    
    const headers = Object.keys(data[0]);
    const csvContent = [
        headers.join(','),
        ...data.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
    ].join('\n');
    
    return csvContent;
}

// Add CSS for admin specific styles
const adminStyle = document.createElement('style');
adminStyle.textContent = `
    .field-error {
        color: #e10600;
        font-size: 0.875rem;
        margin-top: 0.25rem;
        display: flex;
        align-items: center;
        gap: 0.25rem;
    }
    
    .field-error::before {
        content: '⚠';
        font-size: 0.75rem;
    }
    
    input.error,
    select.error,
    textarea.error {
        border-color: #e10600;
        box-shadow: 0 0 0 3px rgba(225, 6, 0, 0.1);
    }
    
    .notification {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1000;
        max-width: 400px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        border-left: 4px solid #1e3c72;
        animation: slideInRight 0.3s ease-out;
    }
    
    .notification-success {
        border-left-color: #28a745;
    }
    
    .notification-error {
        border-left-color: #e10600;
    }
    
    .notification-content {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 1rem;
    }
    
    .notification-close {
        background: none;
        border: none;
        cursor: pointer;
        color: #666;
        margin-left: auto;
    }
    
    @keyframes slideInRight {
        from {
            opacity: 0;
            transform: translateX(100%);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }
    
    .mobile-menu-toggle {
        display: none;
        position: fixed;
        top: 1rem;
        left: 1rem;
        z-index: 1001;
        background: var(--f1-red);
        color: white;
        border: none;
        padding: 0.75rem;
        border-radius: 8px;
        font-size: 1.2rem;
        cursor: pointer;
    }
    
    @media (max-width: 768px) {
        .mobile-menu-toggle {
            display: block;
        }
    }
    
    .action-buttons {
        display: flex;
        gap: 0.5rem;
    }
    
    .btn-sm {
        padding: 0.5rem 0.75rem;
        font-size: 0.85rem;
    }
    
    .btn-danger {
        background: #dc3545;
        color: white;
    }
    
    .btn-danger:hover {
        background: #c82333;
    }
    
    .status-active {
        background: #d4edda;
        color: #155724;
    }
    
    .status-inactive {
        background: #f8d7da;
        color: #721c24;
    }
    
    .appointment-count {
        font-weight: 600;
        color: var(--f1-red);
    }
    
    .events-table table {
        width: 100%;
        border-collapse: collapse;
    }
    
    .events-table th,
    .events-table td {
        padding: 1rem;
        text-align: left;
        border-bottom: 1px solid #eee;
    }
    
    .events-table th {
        background: #f8f9fa;
        font-weight: 600;
        color: var(--volvo-blue);
    }
    
    .events-table tr:hover {
        background: #f8f9fa;
    }
    
    .checkbox-label {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        cursor: pointer;
        font-weight: normal;
    }
    
    .checkbox-label input[type="checkbox"] {
        margin: 0;
    }
`;
document.head.appendChild(adminStyle);
