<?php
// 1. SEGURIDAD Y CONTEXTO
session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso Denegado");
}

// Variables de Configuración (Arquitectura Multi-usuario)
$nombre_bd = "MS_Datos";
$prefijo = $_SESSION['IDU_Prefix'] ?? '1'; // Ajustado a tu prefijo de tablas
$tb_solicitudes = $prefijo . "-Facturacion_Solicitudes"; 
$tb_ventas = $prefijo . "-Ventas_Cabecera";
$tb_clientes = $prefijo . "-Clientes";
$tb_detalle = $prefijo . "-Ventas_Detalle";
?>

<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    :root { --primary: #4f46e5; --success: #10b981; --warning: #f59e0b; --dark: #0f172a; }
    body { background-color: #f8fafc; font-family: 'Plus Jakarta Sans', sans-serif; }
    
    /* Estilos de Tarjetas */
    .kpi-card { border: none; border-radius: 20px; background: white; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1); transition: 0.3s; }
    .kpi-icon { width: 48px; height: 48px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; }
    
    /* Tabla Estilo Premium */
    .table-factura thead th { background: #f1f5f9; color: #475569; font-weight: 700; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; border: none; }
    .status-pill { padding: 6px 12px; border-radius: 12px; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; }
    .st-pendiente { background: #fef3c7; color: #92400e; }
    .st-timbrada { background: #dcfce7; color: #166534; }
    .st-rechazada { background: #fee2e2; color: #991b1b; }

    /* Modal Estilizado */
    .modal-content { border-radius: 25px; border: none; }
    .modal-header { background: var(--dark); color: white; border-radius: 25px 25px 0 0; padding: 1.5rem; }
    .section-title { font-size: 0.8rem; font-weight: 800; color: var(--primary); text-transform: uppercase; margin-bottom: 1rem; border-bottom: 2px solid #f1f5f9; padding-bottom: 5px; }
    .data-box { background: #f8fafc; padding: 12px; border-radius: 12px; border: 1px solid #e2e8f0; height: 100%; }
    .data-label { display: block; font-size: 0.65rem; color: #64748b; font-weight: 700; text-transform: uppercase; }
    .data-value { font-size: 0.9rem; font-weight: 700; color: #1e293b; }
</style>

<div class="container-fluid p-4">
    <div class="row mb-4 align-items-center">
        <div class="col-md-6">
            <h2 class="fw-800 text-dark mb-1">Solicitudes de Facturación</h2>
            <p class="text-muted">Procesa y timbra los CFDI 4.0 de tus clientes.</p>
        </div>
        <div class="col-md-6 text-md-end">
            <button class="btn btn-dark btn-lg rounded-pill px-4 shadow-sm" onclick="listarSolicitudes()">
                <i class="fas fa-sync-alt mr-2"></i> Actualizar
            </button>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-3">
            <div class="kpi-card p-3 d-flex align-items-center">
                <div class="kpi-icon bg-primary text-white mr-3 shadow-sm"><i class="fas fa-file-invoice"></i></div>
                <div><h3 class="mb-0 fw-800" id="kpi_total">0</h3><small class="text-muted fw-bold">Solicitudes Mes</small></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card p-3 d-flex align-items-center border-left border-warning" style="border-left-width: 5px !important;">
                <div class="kpi-icon bg-warning text-white mr-3 shadow-sm"><i class="fas fa-clock"></i></div>
                <div><h3 class="mb-0 fw-800" id="kpi_pendientes">0</h3><small class="text-muted fw-bold">Por Timbrar</small></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card p-3 d-flex align-items-center border-left border-success" style="border-left-width: 5px !important;">
                <div class="kpi-icon bg-success text-white mr-3 shadow-sm"><i class="fas fa-check-double"></i></div>
                <div><h3 class="mb-0 fw-800" id="kpi_timbradas">0</h3><small class="text-muted fw-bold">Completadas</small></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card p-3 d-flex align-items-center">
                <div class="kpi-icon bg-info text-white mr-3 shadow-sm"><i class="fas fa-dollar-sign"></i></div>
                <div><h3 class="mb-0 fw-800" id="kpi_monto">$0.00</h3><small class="text-muted fw-bold">Monto a Facturar</small></div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
        <div class="card-header bg-white py-3">
            <div class="input-group" style="max-width: 400px;">
                <span class="input-group-text bg-light border-0"><i class="fas fa-search"></i></span>
                <input type="text" id="buscador" class="form-control bg-light border-0" placeholder="Buscar por Folio, RFC o Cliente...">
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-hover table-factura align-middle mb-0">
                <thead>
                    <tr>
                        <th class="px-4">Fecha</th>
                        <th>Ticket/Folio</th>
                        <th>Cliente / RFC</th>
                        <th class="text-center">Total</th>
                        <th class="text-center">Estado</th>
                        <th class="text-end px-4">Acción</th>
                    </tr>
                </thead>
                <tbody id="tbody_solicitudes"></tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalDetalleFactura" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content shadow-lg">
            <div class="modal-header">
                <h5 class="fw-800 mb-0"><i class="fas fa-eye mr-2"></i>Detalle de Solicitud CFDI</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <div class="row g-4">
                    <div class="col-md-12">
                        <div class="section-title">Información para Facturación (CFDI 4.0)</div>
                        <div class="row g-2">
                            <div class="col-md-8"><div class="data-box"><span class="data-label">Razón Social</span><div class="data-value" id="det_razon">--</div></div></div>
                            <div class="col-md-4"><div class="data-box"><span class="data-label">RFC</span><div class="data-value text-primary" id="det_rfc">--</div></div></div>
                            <div class="col-md-4"><div class="data-box"><span class="data-label">C.P. Fiscal</span><div class="data-value" id="det_cp">--</div></div></div>
                            <div class="col-md-4"><div class="data-box"><span class="data-label">Uso CFDI</span><div class="data-value" id="det_uso">--</div></div></div>
                            <div class="col-md-4"><div class="data-box"><span class="data-label">Régimen</span><div class="data-value" id="det_regimen">--</div></div></div>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="section-title">Datos del Pago</div>
                        <div class="data-box bg-light">
                            <div class="mb-2"><span class="data-label">Folio Venta</span><span class="data-value" id="det_folio">--</span></div>
                            <div class="mb-2"><span class="data-label">Método / Forma</span><span class="data-value" id="det_metodo">--</span></div>
                            <div><span class="data-label">Total Pagado</span><span class="h4 fw-800 text-success" id="det_total">$0.00</span></div>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="section-title">Conceptos en Factura</div>
                        <div class="overflow-auto" style="max-height: 150px;" id="det_productos">
                            </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer border-0 bg-light rounded-bottom-5">
                <button type="button" class="btn btn-outline-secondary rounded-pill px-4" data-bs-dismiss="modal">Cerrar</button>
                <button type="button" class="btn btn-primary rounded-pill px-4 fw-bold shadow" id="btn_timbrar_final">
                    <i class="fas fa-file-signature mr-2"></i> Procesar Timbrado
                </button>
            </div>
        </div>
    </div>
</div>

<script>
const DB = "<?php echo $nombre_bd; ?>";
const TB_SOL = "<?php echo $tb_solicitudes; ?>";
const TB_VEN = "<?php echo $tb_ventas; ?>";
const TB_CLI = "<?php echo $tb_clientes; ?>";
const TB_DET = "<?php echo $tb_detalle; ?>";

document.addEventListener('DOMContentLoaded', listarSolicitudes);

// Filtrado de tabla
document.getElementById('buscador').addEventListener('keyup', (e) => {
    const term = e.target.value.toLowerCase();
    document.querySelectorAll('#tbody_solicitudes tr').forEach(row => {
        row.style.display = row.innerText.toLowerCase().includes(term) ? '' : 'none';
    });
});

function listarSolicitudes() {
    // Join para traer datos de la solicitud + cabecera de venta + nombre cliente
    const sql = `SELECT s.*, v.Folio, v.Total as TotalVenta, v.Metodo_Pago, c.Nombre as ClienteNombre 
                 FROM \`${TB_SOL}\` s
                 JOIN \`${TB_VEN}\` v ON s.ID_Venta = v.ID_Venta
                 JOIN \`${TB_CLI}\` c ON s.IDC_Cliente = c.IDC
                 ORDER BY s.Fecha_Solicitud DESC LIMIT 100`;

    fetch('../librerias/AJAX/Select.php', { 
        method: 'POST', 
        body: `sql=${encodeURIComponent(sql)}&db=${DB}`, 
        headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
    })
    .then(r => r.json())
    .then(res => {
        const tbody = document.getElementById('tbody_solicitudes');
        tbody.innerHTML = '';
        let p = 0, t = 0, totalMonto = 0;

        if (res.data && res.data.length > 0) {
            res.data.forEach(s => {
                if(s.Estado === 'Pendiente') p++;
                if(s.Estado === 'Timbrada') t++;
                totalMonto += parseFloat(s.TotalVenta);

                const fiscal = JSON.parse(s.Datos_Fiscales_Snapshot || '{}');
                const badge = s.Estado === 'Pendiente' ? 'st-pendiente' : (s.Estado === 'Timbrada' ? 'st-timbrada' : 'st-rechazada');

                tbody.innerHTML += `
                    <tr>
                        <td class="px-4 fw-bold text-muted" style="font-size:0.8rem;">${s.Fecha_Solicitud}</td>
                        <td class="fw-800 text-dark">${s.Folio}</td>
                        <td>
                            <div class="fw-bold">${fiscal.razon || s.ClienteNombre}</div>
                            <div class="small text-primary fw-bold">${fiscal.rfc || 'Sin RFC'}</div>
                        </td>
                        <td class="text-center fw-800">$${parseFloat(s.TotalVenta).toLocaleString()}</td>
                        <td class="text-center"><span class="status-pill ${badge}">${s.Estado}</span></td>
                        <td class="text-end px-4">
                            <button class="btn btn-sm btn-dark rounded-pill px-3" onclick='verDetalle(${JSON.stringify(s)})'>
                                <i class="fas fa-eye"></i> Detalle
                            </button>
                        </td>
                    </tr>`;
            });
        }
        document.getElementById('kpi_total').innerText = res.data ? res.data.length : 0;
        document.getElementById('kpi_pendientes').innerText = p;
        document.getElementById('kpi_timbradas').innerText = t;
        document.getElementById('kpi_monto').innerText = '$' + totalMonto.toLocaleString();
    });
}

async function verDetalle(s) {
    const fiscal = JSON.parse(s.Datos_Fiscales_Snapshot || '{}');
    
    // Poblar modal
    document.getElementById('det_razon').innerText = fiscal.razon || 'N/A';
    document.getElementById('det_rfc').innerText = fiscal.rfc || 'N/A';
    document.getElementById('det_cp').innerText = fiscal.cp || 'N/A';
    document.getElementById('det_uso').innerText = s.Uso_CFDI || fiscal.uso || 'G03';
    document.getElementById('det_regimen').innerText = fiscal.regimen || '601';
    document.getElementById('det_folio').innerText = s.Folio;
    document.getElementById('det_metodo').innerText = `${s.Metodo_Pago} / ${s.Forma_Pago}`;
    document.getElementById('det_total').innerText = '$' + parseFloat(s.TotalVenta).toLocaleString();

    // Obtener productos
    const sqlDet = `SELECT * FROM \`${TB_DET}\` WHERE ID_Venta = ${s.ID_Venta}`;
    const resDet = await fetch('../librerias/AJAX/Select.php', { 
        method: 'POST', 
        body: `sql=${encodeURIComponent(sqlDet)}&db=${DB}`, 
        headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
    }).then(r => r.json());

    const contProd = document.getElementById('det_productos');
    contProd.innerHTML = '';
    if(resDet.data) {
        resDet.data.forEach(p => {
            contProd.innerHTML += `
                <div class="d-flex justify-content-between border-bottom py-1">
                    <span class="small fw-bold">${parseInt(p.Cantidad)} x ${p.Nombre_Producto}</span>
                    <span class="small text-muted font-weight-bold">$${parseFloat(p.Subtotal).toLocaleString()}</span>
                </div>`;
        });
    }

    // Ajustar botón si ya está timbrada
    const btn = document.getElementById('btn_timbrar_final');
    if(s.Estado === 'Timbrada') {
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-check"></i> YA TIMBRADA';
        btn.className = "btn btn-success rounded-pill px-4 fw-bold";
    } else {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-file-signature mr-2"></i> Procesar Timbrado';
        btn.className = "btn btn-primary rounded-pill px-4 fw-bold shadow";
        btn.onclick = () => procesarTimbrado(s.ID_Solicitud);
    }

    $('#modalDetalleFactura').modal('show');
}

function procesarTimbrado(id) {
    Swal.fire({
        title: '¿Enviar al SAT?',
        text: "Se generará el sello digital y el archivo XML.",
        icon: 'info',
        showCancelButton: true,
        confirmButtonText: 'Sí, timbrar ahora',
        confirmButtonColor: '#4f46e5'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire('Procesando', 'Conectando con el PAC...', 'info');
            // Aquí iría tu lógica de conexión con el PAC
            // Por ahora, simulamos el éxito actualizando el estado
            const sql = `UPDATE \`${TB_SOL}\` SET Estado='Timbrada', Fecha_Procesado=NOW() WHERE ID_Solicitud=${id}`;
            fetch('../librerias/AJAX/Execute.php', { 
                method: 'POST', 
                body: `sql=${encodeURIComponent(sql)}&db=${DB}`, 
                headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
            }).then(() => {
                Swal.fire('¡Éxito!', 'Factura Timbrada Correctamente', 'success');
                $('#modalDetalleFactura').modal('hide');
                listarSolicitudes();
            });
        }
    });
}
</script>