/**
 * Login Form Handler
 */
document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    
    if (loginForm) {
        loginForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            
            try {
                // Show loading state
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Logging in...';
                submitBtn.disabled = true;
                
                // Get form data
                const formData = new FormData(this);
                
                // Send login request
                const response = await fetch('../api/process_login.php', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                console.log('Login response:', result); // Debug log
                
                if (result.success) {
                    // ✅ SUCCESS - Redirect to dashboard
                    window.showAlert('Login successful! Redirecting...', 'success');
                    
                    // IMPORTANT: Add a small delay to ensure cookie is set
                    setTimeout(() => {
                        // Check if redirect_url exists in response
                        if (result.redirect_url) {
                            window.location.href = result.redirect_url;
                        } else {
                            // Fallback redirect
                            window.location.href = '../pages/dashboard.php';
                        }
                    }, 500);
                    
                } else {
                    // ❌ FAILURE - Show error
                    window.showAlert(result.message || 'Login failed', 'danger');
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }
                
            } catch (error) {
                console.error('Login error:', error);
                window.showAlert('Network error. Please try again.', 'danger');
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }
        });
    }
    
    // Helper function to show alerts
    window.showAlert = function(message, type) {
        // Remove existing alerts
        const existingAlerts = document.querySelectorAll('.alert');
        existingAlerts.forEach(alert => alert.remove());
        
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        const container = document.querySelector('.container');
        if (container) {
            container.insertBefore(alertDiv, container.firstChild);
        }
    };
});