/**
 * Authentication Handler
 * Login ve Register işlemlerini yöneten JavaScript dosyası
 */

// API base URL - config/database.php ile aynı seviyede olmalı
const API_URL = window.location.origin + '/api';

console.log('API URL:', API_URL); // Debug

// Utility: Toast notification (geliştirilmiş)
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = 'custom-toast';
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 16px 24px;
        background: ${type === 'success' ? '#22c55e' : type === 'error' ? '#ef4444' : '#3b82f6'};
        color: white;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        z-index: 9999;
        animation: slideIn 0.3s ease;
        font-weight: 500;
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// CSS for toast animations
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(400px); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(400px); opacity: 0; }
    }
`;
document.head.appendChild(style);

// Utility: Form validation
function validateForm(formElement) {
    const inputs = formElement.querySelectorAll('input[required]');
    let isValid = true;
    
    inputs.forEach(input => {
        const formGroup = input.closest('.form-floating-custom');
        
        if (!input.value.trim()) {
            if (formGroup) formGroup.classList.add('is-invalid');
            isValid = false;
        } else {
            if (formGroup) formGroup.classList.remove('is-invalid');
        }
        
        // Email validation
        if (input.type === 'email' && input.value) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(input.value)) {
                if (formGroup) formGroup.classList.add('is-invalid');
                isValid = false;
            }
        }
    });
    
    return isValid;
}

// Login Form Handler
const loginForm = document.getElementById('loginForm');
if (loginForm) {
    console.log('Login form found');
    
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        console.log('Login form submitted');
        
        if (!validateForm(loginForm)) {
            showToast('Lütfen tüm alanları doldurun', 'error');
            return;
        }
        
        const submitBtn = loginForm.querySelector('button[type="submit"]');
        const btnText = submitBtn.querySelector('.btn-text');
        const btnLoader = submitBtn.querySelector('.btn-loader');
        
        // Loading state
        submitBtn.disabled = true;
        submitBtn.classList.add('loading');
        if (btnText) btnText.style.display = 'none';
        if (btnLoader) btnLoader.style.display = 'inline-block';
        
        const formData = {
            email: document.getElementById('email').value.trim(),
            password: document.getElementById('password').value
        };
        
        console.log('Sending login request to:', `${API_URL}/login.php`);
        console.log('Form data:', { email: formData.email });
        
        try {
            const response = await fetch(`${API_URL}/login.php`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
                body: JSON.stringify(formData)
            });
            
            console.log('Response status:', response.status);
            console.log('Response headers:', response.headers);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            console.log('Login result:', result);
            
            if (result.success) {
                showToast(result.message, 'success');
                setTimeout(() => {
                    window.location.href = '/';
                }, 1000);
            } else {
                showToast(result.message, 'error');
                submitBtn.disabled = false;
                submitBtn.classList.remove('loading');
                if (btnText) btnText.style.display = 'inline-block';
                if (btnLoader) btnLoader.style.display = 'none';
            }
        } catch (error) {
            console.error('Login error:', error);
            showToast('Bağlantı hatası: ' + error.message, 'error');
            submitBtn.disabled = false;
            submitBtn.classList.remove('loading');
            if (btnText) btnText.style.display = 'inline-block';
            if (btnLoader) btnLoader.style.display = 'none';
        }
    });
}

// Register Form Handler
const registerForm = document.getElementById('registerForm');
if (registerForm) {
    console.log('Register form found');
    
    registerForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        console.log('Register form submitted');
        
        if (!validateForm(registerForm)) {
            showToast('Lütfen tüm alanları doldurun', 'error');
            return;
        }
        
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        
        if (password !== confirmPassword) {
            showToast('Şifreler eşleşmiyor', 'error');
            const formGroup = document.getElementById('confirmPassword').closest('.form-floating-custom');
            if (formGroup) formGroup.classList.add('is-invalid');
            return;
        }
        
        if (password.length < 8) {
            showToast('Şifre en az 8 karakter olmalıdır', 'error');
            const formGroup = document.getElementById('password').closest('.form-floating-custom');
            if (formGroup) formGroup.classList.add('is-invalid');
            return;
        }
        
        const terms = document.getElementById('terms');
        if (!terms || !terms.checked) {
            showToast('Kullanım şartlarını kabul etmelisiniz', 'error');
            return;
        }
        
        const submitBtn = registerForm.querySelector('button[type="submit"]');
        const btnText = submitBtn.querySelector('.btn-text');
        const btnLoader = submitBtn.querySelector('.btn-loader');
        
        // Loading state
        submitBtn.disabled = true;
        submitBtn.classList.add('loading');
        if (btnText) btnText.style.display = 'none';
        if (btnLoader) btnLoader.style.display = 'inline-block';
        
        const formData = {
            firstName: document.getElementById('firstName').value.trim(),
            lastName: document.getElementById('lastName').value.trim(),
            username: document.getElementById('username').value.trim(),
            email: document.getElementById('email').value.trim(),
            password: password,
            confirmPassword: confirmPassword,
            terms: true
        };
        
        console.log('Sending register request to:', `${API_URL}/register.php`);
        console.log('Form data:', { email: formData.email, username: formData.username });
        
        try {
            const response = await fetch(`${API_URL}/register.php`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData)
            });
            
            console.log('Response status:', response.status);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            console.log('Register result:', result);
            
            if (result.success) {
                showToast(result.message, 'success');
                setTimeout(() => {
                    window.location.href = '/login';
                }, 1500);
            } else {
                showToast(result.message, 'error');
                submitBtn.disabled = false;
                submitBtn.classList.remove('loading');
                if (btnText) btnText.style.display = 'inline-block';
                if (btnLoader) btnLoader.style.display = 'none';
            }
        } catch (error) {
            console.error('Register error:', error);
            showToast('Bağlantı hatası: ' + error.message, 'error');
            submitBtn.disabled = false;
            submitBtn.classList.remove('loading');
            if (btnText) btnText.style.display = 'inline-block';
            if (btnLoader) btnLoader.style.display = 'none';
        }
    });
    
    // Password strength indicator
    const passwordInput = document.getElementById('password');
    if (passwordInput) {
        passwordInput.addEventListener('input', (e) => {
            const password = e.target.value;
            const strengthBar = document.querySelector('.strength-fill');
            const strengthText = document.querySelector('.strength-text');
            
            if (!strengthBar || !strengthText) return;
            
            let strength = 0;
            if (password.length >= 8) strength++;
            if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
            if (/\d/.test(password)) strength++;
            if (/[@$!%*?&#]/.test(password)) strength++;
            
            const percentage = (strength / 4) * 100;
            strengthBar.style.width = `${percentage}%`;
            
            if (strength <= 1) {
                strengthBar.style.background = '#ef4444';
                strengthText.textContent = 'Zayıf';
            } else if (strength === 2) {
                strengthBar.style.background = '#f59e0b';
                strengthText.textContent = 'Orta';
            } else if (strength === 3) {
                strengthBar.style.background = '#10b981';
                strengthText.textContent = 'İyi';
            } else {
                strengthBar.style.background = '#059669';
                strengthText.textContent = 'Güçlü';
            }
        });
    }
}

// Toggle password visibility
document.querySelectorAll('.toggle-password').forEach(button => {
    button.addEventListener('click', function() {
        const input = this.parentElement.querySelector('input');
        const icon = this.querySelector('i');
        
        if (input && icon) {
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('bi-eye');
                icon.classList.add('bi-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('bi-eye-slash');
                icon.classList.add('bi-eye');
            }
        }
    });
});

// Cart functionality
async function addToCart(productId, quantity = 1) {
    console.log('Adding to cart:', productId, quantity);
    
    try {
        const response = await fetch(`${API_URL}/cart-add.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include',
            body: JSON.stringify({
                product_id: productId,
                quantity: quantity
            })
        });
        
        console.log('Cart add response status:', response.status);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        console.log('Cart add result:', result);
        
        if (result.success) {
            showToast('Ürün sepete eklendi!', 'success');
            updateCartCount();
        } else {
            showToast(result.message, 'error');
        }
    } catch (error) {
        console.error('Add to cart error:', error);
        showToast('Sepete eklenirken hata oluştu: ' + error.message, 'error');
    }
}

async function updateCartCount() {
    try {
        const response = await fetch(`${API_URL}/cart-get.php`, {
            credentials: 'include'
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.success) {
            const cartBadge = document.querySelector('.cart-count');
            if (cartBadge) {
                cartBadge.textContent = result.data.count;
                if (result.data.count > 0) {
                    cartBadge.style.display = 'inline-block';
                }
            }
        }
    } catch (error) {
        console.error('Update cart count error:', error);
    }
}

// Page load: update cart count
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM Content Loaded');
    if (document.querySelector('.cart-count')) {
        updateCartCount();
    }
});

// Export functions for global use
window.addToCart = addToCart;
window.updateCartCount = updateCartCount;

console.log('Auth.js loaded successfully');