/**
 * Các chức năng hỗ trợ cho giao diện
 * Kiểm tra và xử lý form phía client
 */

document.addEventListener('DOMContentLoaded', function() {
    
    // ============================================
    // SIDEBAR - ĐÓNG MỞ
    // ============================================
    
    const sidebar = document.getElementById('sidebar');
    const toggleBtn = document.getElementById('sidebarToggle');
    const overlay = document.getElementById('sidebarOverlay');
    const mainContent = document.getElementById('mainContent');
    
    // Tạo nút mở menu cho mobile
    if (window.innerWidth <= 768) {
        const menuBtn = document.createElement('button');
        menuBtn.className = 'menu-toggle-mobile';
        menuBtn.innerHTML = '☰';
        menuBtn.setAttribute('aria-label', 'Mở menu');
        menuBtn.id = 'menuToggleMobile';
        document.body.prepend(menuBtn);
        
        menuBtn.addEventListener('click', function() {
            sidebar.classList.add('open');
            overlay.classList.add('active');
        });
    }
    
    // Đóng mở sidebar trên desktop
    if (toggleBtn) {
        toggleBtn.addEventListener('click', function() {
            sidebar.classList.toggle('collapsed');
            // Lưu trạng thái vào cookie
            const isCollapsed = sidebar.classList.contains('collapsed');
            document.cookie = 'sidebar_collapsed=' + isCollapsed + '; path=/; max-age=31536000';
        });
    }
    
    // Đóng sidebar khi click overlay (mobile)
    if (overlay) {
        overlay.addEventListener('click', function() {
            sidebar.classList.remove('open');
            overlay.classList.remove('active');
        });
    }
    
    // Đóng sidebar khi resize lên desktop
    window.addEventListener('resize', function() {
        if (window.innerWidth > 768) {
            sidebar.classList.remove('open');
            if (overlay) overlay.classList.remove('active');
        }
    });
    
    // ============================================
    // TỰ ĐỘNG FOCUS
    // ============================================
    
    const firstInput = document.querySelector('.form-input:not([disabled])');
    if (firstInput && !window.location.pathname.includes('dashboard.php')) {
        firstInput.focus();
    }
    
    // ============================================
    // ALERT TỰ ĐỘNG ẨN
    // ============================================
    
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            alert.style.opacity = '0';
            alert.style.transition = 'opacity 0.5s';
            setTimeout(function() {
                alert.style.display = 'none';
            }, 500);
        }, 5000);
    });
    
    // ============================================
    // KIỂM TRA MẬT KHẨU ĐĂNG KÝ
    // ============================================
    
    if (window.location.pathname.includes('register.php')) {
        const passwordInput = document.getElementById('password');
        const confirmInput = document.getElementById('confirm_password');
        
        if (passwordInput && confirmInput) {
            confirmInput.addEventListener('input', function() {
                if (this.value.length > 0 && this.value !== passwordInput.value) {
                    this.style.borderColor = '#991b1b';
                    this.style.backgroundColor = '#fef2f2';
                } else {
                    this.style.borderColor = '#d0d0d0';
                    this.style.backgroundColor = '#ffffff';
                }
            });
            
            passwordInput.addEventListener('input', function() {
                if (confirmInput.value.length > 0 && this.value !== confirmInput.value) {
                    confirmInput.style.borderColor = '#991b1b';
                    confirmInput.style.backgroundColor = '#fef2f2';
                } else if (confirmInput.value.length > 0) {
                    confirmInput.style.borderColor = '#d0d0d0';
                    confirmInput.style.backgroundColor = '#ffffff';
                }
            });
        }
    }
    
    // ============================================
    // KIỂM TRA MẬT KHẨU ĐỔI MẬT KHẨU
    // ============================================
    
    if (window.location.pathname.includes('profile.php')) {
        const newPassword = document.getElementById('new_password');
        const confirmNewPassword = document.getElementById('confirm_new_password');
        
        if (newPassword && confirmNewPassword) {
            confirmNewPassword.addEventListener('input', function() {
                if (this.value.length > 0 && this.value !== newPassword.value) {
                    this.style.borderColor = '#991b1b';
                    this.style.backgroundColor = '#fef2f2';
                } else {
                    this.style.borderColor = '#d0d0d0';
                    this.style.backgroundColor = '#ffffff';
                }
            });
        }
    }
    
    // ============================================
    // CÀI ĐẶT - LƯU THEME
    // ============================================
    
    const themeSelect = document.getElementById('themeSelect');
    if (themeSelect) {
        // Đọc theme từ cookie
        const theme = getCookie('theme') || 'light';
        themeSelect.value = theme;
        applyTheme(theme);
        
        themeSelect.addEventListener('change', function() {
            applyTheme(this.value);
            document.cookie = 'theme=' + this.value + '; path=/; max-age=31536000';
        });
    }
    
    // ============================================
    // CÀI ĐẶT - TRẠNG THÁI MENU
    // ============================================
    
    const menuStateSelect = document.getElementById('menuStateSelect');
    if (menuStateSelect && sidebar) {
        const isCollapsed = sidebar.classList.contains('collapsed');
        menuStateSelect.value = isCollapsed ? 'collapsed' : 'expanded';
        
        menuStateSelect.addEventListener('change', function() {
            if (this.value === 'collapsed') {
                sidebar.classList.add('collapsed');
                document.cookie = 'sidebar_collapsed=true; path=/; max-age=31536000';
            } else {
                sidebar.classList.remove('collapsed');
                document.cookie = 'sidebar_collapsed=false; path=/; max-age=31536000';
            }
        });
    }
});

