<?php
/**
 * APP: Libro Diario Fiscal ELITE v11.0 - VERSIÓN INTEGRAL DEFINITIVA
 * UI: Drawers Derechos (Captura 1/4, Reporte 3/4).
 * Lógica: Abono = Entrada (Verde), Cargo = Salida (Rojo).
 * Fiscal: IVA Neto = IVA Trasladado - IVA Acreditable.
 */
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso Denegado");
}

$DB_D = "MS_Datos"; 
$IDUg = $_SESSION['IDUg'] ?? 1; 
$IDU  = $_SESSION['IDU'] ?? 0;
$PRE  = $IDUg . "-"; 
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    :root { --ingreso: #28a745; --gasto: #dc3545; --azul: #4e73df; }
    body { background-color: #f4f7f6; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
    
    /* ACCIONES */
    .action-container { display: flex; gap: 12px; margin-bottom: 20px; }
    .action-card { flex: 1; background: #fff; padding: 20px; border-radius: 12px; text-align: center; cursor: pointer; transition: 0.3s; border: 1px solid #eee; }
    .action-card:hover { border-color: var(--azul); transform: translateY(-3px); box-shadow: 0 5px 15px rgba(0,0,0,0.08); }
    .action-card i { font-size: 2rem; display: block; margin-bottom: 5px; }
    .action-card span { font-weight: bold; font-size: 10px; text-transform: uppercase; color: #333; }

    /* KPIs */
    .card-kpi { border: none; border-radius: 12px; background: #fff; box-shadow: 0 4px 12px rgba(0,0,0,0.05); border-top: 5px solid var(--azul); transition: 0.3s; }
    .kpi-clickable { cursor: pointer; }
    .kpi-clickable:hover { transform: scale(1.01); box-shadow: 0 6px 15px rgba(0,0,0,0.1); }
    
    /* FILAS */
    .bg-grad-ingreso { background: linear-gradient(to left, rgba(40, 167, 69, 0.12), #fff) !important; border-right: 5px solid var(--ingreso) !important; }
    .bg-grad-gasto { background: linear-gradient(to left, rgba(220, 53, 69, 0.12), #fff) !important; border-right: 5px solid var(--gasto) !important; }

    /* DRAWERS DERECHOS */
    .modal.drawer-right .modal-dialog {
        position: fixed; margin: auto; height: 100%; top: 0; right: -100%; 
        transition: right 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
    }
    .modal.drawer-right.show .modal-dialog { right: 0; }
    .modal.drawer-right .modal-content { height: 100%; border-radius: 0; border: none; overflow-y: auto; box-shadow: -15px 0 30px rgba(0,0,0,0.1); }

    .drawer-1-4 { width: 420px !important; max-width: 420px !important; }
    .drawer-3-4 { width: 75% !important; max-width: 75% !important; }

    /* SWITCH */
    .switch-tax { position: relative; display: inline-block; width: 40px; height: 20px; vertical-align: middle; }
    .switch-tax input { opacity: 0; width: 0; height: 0; }
    .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 34px; }
    .slider:before { position: absolute; content: ""; height: 14px; width: 14px; left: 3px; bottom: 3px; background-color: white; transition: .4s; border-radius: 50%; }
    input:checked + .slider { background-color: var(--ingreso); }
    input:checked + .slider:before { transform: translateX(20px); }

    .info-box { background: #f8f9fa; border: 1px solid #eee; border-radius: 8px; padding: 12px; margin-bottom: 15px; }
    .item-row { font-size: 12px; border-bottom: 1px solid #eee; padding: 5px 0; display: flex; justify-content: space-between; }
    .iva-row { display: flex; justify-content: space-between; padding: 6px 0; border-bottom: 1px dashed #eee; font-size: 12px; }
</style>

<div class="container-fluid p-3">
    <div class="action-container">
        <div class="action-card" onclick="window.abrirNuevoAsiento()">
            <i class="fas fa-plus-circle text-primary"></i>
            <span>Nuevo Asiento</span>
        </div>
        <div class="action-card" onclick="window.abrirImportar()">
            <i class="fas fa-file-import text-dark"></i>
            <span>Importar Datos</span>
        </div>
        <div class="action-card" onclick="window.abrirDetalleGeneral()">
            <i class="fas fa-print text-success"></i>
            <span>Reporte Fiscal</span>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card card-kpi p-3"><small class="text-muted font-weight-bold uppercase">Balance Global</small><h3 class="mb-0 font-weight-bold" id="kpi_balance_gral">$ 0.00</h3></div>
        </div>
        <div class="col-md-4">
            <div class="card card-kpi p-3" style="border-top-color: var(--ingreso);"><small class="text-muted font-weight-bold text-success uppercase">Flujo Hoy</small><h3 class="mb-0 font-weight-bold text-success" id="kpi_hoy">$ 0.00</h3></div>
        </div>
        <div class="col-md-4">
            <div class="card card-kpi p-3 kpi-clickable" id="kpi_sat_card" onclick="window.abrirDesgloseIVA()">
                <div class="d-flex justify-content-between"><small class="text-muted font-weight-bold uppercase" id="kpi_sat_label">IVA SAT (Neto)</small><i class="fas fa-search-dollar small text-muted"></i></div>
                <h3 class="mb-0 font-weight-bold" id="kpi_sat">$ 0.00</h3>
            </div>
        </div>
    </div>

    <div class="card shadow-sm border-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="bg-light small font-weight-bold text-uppercase">
                    <tr><th width="70" class="text-center">Ref</th><th>Descripción</th><th width="100" class="text-center">Origen</th><th width="160" class="text-right">Monto Total</th><th width="80" class="text-center">Ver</th></tr>
                </thead>
                <tbody id="tabla_libro"></tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade drawer-right" id="modalNuevo" tabindex="-1">
    <div class="modal-dialog drawer-1-4">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white rounded-0"><h5 class="modal-title font-weight-bold">Registro Manual</h5><button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>
            <div class="modal-body p-4">
                <form id="formManual">
                    <div class="form-group mb-3"><label class="small font-weight-bold uppercase">Concepto *</label><input type="text" class="form-control" id="ins_concepto"></div>
                    <div class="p-3 bg-light border rounded text-center mb-3">
                        <label class="small font-weight-bold uppercase">Total con IVA ($) *</label><input type="number" step="0.01" class="form-control form-control-lg text-center font-weight-bold" id="ins_monto" oninput="window.calcIVA()">
                        <div class="mt-2"><span class="small font-weight-bold">¿Desglosar IVA SAT?</span> <label class="switch-tax ml-2"><input type="checkbox" id="ins_aplica_iva" checked onchange="window.calcIVA()"><span class="slider"></span></label></div>
                    </div>
                    <div id="box_iva" class="alert alert-secondary py-2 small mb-3">
                        <div class="d-flex justify-content-between"><span>Base:</span> <span id="lbl_sub" class="font-weight-bold">$ 0.00</span></div>
                        <div class="d-flex justify-content-between text-success"><span>IVA:</span> <span id="lbl_iva" class="font-weight-bold">$ 0.00</span></div>
                    </div>
                    <div class="row">
                        <div class="col-6"><label class="small font-weight-bold">Cuenta</label><select id="ins_metodo" class="form-control"><option value="Caja">Caja</option><option value="Bancos">Bancos</option></select></div>
                        <div class="col-6"><label class="small font-weight-bold">Tipo</label><select id="ins_tipo" class="form-control font-weight-bold"><option value="INGRESO">COBRO (+)</option><option value="GASTO">PAGO (-)</option></select></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer border-0"><button class="btn btn-primary btn-block py-3 font-weight-bold" onclick="window.guardarManual()">PROCESAR REGISTRO</button></div>
        </div>
    </div>
</div>

<div class="modal fade drawer-right" id="modalImportar" tabindex="-1">
    <div class="modal-dialog drawer-1-4">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white rounded-0"><h5 class="modal-title font-weight-bold">Pendientes Hoy</h5><button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>
            <div class="modal-body p-0">
                <div class="p-3 bg-light border-bottom">
                    <select class="form-control font-weight-bold" id="f_fuente" onchange="window.cargarPendientes()">
                        <option value="VENTA">Ventas Directas</option><option value="COMPRA">Compras / Gastos</option><option value="PEDIDO">Pedidos de Venta</option><option value="SERVICIO">Órdenes Servicio</option>
                    </select>
                </div>
                <div id="lista_pendientes" class="list-group list-group-flush"></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade drawer-right" id="modalPreImportar" tabindex="-1" style="z-index: 1060;">
    <div class="modal-dialog drawer-1-4">
        <div class="modal-content border-left shadow-lg">
            <div class="modal-header bg-info text-white rounded-0"><h5 class="modal-title font-weight-bold" id="pre_titulo">Detalle Doc.</h5><button type="button" class="close text-white" onclick="$('#modalPreImportar').modal('hide')"><span>&times;</span></button></div>
            <div class="modal-body p-4">
                <div class="mb-4 text-center border-bottom pb-3">
                    <small class="text-muted d-block uppercase font-weight-bold">Monto del Documento</small>
                    <h2 class="font-weight-bold text-primary" id="pre_total">$ 0.00</h2>
                </div>
                <label class="small font-weight-bold uppercase text-muted">Contenido del Folio:</label>
                <div id="pre_items" class="bg-light p-3 rounded mb-4" style="max-height: 250px; overflow-y: auto; border: 1px solid #eee;"></div>
                <div class="p-3 border rounded bg-white shadow-sm mb-4">
                    <div class="d-flex justify-content-between align-items-center"><span class="font-weight-bold small">¿Registrar IVA SAT?</span> <label class="switch-tax"><input type="checkbox" id="pre_iva_toggle" checked><span class="slider"></span></label></div>
                </div>
                <input type="hidden" id="pre_id"><input type="hidden" id="pre_tipo"><input type="hidden" id="pre_monto_raw"><input type="hidden" id="pre_folio">
                <button class="btn btn-success btn-block py-3 font-weight-bold shadow-lg" onclick="window.confirmarImportacion()">IMPORTAR AL LIBRO</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade drawer-right" id="modalDetalleGral" tabindex="-1">
    <div class="modal-dialog drawer-3-4">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white rounded-0"><h5 class="modal-title font-weight-bold">Reporte Diario de Auditoría</h5><button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>
            <div class="modal-body p-4" id="imprimirAreaContable">
                <div class="d-flex justify-content-between mb-4 border-bottom pb-2">
                    <h3>Libro Diario Fiscal</h3>
                    <h2 id="print_balance" class="font-weight-bold text-success">$ 0.00</h2>
                </div>
                <table class="table table-sm table-bordered"><thead class="bg-light text-center small font-weight-bold"><tr><th>Asiento</th><th>Cuenta</th><th>Concepto</th><th>Abono (Venta)</th><th>Cargo (Compra)</th></tr></thead><tbody id="tbody_detalle_gral" class="small"></tbody></table>
            </div>
            <div class="modal-footer border-0 bg-light"><button class="btn btn-success px-5 font-weight-bold shadow" onclick="window.imprimirReporte()"><i class="fas fa-print mr-2"></i>Imprimir Reporte</button></div>
        </div>
    </div>
</div>

<div class="modal fade drawer-right" id="modalDesgloseIVA" tabindex="-1">
    <div class="modal-dialog drawer-1-4">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white rounded-0"><h5 class="modal-title font-weight-bold">Auditoría de IVA Hoy</h5><button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>
            <div class="modal-body p-4">
                <div class="mb-4 text-center"><small class="text-muted d-block uppercase font-weight-bold">IVA Neto (Ventas-Compras)</small><h2 id="iva_neto_modal" class="font-weight-bold">$ 0.00</h2></div>
                <h6 class="font-weight-bold text-success border-bottom pb-2 small">IVA TRASLADADO (VENTAS)</h6><div id="lista_iva_ventas" class="mb-4"></div>
                <h6 class="font-weight-bold text-danger border-bottom pb-2 small">IVA ACREDITABLE (COMPRAS)</h6><div id="lista_iva_compras" class="mb-4"></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade drawer-right" id="modalVerAsiento" tabindex="-1">
    <div class="modal-dialog drawer-1-4">
        <div class="modal-content">
            <div class="modal-header bg-info text-white rounded-0"><h5 class="modal-title font-weight-bold">Detalle de Partida</h5><button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>
            <div class="modal-body p-4">
                <h6 class="font-weight-bold border-bottom pb-1">ARTÍCULOS / CONTENIDO</h6>
                <div id="ver_articulos" class="info-box small"></div>
                <h6 class="font-weight-bold border-bottom pb-1 mt-4">ASIENTO CONTABLE</h6>
                <div id="ver_partida" class="table-responsive"></div>
            </div>
        </div>
    </div>
</div>



<script>
/**
 * --- NÚCLEO JAVASCRIPT v11.0 ---
 */
const DB = "<?php echo $DB_D; ?>";
const PRE = "<?php echo $PRE; ?>";
const USU = "<?php echo $IDU; ?>";
let isSaving = false;
let globalDataIVA = [];

window.apiSQL = async function(sql, db, type='Select') {
    try {
        const r = await fetch('../librerias/AJAX/' + type + '.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'sql=' + encodeURIComponent(sql) + '&db=' + db
        });
        return await r.json();
    } catch (e) { return {status:'error'}; }
};

window.cargarLibro = async function() {
    const cuentasM = "'Caja','Bancos','Efectivo','Tarjeta','Transferencia'";
    
    // Balance Global Histórico
    const resH = await window.apiSQL("SELECT (SELECT IFNULL(SUM(Abono),0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` WHERE Cuenta_Nombre IN (" + cuentasM + ")) as InM, (SELECT IFNULL(SUM(Cargo),0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` WHERE Cuenta_Nombre IN (" + cuentasM + ")) as OutM", DB);
    const balG = (resH.data && resH.data[0]) ? (parseFloat(resH.data[0].InM) - parseFloat(resH.data[0].OutM)) : 0;
    document.getElementById('kpi_balance_gral').innerText = "$ " + balG.toLocaleString('en-US',{minimumFractionDigits:2});

    // Actividad de Hoy
    const resT = await window.apiSQL("SELECT c.*, (SELECT COUNT(*) FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` WHERE ID_Asiento = c.ID_Asiento AND Abono > 0 AND Cuenta_Nombre IN (" + cuentasM + ")) as EsEntrada, (SELECT IFNULL(SUM(Monto_Impuesto),0) FROM " + DB + ".`" + PRE + "Libro_Impuestos_Detalle` i JOIN " + DB + ".`" + PRE + "Libro_Asientos_Detalle` d ON i.ID_Movimiento = d.ID_Movimiento WHERE d.ID_Asiento = c.ID_Asiento) as IvaT FROM " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` c WHERE DATE(c.Fecha_Contable) = CURDATE() ORDER BY c.ID_Asiento DESC", DB);
    
    globalDataIVA = resT.data || [];
    const tbody = document.getElementById('tabla_libro');
    tbody.innerHTML = ''; let tHoy = 0; let tIvaNeto = 0;

    globalDataIVA.forEach(function(r) {
        const isIn = parseInt(r.EsEntrada) > 0;
        const monto = parseFloat(r.Total_Asiento || 0);
        const iva = parseFloat(r.IvaT || 0);
        tHoy += isIn ? monto : -monto;
        tIvaNeto += isIn ? iva : -iva;
        tbody.innerHTML += '<tr class="' + (isIn ? 'bg-grad-ingreso' : 'bg-grad-gasto') + '"><td class="text-center font-weight-bold">#' + r.ID_Asiento + '</td><td>' + r.Concepto_General + '</td><td class="text-center small font-weight-bold">' + r.Origen_Tipo + '</td><td class="text-right font-weight-bold ' + (isIn ? 'text-success' : 'text-danger') + '">$ ' + monto.toFixed(2) + '</td><td class="text-center"><button class="btn btn-sm btn-white border shadow-sm" onclick="window.verAsientoCompleto(' + r.ID_Asiento + ',\'' + r.Origen_Tipo + '\',' + r.Origen_ID + ')"><i class="fas fa-eye text-dark"></i></button></td></tr>';
    });

    document.getElementById('kpi_hoy').innerText = "$ " + tHoy.toFixed(2);
    const kpiIva = document.getElementById('kpi_sat');
    const kpiCard = document.getElementById('kpi_sat_card');
    const kpiLabel = document.getElementById('kpi_sat_label');
    kpiIva.innerText = "$ " + tIvaNeto.toFixed(2);
    if(tIvaNeto >= 0) {
        kpiIva.className = "mb-0 font-weight-bold text-danger";
        kpiCard.style.borderTopColor = "#dc3545"; kpiLabel.innerText = "IVA SAT (A PAGAR)";
    } else {
        kpiIva.className = "mb-0 font-weight-bold text-success";
        kpiCard.style.borderTopColor = "#28a745"; kpiLabel.innerText = "IVA SAT (A FAVOR)";
    }
};

window.guardarManual = async function() {
    if(isSaving) return;
    const c = document.getElementById('ins_concepto').value.trim();
    const m = parseFloat(document.getElementById('ins_monto').value);
    if(!m || !c) return Swal.fire('Error','Datos incompletos','warning');

    isSaving = true;
    const aplicaIVA = document.getElementById('ins_aplica_iva').checked;
    const sub = aplicaIVA ? m / 1.16 : m; const iva = aplicaIVA ? m - sub : 0;
    const met = document.getElementById('ins_metodo').value;
    const tipo = document.getElementById('ins_tipo').value;

    const resCab = await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` (IDU_Usuario, Origen_Tipo, Origen_ID, Concepto_General, Total_Asiento, Fecha_Contable) VALUES (" + USU + ", 'MANUAL', 0, '" + c.replace(/'/g, "''") + "', " + m + ", NOW())", DB, 'Execute');
    
    if (resCab.status === 'success') {
        const resId = await window.apiSQL("SELECT MAX(ID_Asiento) as id FROM " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` WHERE IDU_Usuario=" + USU, DB);
        const idA = resId.data[0].id;
        const ctaIVA = (tipo === 'INGRESO') ? 'IVA Trasladado' : 'IVA Acreditable';

        if(tipo === 'INGRESO') {
            await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", '" + met + "', " + m + ", 0)", DB, 'Execute');
            await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", 'Ventas', 0, " + sub + ")", DB, 'Execute');
            if(iva > 0) {
                await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", '" + ctaIVA + "', 0, " + iva + ")", DB, 'Execute');
                const lastDet = await window.apiSQL("SELECT MAX(ID_Movimiento) as id FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` WHERE ID_Asiento=" + idA, DB);
                await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Impuestos_Detalle` (ID_Movimiento, Tipo_Impuesto, Tasa, Monto_Impuesto) VALUES (" + lastDet.data[0].id + ", 'IVA', 16, " + iva + ")", DB, 'Execute');
            }
        } else {
            await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", 'Gastos', 0, " + sub + ")", DB, 'Execute');
            if(iva > 0) {
                await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", '" + ctaIVA + "', 0, " + iva + ")", DB, 'Execute');
                const lastDet = await window.apiSQL("SELECT MAX(ID_Movimiento) as id FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` WHERE ID_Asiento=" + idA, DB);
                await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Impuestos_Detalle` (ID_Movimiento, Tipo_Impuesto, Tasa, Monto_Impuesto) VALUES (" + lastDet.data[0].id + ", 'IVA', 16, " + iva + ")", DB, 'Execute');
            }
            await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", '" + met + "', 0, " + m + ")", DB, 'Execute');
        }
        Swal.fire('Éxito','Registrado','success'); $('#modalNuevo').modal('hide'); window.cargarLibro();
    }
    isSaving = false;
};

window.cargarPendientes = async function() {
    const f = document.getElementById('f_fuente').value;
    let sql = "";
    if(f === 'VENTA') sql = "SELECT ID_Venta as id, Folio, Total as t FROM " + DB + ".`" + PRE + "Ventas_Cabecera` WHERE DATE(Fecha) = CURDATE() AND ID_Venta NOT IN (SELECT IFNULL(Origen_ID,0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` WHERE Origen_Tipo='VENTA')";
    else if(f === 'COMPRA') sql = "SELECT ID_Gasto as id, Referencia as Folio, Monto as t FROM " + DB + ".`" + PRE + "Gastos` WHERE DATE(Fecha) = CURDATE() AND ID_Gasto NOT IN (SELECT IFNULL(Origen_ID,0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` WHERE Origen_Tipo='COMPRA')";
    else if(f === 'PEDIDO') sql = "SELECT ID_Pedido as id, Folio, Total_Venta as t FROM " + DB + ".`" + PRE + "Pedidos_Ventas` WHERE DATE(Fecha_Registro) = CURDATE() AND ID_Pedido NOT IN (SELECT IFNULL(Origen_ID,0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` WHERE Origen_Tipo='PEDIDO')";
    else if(f === 'SERVICIO') sql = "SELECT ID_Orden as id, Folio, Total_Estimado as t FROM " + DB + ".`" + PRE + "Ordenes_Servicio` WHERE DATE(Fecha_Ingreso) = CURDATE() AND ID_Orden NOT IN (SELECT IFNULL(Origen_ID,0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` WHERE Origen_Tipo='SERVICIO')";
    
    const r = await window.apiSQL(sql, DB); const data = r.data || [];
    document.getElementById('lista_pendientes').innerHTML = data.map(function(i) {
        return '<button class="list-group-item list-group-item-action d-flex justify-content-between" onclick="window.preImportar(\''+f+'\','+i.id+','+i.t+',\''+i.Folio+'\')"><b>'+i.Folio+'</b> <span>$'+i.t+'</span></button>';
    }).join('') || '<div class="p-3 text-center">Sin pendientes hoy.</div>';
};

window.preImportar = async function(tipo, id, total, folio) {
    document.getElementById('pre_titulo').innerText = tipo + ": " + folio;
    document.getElementById('pre_total').innerText = "$ " + total.toFixed(2);
    document.getElementById('pre_id').value = id; document.getElementById('pre_tipo').value = tipo;
    document.getElementById('pre_monto_raw').value = total; document.getElementById('pre_folio').value = folio;
    
    let tD = (tipo === 'VENTA') ? 'Ventas_Detalle' : (tipo === 'PEDIDO' ? 'Pedidos_Ventas_Detalle' : (tipo === 'SERVICIO' ? 'Ordenes_Servicio_Detalle' : 'Gastos_Detalle'));
    let cID = (tipo === 'VENTA') ? 'ID_Venta' : (tipo === 'PEDIDO' ? 'ID_Pedido' : (tipo === 'SERVICIO' ? 'ID_Orden' : 'ID_Gasto'));
    
    const r = await window.apiSQL("SELECT Cantidad, Descripcion, Precio_Unitario FROM " + DB + ".`" + PRE + tD + "` WHERE " + cID + "=" + id, DB);
    const items = r.data || [];
    document.getElementById('pre_items').innerHTML = items.map(function(i) {
        return '<div class="item-row"><span>' + i.Cantidad + ' x ' + i.Descripcion + '</span><b>$' + i.Precio_Unitario + '</b></div>';
    }).join('') || 'Sin desglose de artículos.';
    $('#modalPreImportar').modal('show');
};

window.confirmarImportacion = async function() {
    if(isSaving) return; isSaving = true;
    const id = document.getElementById('pre_id').value; const tipo = document.getElementById('pre_tipo').value;
    const total = parseFloat(document.getElementById('pre_monto_raw').value); const folio = document.getElementById('pre_folio').value;
    const aplicaIVA = document.getElementById('pre_iva_toggle').checked;
    const sub = aplicaIVA ? total / 1.16 : total; const iva = aplicaIVA ? total - sub : 0;
    const ctaIVA = (tipo === 'COMPRA') ? 'IVA Acreditable' : 'IVA Trasladado';

    const resCab = await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` (IDU_Usuario, Origen_Tipo, Origen_ID, Concepto_General, Total_Asiento, Fecha_Contable) VALUES (" + USU + ", '" + tipo + "', " + id + ", 'Importación: " + folio + "', " + total + ", NOW())", DB, 'Execute');
    if (resCab.status === 'success') {
        const resId = await window.apiSQL("SELECT MAX(ID_Asiento) as id FROM " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` WHERE IDU_Usuario=" + USU, DB);
        const idA = resId.data[0].id;
        if(tipo === 'COMPRA') {
            await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", 'Gastos', 0, " + sub + ")", DB, 'Execute');
            if(aplicaIVA) await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", '" + ctaIVA + "', 0, " + iva + ")", DB, 'Execute');
            await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", 'Caja', 0, " + total + ")", DB, 'Execute');
        } else {
            await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", 'Caja', " + total + ", 0)", DB, 'Execute');
            await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", 'Ventas', 0, " + sub + ")", DB, 'Execute');
            if(aplicaIVA) await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Asientos_Detalle` (ID_Asiento, Cuenta_Nombre, Abono, Cargo) VALUES (" + idA + ", '" + ctaIVA + "', 0, " + iva + ")", DB, 'Execute');
        }
        if(iva > 0) {
            const lastDet = await window.apiSQL("SELECT MAX(ID_Movimiento) as id FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` WHERE ID_Asiento=" + idA + " AND Cuenta_Nombre LIKE '%IVA%'", DB);
            await window.apiSQL("INSERT INTO " + DB + ".`" + PRE + "Libro_Impuestos_Detalle` (ID_Movimiento, Tipo_Impuesto, Tasa, Monto_Impuesto) VALUES (" + lastDet.data[0].id + ", 'IVA', 16, " + iva + ")", DB, 'Execute');
        }
        $('#modalPreImportar').modal('hide'); $('#modalImportar').modal('hide'); window.cargarLibro();
    }
    isSaving = false;
};

window.verAsientoCompleto = async function(idA, tipo, idO) {
    let tD = (tipo === 'VENTA') ? 'Ventas_Detalle' : (tipo === 'PEDIDO' ? 'Pedidos_Ventas_Detalle' : (tipo === 'SERVICIO' ? 'Ordenes_Servicio_Detalle' : (tipo === 'COMPRA' ? 'Gastos_Detalle' : '')));
    let cID = (tipo === 'VENTA') ? 'ID_Venta' : (tipo === 'PEDIDO' ? 'ID_Pedido' : (tipo === 'SERVICIO' ? 'ID_Orden' : (tipo === 'COMPRA' ? 'ID_Gasto' : '')));
    
    if(tD) {
        const rArt = await window.apiSQL("SELECT Cantidad, Descripcion, Precio_Unitario FROM " + DB + ".`" + PRE + tD + "` WHERE " + cID + "=" + idO, DB);
        document.getElementById('ver_articulos').innerHTML = (rArt.data || []).map(function(i) { return '<div class="item-row"><span>' + i.Cantidad + ' x ' + i.Descripcion + '</span><b>$' + i.Precio_Unitario + '</b></div>'; }).join('') || 'Sin desglose.';
    } else { document.getElementById('ver_articulos').innerHTML = 'Registro Manual.'; }

    const resP = await window.apiSQL("SELECT * FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` WHERE ID_Asiento=" + idA, DB);
    let h = '<table class="table table-sm small"><thead><tr><th>Cuenta</th><th>Abono</th><th>Cargo</th></tr></thead><tbody>';
    (resP.data || []).forEach(function(i) { h += '<tr><td>' + i.Cuenta_Nombre + '</td><td class="text-success">' + (i.Abono>0?'$'+i.Abono:'') + '</td><td class="text-danger">' + (i.Cargo>0?'$'+i.Cargo:'') + '</td></tr>'; });
    document.getElementById('ver_partida').innerHTML = h + '</tbody></table>';
    $('#modalVerAsiento').modal('show');
};

window.abrirDesgloseIVA = function() {
    let hV = ''; let hC = ''; let tV = 0; let tC = 0;
    globalDataIVA.forEach(function(r) {
        const isIn = parseInt(r.EsEntrada) > 0; const iva = parseFloat(r.IvaT || 0);
        if(iva <= 0) return;
        if(isIn) { tV += iva; hV += '<div class="iva-row"><small>#' + r.ID_Asiento + ' ' + r.Concepto_General.substring(0,18) + '</small><span>$' + iva.toFixed(2) + '</span></div>'; }
        else { tC += iva; hC += '<div class="iva-row"><small>#' + r.ID_Asiento + ' ' + r.Concepto_General.substring(0,18) + '</small><span>$' + iva.toFixed(2) + '</span></div>'; }
    });
    document.getElementById('lista_iva_ventas').innerHTML = hV || 'Sin ventas';
    document.getElementById('lista_iva_compras').innerHTML = hC || 'Sin compras';
    const neto = tV - tC; document.getElementById('iva_neto_modal').innerText = "$ " + neto.toFixed(2);
    document.getElementById('iva_neto_modal').className = neto >= 0 ? "font-weight-bold text-danger" : "font-weight-bold text-success";
    $('#modalDesgloseIVA').modal('show');
};

window.abrirDetalleGeneral = async function() {
    const res = await window.apiSQL("SELECT d.*, c.Concepto_General FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` d JOIN " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` c ON d.ID_Asiento = c.ID_Asiento WHERE DATE(c.Fecha_Contable) = CURDATE() ORDER BY d.ID_Asiento ASC", DB);
    const data = res.data || [];
    document.getElementById('tbody_detalle_gral').innerHTML = data.map(function(i) {
        return '<tr><td class="text-center font-weight-bold">#' + i.ID_Asiento + '</td><td>' + i.Cuenta_Nombre + '</td><td class="small">' + i.Concepto_General + '</td><td class="text-right text-success">' + (i.Abono>0?'$'+parseFloat(i.Abono).toFixed(2):'') + '</td><td class="text-right text-danger">' + (i.Cargo>0?'$'+parseFloat(i.Cargo).toFixed(2):'') + '</td></tr>';
    }).join('');
    document.getElementById('print_balance').innerText = document.getElementById('kpi_hoy').innerText;
    $('#modalDetalleGral').modal('show');
};

window.calcIVA = function() {
    const t = parseFloat(document.getElementById('ins_monto').value) || 0;
    const a = document.getElementById('ins_aplica_iva').checked;
    const s = a ? t / 1.16 : t; const i = a ? t - s : 0;
    document.getElementById('box_iva').style.display = a ? 'block' : 'none';
    document.getElementById('lbl_sub').innerText = "$ " + s.toFixed(2);
    document.getElementById('lbl_iva').innerText = "$ " + i.toFixed(2);
};

window.imprimirReporte = function() {
    const con = document.getElementById('imprimirAreaContable').innerHTML;
    const v = window.open('', '', 'height=800,width=1100');
    v.document.write('<html><head><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"><style>body{padding:40px;}.table td,.table th{border:1px solid #333!important;}</style></head><body>'+con+'</body></html>');
    v.document.close(); setTimeout(function() { v.print(); v.close(); }, 700);
};

window.abrirNuevoAsiento = function() { document.getElementById('formManual').reset(); window.calcIVA(); $('#modalNuevo').modal('show'); };
window.abrirImportar = function() { window.cargarPendientes(); $('#modalImportar').modal('show'); };
document.addEventListener('DOMContentLoaded', function() { window.cargarLibro(); });
</script>