<?php
/**
 * CONSOLA DE INTELIGENCIA ESTRATÉGICA - FULL WIDTH
 * Versión Final: Distribución Financiera Balanceada y Ficha Técnica Integral.
 */
header('Content-Type: text/html; charset=utf-8');
session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso Denegado."); }

$idProp = $_SESSION['IDUg'] ?? '1'; 
$dbName = $_SESSION['BD'] ?? "MS_Datos"; 
$px = "$idProp-"; 

// Automatización de Porcentajes
function getProgreso($est) {
    $m = [
        'Pendiente' => 10, 'Pedido' => 20, 'En Proceso' => 40, 'En Aduana' => 60,
        'En Ruta' => 75, 'Recibido' => 85, 'Listo' => 95, 'Entregado' => 100, 'Cancelado' => 0
    ];
    return $m[$est] ?? 0;
}

try {
    $pdo = new PDO("mysql:host=localhost;dbname=$dbName;charset=utf8", "root", "33comRxXMysql");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "SELECT v.*, c.Nombre as Cliente, c.Telefono, c.Direccion,
            (SELECT Estado FROM `{$px}Pedidos_Seguimiento` WHERE Folio = v.Folio ORDER BY Fecha_Actualizacion DESC LIMIT 1) as EstadoActual
            FROM `{$px}Pedidos_Ventas` v
            INNER JOIN `{$px}Clientes` c ON v.IDC = c.IDC
            ORDER BY v.Fecha_Registro DESC";
    $pedidos = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

    // Cálculos de KPIs
    $op = ['activos' => 0, 'taller' => 0, 'aduana' => 0, 'listos' => 0];
    $fin = ['venta' => 0, 'caja' => 0, 'resta' => 0];

    foreach($pedidos as $p) {
        $est = $p['EstadoActual'] ?? 'Pendiente';
        if($est !== 'Cancelado') {
            $fin['venta'] += $p['Total_Venta']; $fin['caja'] += $p['Anticipo'];
            if($est !== 'Entregado') $fin['resta'] += ($p['Total_Venta'] - $p['Anticipo']);
        }
        if(!in_array($est, ['Entregado', 'Cancelado'])) {
            $op['activos']++;
            if(in_array($est, ['Pendiente', 'Pedido', 'En Proceso'])) $op['taller']++;
            if($est == 'En Aduana') $op['aduana']++;
            if($est == 'Listo') $op['listos']++;
        }
    }
} catch (PDOException $e) { die("Error: " . $e->getMessage()); }
?>

