<?php
/**
 * APP: Historial de Inteligencia Fiscal ELITE v4.0 - FINAL
 * Layout: Split View + Reporte Mensual Consolidado (3/4)
 * Fecha Actual: <?php echo date('d/m/Y'); ?>
 */
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 . "-"; 

$hoy = date('Y-m-d');
$mesHoy = date('Y-m');
$mesLetra = date('F Y');
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href='https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.css' rel='stylesheet' />
<script src='https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.js'></script>
<script src='https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/locales/es.js'></script>
<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; }

    .card-kpi { border: none; border-radius: 12px; background: #fff; box-shadow: 0 4px 10px rgba(0,0,0,0.05); border-top: 4px solid var(--azul); }
    
    /* LAYOUT SPLIT */
    .main-split { display: flex; gap: 20px; height: calc(100vh - 280px); margin-top: 10px; }
    .col-calendar { flex: 1; max-width: 33.33%; }
    .col-table { flex: 2; background: #fff; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); display: flex; flex-direction: column; overflow: hidden; border: 1px solid #eee; }

    /* CALENDARIO */
    #calendar { background: #fff; padding: 10px; border-radius: 15px; border: 1px solid #eee; font-size: 12px; height: 100%; }
    
    /* DRAWERS */
    .modal.drawer-right .modal-dialog { position: fixed; margin: auto; height: 100%; right: -100%; top: 0; transition: right 0.4s; }
    .modal.drawer-right.show .modal-dialog { right: 0; }
    .modal.drawer-right .modal-content { height: 100%; border-radius: 0; border: none; overflow-y: auto; }
    
    .drawer-1-4 { width: 420px !important; max-width: 420px !important; }
    .drawer-3-4 { width: 75% !important; max-width: 75% !important; }

    .table-sticky-header { position: sticky; top: 0; background: #fff; z-index: 5; border-bottom: 2px solid #f4f7f6; padding: 15px 20px; }
    .scroll-area { flex: 1; overflow-y: auto; padding: 0 20px 20px 20px; }
    
    .bg-grad-ingreso { background: linear-gradient(to left, rgba(40, 167, 69, 0.08), #fff) !important; border-right: 5px solid var(--ingreso) !important; }
    .bg-grad-gasto { background: linear-gradient(to left, rgba(220, 53, 69, 0.08), #fff) !important; border-right: 5px solid var(--gasto) !important; }
</style>

<div class="container-fluid p-3">
    <div class="d-flex gap-3 mb-3">
        <button class="btn btn-primary shadow-sm px-4 mr-2" onclick="window.location.reload()">
            <i class="fas fa-sync-alt mr-1"></i> Actualizar
        </button>
        <button class="btn btn-dark shadow-sm px-4" onclick="window.abrirReporteMensual()">
            <i class="fas fa-file-invoice-dollar mr-1"></i> Generar Reporte Mensual (<?php echo date('M'); ?>)
        </button>
    </div>

    <div class="row mb-3">
        <div class="col-md-3">
            <div class="card card-kpi p-3">
                <small class="text-muted font-weight-bold uppercase">Balance Global</small>
                <h4 class="mb-0 font-weight-bold" id="kpi_global">$ 0.00</h4>
                <small class="text-muted font-italic" style="font-size: 10px;">Acumulado histórico</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card card-kpi p-3" style="border-top-color: var(--ingreso);">
                <small class="text-muted font-weight-bold text-success uppercase">Cobros del Mes</small>
                <h4 class="mb-0 font-weight-bold text-success" id="kpi_cobros_mes">$ 0.00</h4>
                <small class="text-muted font-italic" style="font-size: 10px;"><?php echo $mesLetra; ?></small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card card-kpi p-3" style="border-top-color: var(--gasto);">
                <small class="text-muted font-weight-bold text-danger uppercase">Pagos del Mes</small>
                <h4 class="mb-0 font-weight-bold text-danger" id="kpi_pagos_mes">$ 0.00</h4>
                <small class="text-muted font-italic" style="font-size: 10px;"><?php echo $mesLetra; ?></small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card card-kpi p-3" id="kpi_iva_card">
                <small class="text-muted font-weight-bold uppercase">IVA SAT Neto Mes</small>
                <h4 class="mb-0 font-weight-bold" id="kpi_iva_mes">$ 0.00</h4>
                <small class="text-muted font-italic" style="font-size: 10px;"><?php echo $mesLetra; ?></small>
            </div>
        </div>
    </div>

    <div class="main-split">
        <div class="col-calendar"><div id='calendar'></div></div>
        <div class="col-table">
            <div class="table-sticky-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0 font-weight-bold text-dark">Detalle del Día: <span id="lbl_fecha_sel">--/--/--</span></h5>
                <h4 class="mb-0 font-weight-bold" id="lbl_neto_dia">$ 0.00</h4>
            </div>
            <div class="scroll-area">
                <table class="table table-hover">
                    <thead class="small font-weight-bold text-muted text-uppercase">
                        <tr><th width="60">ID</th><th>Descripción</th><th width="100" class="text-center">Origen</th><th width="120" class="text-right">Monto</th><th width="50">Auditar</th></tr>
                    </thead>
                    <tbody id="tbody_detalle_dia"></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade drawer-right" id="modalReporteMensual" 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"><i class="fas fa-print mr-2"></i>Reporte Contable Mensual - <?php echo $mesLetra; ?></h5>
                <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body p-5" id="areaImpresionMensual">
                <div class="row mb-5 border-bottom pb-4">
                    <div class="col-6">
                        <h2 class="font-weight-bold mb-0">ESTADO DE CUENTA</h2>
                        <p class="text-muted uppercase mb-0">Libro Diario Fiscal Consolidado</p>
                    </div>
                    <div class="col-6 text-right">
                        <h3 class="text-primary font-weight-bold mb-0" id="rep_mes_nombre"><?php echo $mesLetra; ?></h3>
                        <small class="text-muted">Generado el: <?php echo date('d/m/Y H:i'); ?></small>
                    </div>
                </div>

                <div class="row mb-5">
                    <div class="col-4">
                        <div class="p-3 border rounded text-center">
                            <small class="text-muted font-weight-bold d-block">TOTAL INGRESOS</small>
                            <h3 class="text-success font-weight-bold mb-0" id="rep_total_in">$ 0.00</h3>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="p-3 border rounded text-center">
                            <small class="text-muted font-weight-bold d-block">TOTAL EGRESOS</small>
                            <h3 class="text-danger font-weight-bold mb-0" id="rep_total_out">$ 0.00</h3>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="p-3 border rounded text-center">
                            <small class="text-muted font-weight-bold d-block">SALDO NETO MES</small>
                            <h3 class="font-weight-bold mb-0" id="rep_total_neto">$ 0.00</h3>
                        </div>
                    </div>
                </div>

                <table class="table table-bordered table-sm">
                    <thead class="bg-light text-center small font-weight-bold">
                        <tr>
                            <th>Fecha</th>
                            <th>Ref</th>
                            <th>Concepto / Descripción del Movimiento</th>
                            <th>Abono (+)</th>
                            <th>Cargo (-)</th>
                        </tr>
                    </thead>
                    <tbody id="tbody_reporte_mensual" class="small">
                        </tbody>
                </table>
            </div>
            <div class="modal-footer bg-light border-0">
                <button class="btn btn-success px-5 py-3 font-weight-bold" onclick="window.imprimirReporteMensual()">
                    <i class="fas fa-print mr-2"></i>IMPRIMIR REPORTE COMPLETO
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade drawer-right" id="modalOjo" 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">Auditoría Individual</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 uppercase small">Artículos Incluidos</h6>
                <div id="ojo_articulos" class="mb-4"></div>
                <h6 class="font-weight-bold border-bottom pb-1 uppercase mt-4 small">Asiento en Partida Doble</h6>
                <div id="ojo_partida" class="table-responsive"></div>
            </div>
        </div>
    </div>
</div>



<script>
/**
 * --- NÚCLEO HISTORIAL v4.0 FINAL ---
 */
const DB = "<?php echo $DB_D; ?>";
const PRE = "<?php echo $PRE; ?>";
const USU = "<?php echo $IDU; ?>";

window.apiSQL = async (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.initHistorial = async function() {
    const cuentasL = "'Caja','Bancos','Efectivo','Tarjeta','Transferencia'";
    const mesActual = "<?php echo $mesHoy; ?>";

    // 1. KPIs MENSUALES
    const sqlKPI = "SELECT " +
        "(SELECT IFNULL(SUM(Abono),0) - IFNULL(SUM(Cargo),0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` WHERE Cuenta_Nombre IN (" + cuentasL + ")) as Global, " +
        "(SELECT IFNULL(SUM(d.Abono),0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` d JOIN " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` c ON d.ID_Asiento = c.ID_Asiento WHERE d.Cuenta_Nombre IN (" + cuentasL + ") AND DATE_FORMAT(c.Fecha_Contable, '%Y-%m') = '" + mesActual + "' AND d.Abono > 0) as InMes, " +
        "(SELECT IFNULL(SUM(d.Cargo),0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` d JOIN " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` c ON d.ID_Asiento = c.ID_Asiento WHERE d.Cuenta_Nombre IN (" + cuentasL + ") AND DATE_FORMAT(c.Fecha_Contable, '%Y-%m') = '" + mesActual + "' AND d.Cargo > 0) as OutMes, " +
        "(SELECT SUM(CASE WHEN c.Origen_Tipo != 'COMPRA' THEN i.Monto_Impuesto ELSE -i.Monto_Impuesto END) FROM " + DB + ".`" + PRE + "Libro_Impuestos_Detalle` i JOIN " + DB + ".`" + PRE + "Libro_Asientos_Detalle` d ON i.ID_Movimiento = d.ID_Movimiento JOIN " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` c ON d.ID_Asiento = c.ID_Asiento WHERE DATE_FORMAT(c.Fecha_Contable, '%Y-%m') = '" + mesActual + "') as IvaNeto";

    const rK = await window.apiSQL(sqlKPI, DB);
    const k = rK.data[0];

    document.getElementById('kpi_global').innerText = "$ " + parseFloat(k.Global).toLocaleString('en-US',{minimumFractionDigits:2});
    document.getElementById('kpi_cobros_mes').innerText = "$ " + parseFloat(k.InMes).toLocaleString('en-US',{minimumFractionDigits:2});
    document.getElementById('kpi_pagos_mes').innerText = "$ " + parseFloat(k.OutMes).toLocaleString('en-US',{minimumFractionDigits:2});
    
    const ivaN = parseFloat(k.IvaNeto || 0);
    const kIva = document.getElementById('kpi_iva_mes');
    kIva.innerText = "$ " + ivaN.toFixed(2);
    kIva.className = "mb-0 font-weight-bold " + (ivaN >= 0 ? "text-danger" : "text-success");
    document.getElementById('kpi_iva_card').style.borderTopColor = ivaN >= 0 ? "#dc3545" : "#28a745";

    // 2. CALENDARIO
    var calendar = new FullCalendar.Calendar(document.getElementById('calendar'), {
        locale: 'es',
        initialView: 'dayGridMonth',
        headerToolbar: { left: 'prev,next', center: 'title', right: 'today' },
        height: '100%',
        dateClick: function(info) { window.cargarVistaDia(info.dateStr); }
    });
    calendar.render();
    window.cargarVistaDia("<?php echo $hoy; ?>");
};

window.cargarVistaDia = async function(fecha) {
    const parts = fecha.split('-');
    document.getElementById('lbl_fecha_sel').innerText = parts[2] + "/" + parts[1] + "/" + parts[0];
    
    const sqlDia = "SELECT c.*, (SELECT IFNULL(SUM(Abono),0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` WHERE ID_Asiento = c.ID_Asiento AND Cuenta_Nombre IN ('Caja','Bancos','Efectivo','Tarjeta','Transferencia') AND Abono > 0) as DineroIn FROM " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` c WHERE DATE(c.Fecha_Contable) = '" + fecha + "' ORDER BY c.ID_Asiento DESC";

    const rD = await window.apiSQL(sqlDia, DB);
    const movs = rD.data || [];
    const tbody = document.getElementById('tbody_detalle_dia');
    tbody.innerHTML = '';
    let inD = 0; let outD = 0;

    movs.forEach(function(m) {
        const isIn = parseFloat(m.DineroIn) > 0;
        const total = parseFloat(m.Total_Asiento);
        if(isIn) inD += total; else outD += total;

        tbody.innerHTML += '<tr class="' + (isIn ? 'bg-grad-ingreso' : 'bg-grad-gasto') + '">' +
            '<td class="text-center font-weight-bold">#' + m.ID_Asiento + '</td>' +
            '<td>' + m.Concepto_General + '</td>' +
            '<td class="text-center small"><small class="badge badge-light border">' + m.Origen_Tipo + '</small></td>' +
            '<td class="text-right font-weight-bold ' + (isIn ? 'text-success' : 'text-danger') + '">$ ' + total.toFixed(2) + '</td>' +
            '<td class="text-center"><button class="btn btn-sm btn-light border" onclick="window.ojoAsiento(' + m.ID_Asiento + ',\'' + m.Origen_Tipo + '\',' + m.Origen_ID + ')"><i class="fas fa-eye"></i></button></td>' +
        '</tr>';
    });

    const neto = inD - outD;
    document.getElementById('lbl_neto_dia').innerText = "$ " + neto.toLocaleString('en-US',{minimumFractionDigits:2});
    document.getElementById('lbl_neto_dia').className = "mb-0 font-weight-bold " + (neto >= 0 ? "text-success" : "text-danger");
};

window.abrirReporteMensual = async function() {
    const mesActual = "<?php echo $mesHoy; ?>";
    const sqlRep = "SELECT c.Fecha_Contable, c.ID_Asiento, c.Concepto_General, c.Total_Asiento, " +
        "(SELECT IFNULL(SUM(Abono),0) FROM " + DB + ".`" + PRE + "Libro_Asientos_Detalle` WHERE ID_Asiento = c.ID_Asiento AND Cuenta_Nombre IN ('Caja','Bancos','Efectivo','Tarjeta','Transferencia') AND Abono > 0) as Abono " +
        "FROM " + DB + ".`" + PRE + "Libro_Asientos_Cabecera` c WHERE DATE_FORMAT(c.Fecha_Contable, '%Y-%m') = '" + mesActual + "' ORDER BY c.Fecha_Contable ASC";

    const res = await window.apiSQL(sqlRep, DB);
    const data = res.data || [];
    const tbody = document.getElementById('tbody_reporte_mensual');
    tbody.innerHTML = '';
    let totalIn = 0; let totalOut = 0;

    data.forEach(function(r) {
        const isIn = parseFloat(r.Abono) > 0;
        const total = parseFloat(r.Total_Asiento);
        if(isIn) totalIn += total; else totalOut += total;

        tbody.innerHTML += '<tr>' +
            '<td class="text-center">' + r.Fecha_Contable.split(' ')[0] + '</td>' +
            '<td class="text-center">#' + r.ID_Asiento + '</td>' +
            '<td>' + r.Concepto_General + '</td>' +
            '<td class="text-right text-success">' + (isIn ? '$' + total.toFixed(2) : '') + '</td>' +
            '<td class="text-right text-danger">' + (!isIn ? '$' + total.toFixed(2) : '') + '</td>' +
        '</tr>';
    });

    document.getElementById('rep_total_in').innerText = "$ " + totalIn.toLocaleString('en-US',{minimumFractionDigits:2});
    document.getElementById('rep_total_out').innerText = "$ " + totalOut.toLocaleString('en-US',{minimumFractionDigits:2});
    const neto = totalIn - totalOut;
    document.getElementById('rep_total_neto').innerText = "$ " + neto.toLocaleString('en-US',{minimumFractionDigits:2});
    document.getElementById('rep_total_neto').className = "font-weight-bold mb-0 " + (neto >= 0 ? 'text-success' : 'text-danger');

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

window.imprimirReporteMensual = function() {
    const con = document.getElementById('areaImpresionMensual').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-bordered td, .table-bordered th { border: 1px solid #333!important; }</style></head><body>' + con + '</body></html>');
    v.document.close(); setTimeout(function() { v.print(); v.close(); }, 700);
};

window.ojoAsiento = 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('ojo_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('ojo_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-right text-success">' + (i.Abono>0?'$'+i.Abono:'') + '</td><td class="text-right text-danger">' + (i.Cargo>0?'$'+i.Cargo:'') + '</td></tr>'; });
    document.getElementById('ojo_partida').innerHTML = h + '</tbody></table>';
    $('#modalOjo').modal('show');
};

document.addEventListener('DOMContentLoaded', function() { window.initHistorial(); });
</script>