// ============================================
// HÀM TIỆN ÍCH
// ============================================

/**
 * Xác nhận đăng xuất
 */
function confirmLogout() {
    return confirm('Bạn có chắc chắn muốn đăng xuất?');
}

/**
 * Lấy cookie theo tên
 */
function getCookie(name) {
    const value = '; ' + document.cookie;
    const parts = value.split('; ' + name + '=');
    if (parts.length === 2) return parts.pop().split(';').shift();
    return null;
}

/**
 * Áp dụng theme
 */
function applyTheme(theme) {
    if (theme === 'dark') {
        document.body.style.backgroundColor = '#1a1a1a';
        document.body.style.color = '#ffffff';
        // Thêm class dark cho các phần tử
        document.querySelectorAll('.stat-card, .content-card, .profile-section, .settings-section, .admin-table-wrapper, .admin-table').forEach(function(el) {
            el.style.backgroundColor = '#2d2d2d';
            el.style.borderColor = '#404040';
        });
        document.querySelectorAll('.stat-number, .card-title, .section-title, .page-title, .form-label, .settings-label').forEach(function(el) {
            el.style.color = '#ffffff';
        });
        document.querySelectorAll('.stat-label, .page-subtitle, .auth-subtitle, .card-content, .sidebar-userrole').forEach(function(el) {
            el.style.color = '#aaaaaa';
        });
        document.querySelectorAll('.form-input').forEach(function(el) {
            el.style.backgroundColor = '#2d2d2d';
            el.style.color = '#ffffff';
            el.style.borderColor = '#404040';
        });
        document.querySelectorAll('.auth-wrapper, .auth-container').forEach(function(el) {
            el.style.backgroundColor = '#1a1a1a';
        });
        document.querySelectorAll('.sidebar, .auth-wrapper').forEach(function(el) {
            el.style.backgroundColor = '#1a1a1a';
            el.style.borderColor = '#404040';
        });
        document.querySelectorAll('.nav-link:not(.active)').forEach(function(el) {
            el.style.color = '#aaaaaa';
        });
        document.querySelectorAll('.nav-link:hover').forEach(function(el) {
            el.style.backgroundColor = '#2d2d2d';
        });
        document.querySelectorAll('.nav-divider .divider-text').forEach(function(el) {
            el.style.color = '#666666';
        });
        document.querySelectorAll('.admin-table th').forEach(function(el) {
            el.style.backgroundColor = '#2d2d2d';
            el.style.color = '#ffffff';
        });
        document.querySelectorAll('.admin-table td').forEach(function(el) {
            el.style.color = '#cccccc';
        });
        document.querySelectorAll('.admin-table tbody tr:hover').forEach(function(el) {
            el.style.backgroundColor = '#2d2d2d';
        });
        document.querySelectorAll('.badge-member').forEach(function(el) {
            el.style.backgroundColor = '#404040';
            el.style.color = '#aaaaaa';
        });
        document.querySelectorAll('.sidebar-toggle').forEach(function(el) {
            el.style.backgroundColor = '#2d2d2d';
            el.style.borderColor = '#404040';
            el.style.color = '#ffffff';
        });
    } else {
        // Reset về light
        document.body.style.backgroundColor = '#f5f6fa';
        document.body.style.color = '#000000';
        document.querySelectorAll('.stat-card, .content-card, .profile-section, .settings-section, .admin-table-wrapper, .admin-table').forEach(function(el) {
            el.style.backgroundColor = '#ffffff';
            el.style.borderColor = '#e0e0e0';
        });
        document.querySelectorAll('.stat-number, .card-title, .section-title, .page-title, .form-label, .settings-label').forEach(function(el) {
            el.style.color = '#000000';
        });
        document.querySelectorAll('.stat-label, .page-subtitle, .auth-subtitle, .card-content, .sidebar-userrole').forEach(function(el) {
            el.style.color = '#666666';
        });
        document.querySelectorAll('.form-input').forEach(function(el) {
            el.style.backgroundColor = '#ffffff';
            el.style.color = '#000000';
            el.style.borderColor = '#d0d0d0';
        });
        document.querySelectorAll('.auth-wrapper, .auth-container').forEach(function(el) {
            el.style.backgroundColor = '#ffffff';
        });
        document.querySelectorAll('.sidebar, .auth-wrapper').forEach(function(el) {
            el.style.backgroundColor = '#ffffff';
            el.style.borderColor = '#e0e0e0';
        });
        document.querySelectorAll('.nav-link:not(.active)').forEach(function(el) {
            el.style.color = '#333333';
        });
        document.querySelectorAll('.nav-link:hover').forEach(function(el) {
            el.style.backgroundColor = '#f5f5f5';
        });
        document.querySelectorAll('.nav-divider .divider-text').forEach(function(el) {
            el.style.color = '#999999';
        });
        document.querySelectorAll('.admin-table th').forEach(function(el) {
            el.style.backgroundColor = '#f8f9fa';
            el.style.color = '#000000';
        });
        document.querySelectorAll('.admin-table td').forEach(function(el) {
            el.style.color = '#333333';
        });
        document.querySelectorAll('.admin-table tbody tr:hover').forEach(function(el) {
            el.style.backgroundColor = '#f8f9fa';
        });
        document.querySelectorAll('.badge-member').forEach(function(el) {
            el.style.backgroundColor = '#e0e0e0';
            el.style.color = '#333333';
        });
        document.querySelectorAll('.sidebar-toggle').forEach(function(el) {
            el.style.backgroundColor = '#ffffff';
            el.style.borderColor = '#e0e0e0';
            el.style.color = '#000000';
        });
    }
}

