/**
 * ZLETS - App.js
 * Funcionalidades globales: Toasts, alertas de vencimiento, utilidades
 */

// ============================================================
// Toast Configuration (SweetAlert2)
// ============================================================
const Toast = Swal.mixin({
    toast: true,
    position: 'top-end',
    showConfirmButton: false,
    timer: 5000,
    timerProgressBar: true,
    didOpen: (toast) => {
        toast.addEventListener('mouseenter', Swal.stopTimer);
        toast.addEventListener('mouseleave', Swal.resumeTimer);
    },
    customClass: {
        popup: 'swal2-toast',
    }
});

/**
 * Mostrar notificación Toast
 */
function showToast(icon, title, text = '', timer = 5000) {
    Toast.fire({
        icon: icon,
        title: title,
        text: text,
        timer: timer,
    });
}

// ============================================================
// Alertas de Vencimiento (procesadas desde PHP)
// ============================================================

/**
 * Procesar alertas y mostrar Toasts escalonados
 * @param {Array} alertas - Letras próximas a vencer
 * @param {Array} excedidas - Letras que excedieron plazo de pago
 */
function procesarAlertas(alertas, excedidas) {
    let delay = 500;

    // Primero las excedidas (CRÍTICO)
    excedidas.forEach((exc) => {
        setTimeout(() => {
            Toast.fire({
                icon: 'error',
                title: `¡CRÍTICO! Plazo de pago excedido`,
                text: `Letra #${exc.numero_letra} de ${exc.razon_social} - $${parseFloat(exc.importe).toFixed(2)} - Excedida ${exc.dias_excedidos} día(s)`,
                timer: 8000,
                background: 'rgba(30, 42, 58, 0.98)',
                iconColor: '#ef4444',
            });
        }, delay);
        delay += 1200;
    });

    // Luego las próximas a vencer
    alertas.forEach((alerta) => {
        const diasVencer = parseInt(alerta.dias_para_vencer);
        const diasPagar = parseInt(alerta.dias_para_pagar);
        let icon, title, iconColor;

        if (diasVencer < 0) {
            // Ya venció pero aún puede pagar
            icon = 'error';
            title = `¡URGENTE! Letra vencida`;
            iconColor = '#ef4444';
        } else if (diasVencer === 0) {
            icon = 'error';
            title = `¡Vence HOY!`;
            iconColor = '#ef4444';
        } else if (diasVencer <= 3) {
            icon = 'warning';
            title = `Vence en ${diasVencer} día(s)`;
            iconColor = '#f59e0b';
        } else {
            icon = 'info';
            title = `Vence en ${diasVencer} días`;
            iconColor = '#6366f1';
        }

        const textoPago = diasVencer < 0
            ? `Quedan ${diasPagar} día(s) para pagar al banco`
            : `Fecha pago: ${alerta.fecha_pago || 'N/A'}`;

        setTimeout(() => {
            Toast.fire({
                icon: icon,
                title: title,
                text: `Letra #${alerta.numero_letra} - ${alerta.razon_social} - $${parseFloat(alerta.importe).toFixed(2)} | ${textoPago}`,
                timer: 6000,
                background: 'rgba(30, 42, 58, 0.98)',
                iconColor: iconColor,
            });
        }, delay);
        delay += 1000;
    });
}

/**
 * Mostrar resumen de todas las alertas en un modal
 */
