/**
 * Admin Functions
 * Admin panel specific functionality
 */

// ============================================
// Admin Manager Class
// ============================================

class AdminManager {
    constructor() {
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.initBulkActions();
        this.initRubricManager();
        this.initRemedyManager();
        this.initSubscriptionManager();
    }
    
    bindEvents() {
        // Toggle sidebar
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => this.toggleSidebar());
        }
        
        // Confirm dangerous actions
        document.querySelectorAll('[data-danger]').forEach(el => {
            el.addEventListener('click', (e) => {
                if (!confirm('This action cannot be undone. Are you sure?')) {
                    e.preventDefault();
                }
            });
        });
    }
    
    toggleSidebar() {
        const sidebar = document.querySelector('.admin-sidebar');
        const main = document.querySelector('.admin-main');
        if (sidebar && main) {
            sidebar.classList.toggle('collapsed');
            main.classList.toggle('expanded');
            localStorage.setItem('sidebar_collapsed', sidebar.classList.contains('collapsed'));
        }
    }
    
    initBulkActions() {
        const selectAll = document.getElementById('selectAll');
        if (selectAll) {
            selectAll.addEventListener('change', () => {
                const checkboxes = document.querySelectorAll('.bulk-checkbox');
                checkboxes.forEach(cb => cb.checked = selectAll.checked);
            });
        }
        
        const bulkActionBtn = document.getElementById('bulkActionBtn');
        if (bulkActionBtn) {
            bulkActionBtn.addEventListener('click', () => this.executeBulkAction());
        }
    }
    
    executeBulkAction() {
        const action = document.getElementById('bulkAction')?.value;
        const selected = Array.from(document.querySelectorAll('.bulk-checkbox:checked')).map(cb => cb.value);
        
        if (!action) {
            showNotification('Please select an action', 'warning');
            return;
        }
        
        if (selected.length === 0) {
            showNotification('Please select items', 'warning');
            return;
        }
        
        if (!confirm(`Are you sure you want to ${action} ${selected.length} item(s)?`)) {
            return;
        }
        
        showLoading();
        
        fetch('api/bulk-action.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: action, ids: selected })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification(`Successfully ${action}d ${selected.length} item(s)`, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showNotification(data.error || 'Action failed', 'error');
            }
        })
        .catch(error => {
            showNotification('Network error', 'error');
        })
        .finally(() => hideLoading());
    }
    
    initRubricManager() {
        const rubricForm = document.getElementById('rubricForm');
        if (rubricForm) {
            rubricForm.addEventListener('submit', (e) => this.saveRubric(e));
        }
        
        this.initRubricReorder();
    }
    
    async saveRubric(e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        
        showLoading();
        
        try {
            const response = await fetch('api/save-rubric.php', {
                method: 'POST',
                body: formData
            });
            const data = await response.json();
            
            if (data.success) {
                showNotification('Rubric saved successfully', 'success');
                if (data.redirect) {
                    setTimeout(() => window.location.href = data.redirect, 1500);
                }
            } else {
                showNotification(data.error || 'Failed to save rubric', 'error');
            }
        } catch (error) {
            showNotification('Network error', 'error');
        } finally {
            hideLoading();
        }
    }
    
    initRubricReorder() {
        const reorderContainer = document.getElementById('rubricReorderContainer');
        if (reorderContainer && typeof Sortable !== 'undefined') {
            new Sortable(reorderContainer, {
                handle: '.drag-handle',
                animation: 150,
                onEnd: () => this.saveRubricOrder()
            });
        }
    }
    
    async saveRubricOrder() {
        const items = document.querySelectorAll('.rubric-sort-item');
        const order = Array.from(items).map((item, index) => ({
            id: item.dataset.id,
            order: index
        }));
        
        try {
            const response = await fetch('api/reorder-rubrics.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ order: order })
            });
            const data = await response.json();
            if (data.success) {
                showNotification('Order saved', 'success');
            }
        } catch (error) {
            console.error('Reorder error:', error);
        }
    }
    
    initRemedyManager() {
        const remedyForm = document.getElementById('remedyForm');
        if (remedyForm) {
            remedyForm.addEventListener('submit', (e) => this.saveRemedy(e));
        }
    }
    
    async saveRemedy(e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        
        showLoading();
        
        try {
            const response = await fetch('api/save-remedy.php', {
                method: 'POST',
                body: formData
            });
            const data = await response.json();
            
            if (data.success) {
                showNotification('Remedy saved successfully', 'success');
                if (data.redirect) {
                    setTimeout(() => window.location.href = data.redirect, 1500);
                }
            } else {
                showNotification(data.error || 'Failed to save remedy', 'error');
            }
        } catch (error) {
            showNotification('Network error', 'error');
        } finally {
            hideLoading();
        }
    }
    
    initSubscriptionManager() {
        const planSelect = document.getElementById('plan_type');
        if (planSelect) {
            planSelect.addEventListener('change', () => this.updatePlanAmount());
        }
    }
    
    updatePlanAmount() {
        const planSelect = document.getElementById('plan_type');
        const amountField = document.getElementById('amount');
        const amounts = { '1month': 9.99, '6month': 49.99, '1year': 89.99, 'unlimited': 299.99 };
        
        if (planSelect && amountField && amounts[planSelect.value]) {
            amountField.value = amounts[planSelect.value];
        }
    }
    
    async createBackup() {
        if (!confirm('Create a full database backup?')) return;
        
        showLoading();
        
        try {
            const response = await fetch('api/create-backup.php', { method: 'POST' });
            const data = await response.json();
            
            if (data.success) {
                showNotification('Backup created successfully', 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showNotification(data.error || 'Backup failed', 'error');
            }
        } catch (error) {
            showNotification('Network error', 'error');
        } finally {
            hideLoading();
        }
    }
    
    async restoreBackup(backupFile) {
        if (!confirm(`Restore backup from ${backupFile}? This will overwrite all current data.`)) {
            return;
        }
        
        showLoading();
        
        try {
            const response = await fetch('api/restore-backup.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ backup_file: backupFile })
            });
            const data = await response.json();
            
            if (data.success) {
                showNotification('Database restored successfully', 'success');
                setTimeout(() => location.reload(), 2000);
            } else {
                showNotification(data.error || 'Restore failed', 'error');
            }
        } catch (error) {
            showNotification('Network error', 'error');
        } finally {
            hideLoading();
        }
    }
}

// Initialize Admin Manager
let adminManager = null;

document.addEventListener('DOMContentLoaded', () => {
    if (document.body.classList.contains('admin-panel')) {
        adminManager = new AdminManager();
        window.adminManager = adminManager;
    }
});