/**
 * Lưu cài đặt
 */
function saveSettings() {
    const theme = document.getElementById('themeSelect')?.value || 'light';
    const menuState = document.getElementById('menuStateSelect')?.value || 'expanded';
    
    document.cookie = 'theme=' + theme + '; path=/; max-age=31536000';
    document.cookie = 'sidebar_collapsed=' + (menuState === 'collapsed') + '; path=/; max-age=31536000';
    
    applyTheme(theme);
    
    const sidebar = document.getElementById('sidebar');
    if (sidebar) {
        if (menuState === 'collapsed') {
            sidebar.classList.add('collapsed');
        } else {
            sidebar.classList.remove('collapsed');
        }
    }
    
    alert('Cài đặt đã được lưu.');
}

/**
 * Khôi phục cài đặt mặc định
 */
function resetSettings() {
    if (!confirm('Bạn có chắc chắn muốn khôi phục cài đặt mặc định?')) {
        return;
    }
    
    document.cookie = 'theme=light; path=/; max-age=31536000';
    document.cookie = 'sidebar_collapsed=false; path=/; max-age=31536000';
    
    const themeSelect = document.getElementById('themeSelect');
    const menuStateSelect = document.getElementById('menuStateSelect');
    const sidebar = document.getElementById('sidebar');
    
    if (themeSelect) themeSelect.value = 'light';
    if (menuStateSelect) menuStateSelect.value = 'expanded';
    if (sidebar) sidebar.classList.remove('collapsed');
    
    applyTheme('light');
    
    alert('Đã khôi phục cài đặt mặc định.');
}

/**
 * Chỉnh sửa người dùng (Admin)
 */
function editUser(userId) {
    alert('Chức năng đang được phát triển. ID: ' + userId);
}

/**
 * Xóa người dùng (Admin)
 */
function deleteUser(userId) {
    if (!confirm('Bạn có chắc chắn muốn xóa người dùng này?')) {
        return;
    }
    alert('Chức năng đang được phát triển. ID: ' + userId);
}