function mostrarTodasAlertas() {
    // Fetch alertas via AJAX
    fetch(BASE_URL + '?c=dashboard&a=alertas')
        .then(res => res.json())
        .then(data => {
            const alertas = data.alertas || [];
            const excedidas = data.excedidas || [];

            if (alertas.length === 0 && excedidas.length === 0) {
                Swal.fire({
                    icon: 'success',
                    title: 'Sin alertas',
                    text: 'No hay letras próximas a vencer ni vencidas.',
                    background: 'rgba(30, 42, 58, 0.98)',
                    color: '#fff',
                    confirmButtonColor: '#3d5af5',
                });
                return;
            }

            let html = '<div style="text-align:left; max-height:400px; overflow-y:auto; font-family:Inter,sans-serif;">';
            
            if (excedidas.length > 0) {
                html += '<h4 style="color:#ef4444; margin-bottom:8px; font-size:13px;">⚠ Excedidas (plazo de pago vencido)</h4>';
                excedidas.forEach(e => {
                    html += `<div style="padding:8px; margin-bottom:6px; border-radius:8px; background:rgba(239,68,68,0.08); border:1px solid rgba(239,68,68,0.15); font-size:12px;">
                        <strong style="color:#fca5a5;">${e.razon_social}</strong><br>
                        <span style="color:#94a3b8;">Letra #${e.numero_letra} | $${parseFloat(e.importe).toFixed(2)} | Excedida ${e.dias_excedidos} día(s)</span>
                    </div>`;
                });
            }

            if (alertas.length > 0) {
                html += '<h4 style="color:#f59e0b; margin-bottom:8px; margin-top:12px; font-size:13px;">⏰ Próximas a vencer</h4>';
                alertas.forEach(a => {
                    const dias = parseInt(a.dias_para_vencer);
                    const color = dias < 0 ? '#ef4444' : dias <= 3 ? '#f59e0b' : '#6366f1';
                    const label = dias < 0 ? `Vencida (${a.dias_para_pagar}d para pagar)` : dias === 0 ? 'Vence HOY' : `Vence en ${dias} día(s)`;
                    html += `<div style="padding:8px; margin-bottom:6px; border-radius:8px; background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06); font-size:12px;">
                        <strong style="color:#e2e8f0;">${a.razon_social}</strong>
                        <span style="color:${color}; float:right; font-size:11px; font-weight:600;">${label}</span><br>
                        <span style="color:#94a3b8;">Letra #${a.numero_letra} | $${parseFloat(a.importe).toFixed(2)}</span>
                    </div>`;
                });
            }

            html += '</div>';

            Swal.fire({
                title: `Alertas de Vencimiento (${alertas.length + excedidas.length})`,
                html: html,
                background: 'rgba(30, 42, 58, 0.98)',
                color: '#fff',
                confirmButtonColor: '#3d5af5',
                confirmButtonText: 'Cerrar',
                width: '520px',
            });
        })
        .catch(err => {
            showToast('error', 'Error al cargar alertas');
        });
}

// ============================================================
// Utility Functions
// ============================================================

/**
 * Formatear número como moneda
 */
function formatCurrency(amount, currency = 'USD') {
    const prefix = currency === 'USD' ? '$' : 'S/';
    return prefix + parseFloat(amount).toLocaleString('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
    });
}

/**
 * Formatear fecha
 */
function formatDate(dateStr) {
    if (!dateStr) return '-';
    const d = new Date(dateStr + 'T00:00:00');
    return d.toLocaleDateString('es-PE', { day: '2-digit', month: '2-digit', year: 'numeric' });
}

/**
 * Sumar días a una fecha
 */
function addDays(dateStr, days) {
    const d = new Date(dateStr + 'T00:00:00');
    d.setDate(d.getDate() + days);
    return d.toISOString().split('T')[0];
}

// ============================================================
// Sidebar Toggle (Mobile)
// ============================================================
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    sidebar.classList.toggle('open');
    overlay.classList.toggle('hidden');
}

// Define BASE_URL for JS
const BASE_URL = document.querySelector('meta[name="base-url"]')?.content || '/zlets/';

// Theme Toggle
// ============================================================
function toggleTheme() {
    const html = document.documentElement;
    const isLight = html.classList.toggle('light-theme');
    
    // Save preference
    localStorage.setItem('theme', isLight ? 'light' : 'dark');
    
    // Update icon
    updateThemeIcon(isLight);
}

// ============================================================
// Modal Crear Empresa Global
// ============================================================

/**
 * Abre un modal con SweetAlert para crear una nueva empresa vía AJAX
 * @param {function} onSuccess Callback opcional que se ejecuta si se crea con éxito
 */