<style>
    :root { --aduana: #6f42c1; --ruta: #f6ad55; --success: #1cc88a; --primary: #4e73df; --dark-ui: #1a202c; }
    
    /* Layout Pantalla Completa */
    .report-bi { 
        background: #f0f3f7; min-height: 100vh; padding: 20px; 
        width: 100%; max-width: 100% !important; margin: 0;
        font-family: 'Inter', sans-serif; 
    }
    
    /* Widgets Operativos */
    .card-kpi { background: #fff; border: none; border-radius: 15px; padding: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); height: 100%; border-bottom: 4px solid #eee; }
    .kpi-val { font-size: 28px; font-weight: 900; color: #2d3436; display: block; }
    .kpi-label { font-size: 11px; font-weight: 800; color: #adb5bd; text-transform: uppercase; letter-spacing: 1.2px; }

    /* REDISTRIBUCIÓN RESUMEN DE CAJA */
    #panel-finanzas { display: none; margin-bottom: 30px; width: 100%; }
    .fin-box { 
        background: var(--dark-ui); border-radius: 20px; padding: 30px; 
        box-shadow: 0 15px 35px rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.05);
    }
    .fin-item { text-align: center; border-right: 1px solid rgba(255,255,255,0.1); }
    .fin-item:last-child { border-right: none; }
    .fin-val { font-size: 32px; font-weight: 800; display: block; letter-spacing: -1px; }
    .fin-label { font-size: 10px; font-weight: 700; color: #718096; text-transform: uppercase; letter-spacing: 2px; }

    /* Tabla Full-Width */
    .panel-bi { background: #fff; border-radius: 20px; padding: 30px; box-shadow: 0 4px 20px rgba(0,0,0,0.04); width: 100%; }
    .table-bi thead th { background: #f8f9fc; color: var(--primary); border: none; font-size: 12px; text-transform: uppercase; padding: 20px; }
    
    /* Barra de Progreso */
    .track-bar { height: 12px; background: #eaecf4; border-radius: 10px; display: flex; overflow: hidden; margin-top: 5px; border: 1px solid #e3e6f0; }
    .t-seg { flex: 1; border-right: 1px solid #fff; }
    .t-on { background: var(--primary); }
    .t-aduana { background: var(--aduana); }
    .t-ruta { background: var(--ruta); }
    .t-ready { background: var(--success); }

    /* Drawer de Detalle */
    .drawer-right { position: fixed; top: 0; right: -60%; width: 55%; height: 100%; background: #fff; z-index: 1050; transition: 0.6s cubic-bezier(0.16, 1, 0.3, 1); box-shadow: -20px 0 50px rgba(0,0,0,0.2); padding: 40px; overflow-y: auto; }
    .drawer-show { right: 0; }
    .drawer-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 1040; display: none; backdrop-filter: blur(8px); }
</style>



<div class="report-bi">
    <div class="d-flex justify-content-between align-items-center mb-4 px-2">
        <div>
            <h2 class="font-weight-bold text-dark m-0">Inteligencia Logística Aplicada</h2>
            <p class="text-muted m-0 small">Monitor operativo y balance de flujo de efectivo en tiempo real</p>
        </div>
        <button class="btn btn-dark rounded-pill px-5 shadow-lg font-weight-bold" onclick="bi.toggleFin()">
            <i class="feather icon-briefcase mr-2"></i> RESUMEN DE CAJA
        </button>
    </div>

    <div class="row no-gutters mb-4">
        <div class="col-md-3 px-2"><div class="card-kpi"><span class="kpi-label">Activos</span><span class="kpi-val"><?php echo $op['activos']; ?></span></div></div>
        <div class="col-md-3 px-2"><div class="card-kpi"><span class="kpi-label text-primary">Taller</span><span class="kpi-val text-primary"><?php echo $op['taller']; ?></span></div></div>
        <div class="col-md-3 px-2"><div class="card-kpi"><span class="kpi-label" style="color:var(--aduana)">Aduana</span><span class="kpi-val" style="color:var(--aduana)"><?php echo $op['aduana']; ?></span></div></div>
        <div class="col-md-3 px-2"><div class="card-kpi"><span class="kpi-label text-success">Listos</span><span class="kpi-val text-success"><?php echo $op['listos']; ?></span></div></div>
    </div>

    <div id="panel-finanzas">
        <div class="fin-box">
            <div class="row align-items-center">
                <div class="col-md-4 fin-item">
                    <span class="fin-label">Venta Total Bruta</span>
                    <span class="fin-val text-white">$<?php echo number_format($fin['venta'], 2); ?></span>
                </div>
                <div class="col-md-4 fin-item">
                    <span class="fin-label">Capital Recaudado</span>
                    <span class="fin-val text-success">$<?php echo number_format($fin['caja'], 2); ?></span>
                </div>
                <div class="col-md-4 fin-item">
                    <span class="fin-label">Cartera por Cobrar</span>
                    <span class="fin-val text-danger">$<?php echo number_format($fin['resta'], 2); ?></span>
                </div>
            </div>
        </div>
    </div>

    <div class="panel-bi">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h5 class="font-weight-bold m-0 text-dark"><i class="feather icon-navigation mr-2 text-primary"></i>Monitor de Tránsito Logístico</h5>
            <div class="w-25">
                <input type="text" id="masterSearch" class="form-control form-control-sm border-0 bg-light shadow-sm" placeholder="Buscar folio, cliente...">
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-hover table-bi" id="mainTable">
                <thead>
                    <tr>
                        <th width="150">Folio</th>
                        <th>Cliente</th>
                        <th width="380">Estatus Logístico</th>
                        <th class="text-right" width="180">Pendiente</th>
                        <th class="text-center" width="80">Ver</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($pedidos as $p): 
                        $est = $p['EstadoActual'] ?? 'Pendiente';
                        if(in_array($est, ['Entregado', 'Cancelado'])) continue; 
                        $prog = getProgreso($est);
                        $s = ($est=='Pedido'?2:($est=='En Proceso'?3:($est=='En Aduana'?4:($est=='En Ruta'?5:($est=='Recibido'?6:($est=='Listo'?7:1))))));
                    ?>
                    <tr>
                        <td class="font-weight-bold text-primary"><?php echo $p['Folio']; ?></td>
                        <td><b><?php echo $p['Cliente']; ?></b><br><small class="text-muted"><?php echo $p['Telefono']; ?></small></td>
                        <td>
                            <div class="track-bar">
                                <div class="t-seg <?php echo $s >= 1 ? 't-on' : ''; ?>"></div><div class="t-seg <?php echo $s >= 2 ? 't-on' : ''; ?>"></div><div class="t-seg <?php echo $s >= 3 ? 't-on' : ''; ?>"></div>
                                <div class="t-seg <?php echo $s >= 4 ? 't-aduana' : ''; ?>"></div><div class="t-seg <?php echo $s >= 5 ? 't-ruta' : ''; ?>"></div><div class="t-seg <?php echo $s >= 6 ? 't-ruta' : ''; ?>"></div><div class="t-seg <?php echo $s >= 7 ? 't-ready' : ''; ?>"></div>
                            </div>
                            <small class="font-weight-bold text-uppercase"><?php echo $est; ?> (<?php echo $prog; ?>%)</small>
                        </td>
                        <td class="text-right font-weight-bold text-danger">
                            $<?php echo number_format($p['Total_Venta'] - $p['Anticipo'], 2); ?>
                        </td>
                        <td class="text-center">
                            <button class="btn btn-sm btn-dark rounded-circle shadow-sm" onclick="bi.open('<?php echo $p['Folio']; ?>')">
                                <i class="feather icon-eye"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="drawer-overlay" id="drOverlay" onclick="bi.close()"></div>
<div class="drawer-right" id="drDetails">
    <div class="d-flex justify-content-between align-items-center mb-5 border-bottom pb-3">
        <div>
            <h3 class="font-weight-bold m-0 text-dark" id="drFolio">FOLIO</h3>
            <span class="badge badge-primary px-3 py-2" id="drBadgeEst">Estatus</span>
        </div>
        <button class="btn btn-link text-dark" onclick="bi.close()" style="font-size:2.5rem; line-height:1;">&times;</button>
    </div>

    <div class="row text-center mb-5 bg-light py-4 rounded-xl border">
        <div class="col-4 border-right">
            <small class="text-muted d-block font-weight-bold uppercase mb-1">VENTA</small>
            <b id="drTotal" class="h4 m-0">$0</b>
        </div>
        <div class="col-4 border-right">
            <small class="text-success d-block font-weight-bold uppercase mb-1">PAGADO</small>
            <b id="drPagado" class="h4 m-0 text-success">$0</b>
        </div>
        <div class="col-4">
            <small class="text-danger d-block font-weight-bold uppercase mb-1">RESTA</small>
            <b id="drResta" class="h4 m-0 text-danger">$0</b>
        </div>
    </div>

    <div class="mb-5">
        <small class="text-primary font-weight-bold uppercase d-block mb-3">Información del Cliente</small>
        <div class="p-4 rounded-xl border-0 shadow-sm bg-white" style="background: #f8f9fc">
            <h5 id="drCli" class="font-weight-bold mb-1">---</h5>
            <p id="drTel" class="text-primary m-0">---</p>
            <p id="drDir" class="text-muted small m-0 mt-2">---</p>
        </div>
    </div>

    <div class="mb-5">
        <small class="text-primary font-weight-bold uppercase d-block mb-3">Artículos del Pedido</small>
        <div id="drItems" class="p-3 bg-white rounded-xl border"></div>
    </div>

    <div class="card border-primary mb-5 shadow-sm" style="background:#f0f3ff; border-radius: 20px;">
        <div class="card-body p-4">
            <h6 class="font-weight-bold text-primary mb-4"><i class="feather icon-refresh-cw mr-2"></i>Registrar Avance Operativo</h6>
            <div class="form-row">
                <div class="col-6 mb-3">
                    <label class="small font-weight-bold">Estado Logístico</label>
                    <select id="updEstado" class="form-control font-weight-bold border-0 shadow-sm" onchange="bi.autoProg()">
                        <option>Pendiente</option><option>Pedido</option><option>En Proceso</option><option>En Aduana</option>
                        <option>En Ruta</option><option>Recibido</option><option>Listo</option><option>Entregado</option><option>Cancelado</option>
                    </select>
                </div>
                <div class="col-6 mb-3">
                    <label class="small font-weight-bold">Progreso (Automático %)</label>
                    <input type="number" id="updProg" class="form-control bg-white shadow-sm border-0" readonly>
                </div>
                <div class="col-12 mb-4">
                    <label class="small font-weight-bold">Reporte Público</label>
                    <textarea id="updNota" class="form-control border-0 shadow-sm" rows="3" placeholder="Nota del estatus para el cliente..."></textarea>
                </div>
                <button class="btn btn-primary btn-block btn-lg font-weight-bold shadow" onclick="bi.save()">GUARDAR ACTUALIZACIÓN</button>
            </div>
        </div>
    </div>

    <h6 class="font-weight-bold mb-4 text-dark"><i class="feather icon-clock mr-2"></i>Historial Logístico</h6>
    <div id="drTimeline" class="ml-2 border-left pl-4" style="border-width:2.5px !important; border-color: #e3e6f0 !important;"></div>
</div>

<script>
const bi = (function() {
    const peds = <?php echo json_encode($pedidos); ?>;
    const CFG = { px: '<?php echo $px; ?>', db: '<?php echo $dbName; ?>' };
    const pMap = {'Pendiente':10,'Pedido':20,'En Proceso':40,'En Aduana':60,'En Ruta':75,'Recibido':85,'Listo':95,'Entregado':100,'Cancelado':0};
    let curFolio = '';

    return {
        toggleFin: () => { $('#panel-finanzas').slideToggle(500); },
        autoProg: () => { $('#updProg').val(pMap[$('#updEstado').val()] || 0); },
        open: function(fol) {
            curFolio = fol;
            const p = peds.find(x => x.Folio === fol);
            const m = n => new Intl.NumberFormat('es-MX',{style:'currency',currency:'MXN'}).format(n);
            
            $('#drFolio').text(p.Folio);
            $('#drBadgeEst').text(p.EstadoActual || 'Pendiente');
            $('#drTotal').text(m(p.Total_Venta));
            $('#drPagado').text(m(p.Anticipo));
            $('#drResta').text(m(p.Total_Venta - p.Anticipo));
            $('#drCli').text(p.Cliente);
            $('#drTel').text("📞 " + p.Telefono);
            $('#drDir').text("📍 " + (p.Direccion || 'S/D'));
            $('#updEstado').val(p.EstadoActual || 'Pendiente');
            this.autoProg();

            const items = JSON.parse(p.Productos_JSON || "[]");
            $('#drItems').html(items.map(it => `<div class="d-flex justify-content-between py-2 border-bottom small"><span>${it.producto} (x${it.cant})</span><b>${m(it.total)}</b></div>`).join(''));

            this.loadLog();
            $('#drOverlay').fadeIn(); $('#drDetails').addClass('drawer-show');
        },
        loadLog: async function() {
            const fd = new FormData(); fd.append('db',CFG.db);
            fd.append('sql', `SELECT * FROM \`${CFG.px}Pedidos_Seguimiento\` WHERE Folio='${curFolio}' ORDER BY Fecha_Actualizacion DESC`);
            const r = await fetch(`../librerias/AJAX/Select.php`,{method:'POST', body:fd}).then(res=>res.json());
            $('#drTimeline').html(r.data.map(l => `<div class="mb-4 position-relative"><small class="text-muted d-block">${l.Fecha_Actualizacion}</small><b>${l.Estado} (${l.Progreso}%)</b><p class="small m-0 text-muted mt-1">${l.Reporte_Publico}</p></div>`).join('') || '<p class="small text-muted">Sin movimientos.</p>');
        },
        save: async function() {
            const est = $('#updEstado').val(), pro = $('#updProg').val(), n = $('#updNota').val();
            if(!n) return alert("Por favor, ingrese una nota de seguimiento.");
            const sql = `INSERT INTO \`${CFG.px}Pedidos_Seguimiento\` (Folio, Estado, Progreso, Reporte_Publico) VALUES ('${curFolio}', '${est}', ${pro}, '${n.replace(/'/g,"")}')`;
            const fd = new FormData(); fd.append('db',CFG.db); fd.append('sql',sql);
            const r = await fetch(`../librerias/AJAX/Execute.php`,{method:'POST', body:fd}).then(res=>res.json());
            if(r.status==='success') { $('#updNota').val(''); this.loadLog(); if(est==='Entregado') location.reload(); }
        },
        close: () => { $('#drOverlay').fadeOut(); $('#drDetails').removeClass('drawer-show'); }
    };
})();

$('#masterSearch').on('keyup', function() {
    let v = $(this).val().toLowerCase();
    $('#mainTable tbody tr').filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(v) > -1) });
});
</script>