function abrirModalNuevaEmpresa(onSuccess = null) {
    Swal.fire({
        title: 'Nueva Empresa Proveedora',
        html: `
            <form id="form-nueva-empresa-ajax" class="text-left mt-4">
                <div class="mb-4">
                    <label class="block text-xs text-gray-400 mb-1.5 font-medium">Razón Social <span class="text-red-400">*</span></label>
                    <input type="text" id="swal-razon-social" class="input-glass w-full" placeholder="Ej: JYW REPUESTOS S.R.L." required>
                </div>
                <div class="mb-4">
                    <label class="block text-xs text-gray-400 mb-1.5 font-medium">RUC <span class="text-red-400">*</span></label>
                    <input type="text" id="swal-ruc" class="input-glass w-full" placeholder="20456789012" required minlength="11" maxlength="11" pattern="\\d{11}">
                </div>
                <div class="mb-4">
                    <label class="block text-xs text-gray-400 mb-1.5 font-medium">Dirección</label>
                    <input type="text" id="swal-direccion" class="input-glass w-full" placeholder="Opcional">
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs text-gray-400 mb-1.5 font-medium">Teléfono</label>
                        <input type="text" id="swal-telefono" class="input-glass w-full" placeholder="Opcional">
                    </div>
                    <div>
                        <label class="block text-xs text-gray-400 mb-1.5 font-medium">Contacto</label>
                        <input type="text" id="swal-contacto" class="input-glass w-full" placeholder="Opcional">
                    </div>
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: '<i class="fas fa-save mr-1"></i> Guardar',
        cancelButtonText: 'Cancelar',
        confirmButtonColor: '#3d5af5',
        cancelButtonColor: '#64748b',
        background: 'rgba(30, 42, 58, 0.98)',
        color: '#fff',
        width: '500px',
        focusConfirm: false,
        preConfirm: () => {
            const form = document.getElementById('form-nueva-empresa-ajax');
            if (!form.checkValidity()) {
                form.reportValidity();
                return false;
            }

            const razonSocial = document.getElementById('swal-razon-social').value;
            const ruc = document.getElementById('swal-ruc').value;
            
            if (!razonSocial || !ruc) {
                Swal.showValidationMessage('La razón social y el RUC son obligatorios');
                return false;
            }

            if (!/^\\d{11}$/.test(ruc)) {
                Swal.showValidationMessage('El RUC debe tener exactamente 11 dígitos numéricos');
                return false;
            }

            const formData = new FormData();
            formData.append('razon_social', razonSocial);
            formData.append('ruc', ruc);
            formData.append('direccion', document.getElementById('swal-direccion').value);
            formData.append('telefono', document.getElementById('swal-telefono').value);
            formData.append('contacto', document.getElementById('swal-contacto').value);

            return fetch(BASE_URL + '?c=empresas&a=guardarajax', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(response.statusText)
                }
                return response.json()
            })
            .then(data => {
                if (!data.success) {
                    Swal.showValidationMessage(data.mensaje || 'Error al guardar la empresa');
                    return false;
                }
                return data;
            })
            .catch(error => {
                Swal.showValidationMessage(`Request failed: ${error}`);
            });
        }
    }).then((result) => {
        if (result.isConfirmed && result.value && result.value.success) {
            showToast('success', result.value.mensaje);
            
            if (typeof onSuccess === 'function') {
                onSuccess(result.value.empresa);
            } else {
                // Default action: reload page
                setTimeout(() => location.reload(), 1000);
            }
        }
    });
}

function updateThemeIcon(isLight) {
    const icon = document.getElementById('theme-icon');
    if (!icon) return;
    
    if (isLight) {
        icon.className = 'fas fa-moon text-slate-400 group-hover:text-slate-600 transition-colors';
    } else {
        icon.className = 'fas fa-sun text-amber-400 group-hover:text-amber-300 transition-colors';
    }
}

// Initialize theme icon on load
document.addEventListener('DOMContentLoaded', () => {
    const isLight = document.documentElement.classList.contains('light-theme');
    updateThemeIcon(isLight);
});
