<?php
// 1. CODIFICACIÓN Y SEGURIDAD
header('Content-Type: text/html; charset=utf-8');
session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso denegado."); }

// Asignación de Prefijo Multiusuario
$idUsuario = $_SESSION['IDUg'] ?? '1'; 
$dbName = $_SESSION['BD'] ?? "MS_Datos"; 
$prefijoTablas = $idUsuario . "-"; 

try {
    // Conexión con charset explícito para evitar problemas de acentos
    $pdo = new PDO("mysql:host=localhost;dbname=$dbName;charset=utf8", "root", "33comRxXMysql");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $fechaLimite = date('Y-m-d', strtotime('-1 year'));
    
    // Consulta Maestra con Prefijos Dinámicos
    $sql = "SELECT os.*, c.Nombre as Cliente, c.Telefono, its.Marca, its.Modelo, its.Categoria, its.Serie_Placas
            FROM `{$prefijoTablas}Ordenes_Servicio` os
            INNER JOIN `{$prefijoTablas}Clientes` c ON os.IDC = c.IDC
            INNER JOIN `{$prefijoTablas}Items_Servicio` its ON os.ID_Orden = its.ID_Orden
            WHERE os.Fecha_Ingreso >= '$fechaLimite'
            ORDER BY os.Fecha_Ingreso DESC";
    $servicios = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

    // CÁLCULO DE KPIs
    $kpi = [
        'total' => 0, 'taller' => 0, 'listos' => 0, 'entregados' => 0,
        'monto_total' => 0, 'monto_caja' => 0, 'monto_taller' => 0, 'olvidados' => 0
    ];

    foreach($servicios as $s) {
        $kpi['total']++;
        $val = floatval($s['Total_Estimado']);
        $ant = floatval($s['Anticipo']);
        $kpi['monto_total'] += $val;
        $kpi['monto_caja'] += $ant;
        
        $dias = (strtotime(date('Y-m-d')) - strtotime($s['Fecha_Ingreso'])) / 86400;

        if($s['Estado'] == 'Entregado') {
            $kpi['entregados']++;
        } else {
            $kpi['monto_taller'] += ($val - $ant);
            if($s['Estado'] == 'Listo') $kpi['listos']++;
            else {
                $kpi['taller']++;
                if($dias > 15) $kpi['olvidados']++; 
            }
        }
    }

} catch (PDOException $e) { die("Error de Base de Datos: " . $e->getMessage()); }
?>

<style>
    .report-wrapper { width: 100%; background: #f0f2f5; min-height: 100vh; padding: 25px; font-family: 'Inter', sans-serif; }
    .kpi-card { border: none; border-radius: 15px; padding: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); background: #fff; transition: 0.3s; }
    .kpi-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
    .kpi-title { font-size: 0.75rem; font-weight: 800; color: #888; text-transform: uppercase; letter-spacing: 1px; }
    .kpi-value { font-size: 1.8rem; font-weight: 800; color: #2c3e50; display: block; }
    .alert-stagnant { background: #fff5f5; border-left: 5px solid #dc3545; border-radius: 10px; padding: 15px; margin-bottom: 25px; display: flex; align-items: center; justify-content: space-between; }
    .track-bar { height: 8px; background: #e9ecef; border-radius: 10px; display: flex; overflow: hidden; margin-top: 5px; }
    .track-seg { flex: 1; border-right: 1px solid #fff; }
    .seg-on { background: #f26522; }
    .seg-ready { background: #28a745; }
    .seg-done { background: #2c3e50; }
    .card-table { background: #fff; border-radius: 15px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
    .table thead th { background: #f8f9fa; border: none; font-size: 0.7rem; text-transform: uppercase; padding: 15px; }
    .drawer-right { position: fixed; top: 0; right: -50%; width: 50%; height: 100%; background: #fff; z-index: 9999; transition: 0.4s; box-shadow: -10px 0 30px rgba(0,0,0,0.2); padding: 30px; 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.5); z-index: 9998; display:none; }
    @media print { .no-print { display: none !important; } .report-wrapper { padding: 0; background: #fff; } }
</style>

<div class="report-wrapper">
    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <div>
            <h2 class="font-weight-bold text-dark m-0">Consola de Inteligencia</h2>
            <p class="text-muted">Balance de productividad - Usuario: <?php echo $idUsuario; ?></p>
        </div>
        <button class="btn btn-dark btn-lg shadow-sm" onclick="osReport.print()">
            <i class="feather icon-printer mr-2"></i>IMPRIMIR REPORTE MÁSTER
        </button>
    </div>

    <div class="row mb-4">
        <div class="col-md-3">
            <div class="kpi-card">
                <span class="kpi-title">Órdenes Totales</span>
                <span class="kpi-value"><?php echo $kpi['total']; ?></span>
                <small class="text-muted">Anual</small>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card">
                <span class="kpi-title text-warning">En Reparación</span>
                <span class="kpi-value text-warning"><?php echo $kpi['taller']; ?></span>
                <div class="progress mt-2" style="height:4px;"><div class="progress-bar bg-warning" style="width: 50%"></div></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card">
                <span class="kpi-title text-success">Listos</span>
                <span class="kpi-value text-success"><?php echo $kpi['listos']; ?></span>
                <div class="progress mt-2" style="height:4px;"><div class="progress-bar bg-success" style="width: 100%"></div></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card">
                <span class="kpi-title text-dark">Entregados</span>
                <span class="kpi-value"><?php echo $kpi['entregados']; ?></span>
                <small class="text-muted">Recaudado: $<?php echo number_format($kpi['monto_caja'], 2); ?></small>
            </div>
        </div>
    </div>

    <?php if($kpi['olvidados'] > 0): ?>
    <div class="alert-stagnant shadow-sm no-print">
        <div>
            <h5 class="m-0 font-weight-bold text-danger"><i class="feather icon-alert-circle mr-2"></i>Equipos Estancados</h5>
            <p class="m-0 small">Hay <b><?php echo $kpi['olvidados']; ?></b> equipos con más de 15 días de inactividad.</p>
        </div>
        <button class="btn btn-danger btn-sm shadow" onclick="osReport.filterStagnant()">REVISAR RIESGOS</button>
    </div>
    <?php endif; ?>

    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card border-0 shadow-sm" style="background: #2c3e50; border-radius: 15px;">
                <div class="card-body p-4 d-flex justify-content-around text-center">
                    <div><small class="text-muted uppercase d-block">Valor Bruto</small><h3 class="text-white font-weight-bold">$<?php echo number_format($kpi['monto_total'], 2); ?></h3></div>
                    <div style="width: 2px; background: rgba(255,255,255,0.1);"></div>
                    <div><small class="text-success uppercase d-block">Cobrado (Caja)</small><h3 class="text-success font-weight-bold">$<?php echo number_format($kpi['monto_caja'], 2); ?></h3></div>
                    <div style="width: 2px; background: rgba(255,255,255,0.1);"></div>
                    <div><small class="text-warning uppercase d-block">Por Cobrar</small><h3 class="text-warning font-weight-bold">$<?php echo number_format($kpi['monto_taller'], 2); ?></h3></div>
                </div>
            </div>
        </div>
    </div>

    <div class="card-table shadow-sm">
        <div class="p-3 bg-white d-flex justify-content-between no-print border-bottom">
            <h6 class="m-0 font-weight-bold">Desglose de Servicios</h6>
            <input type="text" id="masterSearch" class="form-control form-control-sm w-25" placeholder="Buscar cliente, equipo o folio...">
        </div>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0" id="mainTable">
                <thead>
                    <tr>
                        <th>Folio</th>
                        <th>Cliente</th>
                        <th>Equipo</th>
                        <th width="180">Estado</th>
                        <th class="text-right">Balance</th>
                        <th class="text-center no-print">Ver</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($servicios as $s): 
                        $costo = floatval($s['Total_Estimado']); $pago = floatval($s['Anticipo']); $resta = $costo - $pago;
                        $step = 1; 
                        if($s['Estado'] == 'Diagnostico') $step = 2;
                        if($s['Estado'] == 'En Reparacion') $step = 3;
                        if($s['Estado'] == 'Listo') $step = 4;
                        if($s['Estado'] == 'Entregado') $step = 5;
                        $dias = (strtotime(date('Y-m-d')) - strtotime($s['Fecha_Ingreso'])) / 86400;
                    ?>
                    <tr class="<?php echo ($dias > 15 && $s['Estado'] != 'Entregado') ? 'table-warning' : ''; ?>">
                        <td><b class="text-dark"><?php echo $s['Folio']; ?></b><br><small class="text-muted"><?php echo date('d/m/y', strtotime($s['Fecha_Ingreso'])); ?></small></td>
                        <td><b><?php echo $s['Cliente']; ?></b></td>
                        <td><b><?php echo $s['Marca'] . " " . $s['Modelo']; ?></b></td>
                        <td>
                            <div class="track-bar">
                                <div class="track-seg <?php echo $step >= 1 ? 'seg-on' : ''; ?>"></div>
                                <div class="track-seg <?php echo $step >= 2 ? 'seg-on' : ''; ?>"></div>
                                <div class="track-seg <?php echo $step >= 3 ? 'seg-on' : ''; ?>"></div>
                                <div class="track-seg <?php echo $step >= 4 ? 'seg-ready' : ''; ?>"></div>
                                <div class="track-seg <?php echo $step >= 5 ? 'seg-done' : ''; ?>"></div>
                            </div>
                            <small class="font-weight-bold text-uppercase" style="font-size:10px"><?php echo $s['Estado']; ?></small>
                        </td>
                        <td class="text-right">
                            <span class="d-block small text-muted">Total: $<?php echo number_format($costo, 2); ?></span>
                            <b class="text-danger">$<?php echo number_format($resta, 2); ?></b>
                        </td>
                        <td class="text-center no-print">
                            <button class="btn btn-sm btn-outline-dark border-0" onclick="osReport.openDrawer(<?php echo $s['ID_Orden']; ?>)"><i class="feather icon-maximize-2"></i></button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="drawer-overlay" id="drawerOverlay" onclick="osReport.closeDrawer()"></div>
<div class="drawer-right" id="drawerDetails">
    <div class="d-flex justify-content-between align-items-center mb-4 border-bottom pb-3">
        <h4 class="m-0 font-weight-bold" id="drFolio">---</h4>
        <button class="btn btn-close" onclick="osReport.closeDrawer()">&times;</button>
    </div>
    <div id="drContent"></div>
</div>

<?php include_once('../librerias/Modulos/ImpresoraOS.php'); ?>

<script>
const osReport = (function() {
    const data = <?php echo json_encode($servicios); ?>;
    const CFG = { px: '<?php echo $prefijoTablas; ?>', db: '<?php echo $dbName; ?>' };

    return {
        openDrawer: async function(id) {
            const item = data.find(x => x.ID_Orden == id);
            document.getElementById('drFolio').innerText = "Detalles: " + item.Folio;
            
            const fd = new FormData(); 
            // CORRECCIÓN: Uso de prefijo dinámico en el Historial
            fd.append('sql', `SELECT * FROM \`${CFG.px}Ordenes_Historial\` WHERE ID_Orden = ${id} ORDER BY Fecha_Cambio DESC`);
            fd.append('db', CFG.db);
            
            const r = await fetch(`../librerias/AJAX/Select.php`, {method:'POST', body:fd}).then(res => res.json());
            
            let timeline = '<h6 class="font-weight-bold mb-3 mt-4">Línea de Tiempo</h6>';
            if(r.data && r.data.length) {
                r.data.forEach(h => {
                    timeline += `<div class="border-left pl-3 mb-3 ml-2">
                        <small class="text-muted">${h.Fecha_Cambio}</small><br>
                        <b class="text-primary">${h.Estado_Nuevo}</b>
                        <p class="small text-muted mb-0">${h.Comentario || 'Sin observaciones.'}</p>
                    </div>`;
                });
            } else { timeline += '<p class="text-muted">No hay movimientos registrados.</p>'; }

            document.getElementById('drContent').innerHTML = `
                <div class="alert alert-secondary border-0">
                    <b>Cliente:</b> ${item.Cliente}<br>
                    <b>Equipo:</b> ${item.Marca} ${item.Modelo} (${item.Categoria})<br>
                    <b>Falla:</b> ${item.Notas_Cliente || 'No especificada'}
                </div>
                ${timeline}
            `;

            document.getElementById('drawerOverlay').style.display = 'block';
            document.getElementById('drawerDetails').classList.add('drawer-show');
        },

        closeDrawer: function() {
            document.getElementById('drawerOverlay').style.display = 'none';
            document.getElementById('drawerDetails').classList.remove('drawer-show');
        },

        filterStagnant: function() {
            document.getElementById('masterSearch').value = "table-warning";
            document.getElementById('masterSearch').dispatchEvent(new Event('keyup'));
        },

        print: function() {
            // Estructura para el motor de impresión conservando los elementos
            const dataDoc = { 
                isReport: true, 
                listado: data, 
                titulo: "REPORTE DE CONSOLA DE INTELIGENCIA",
                kpi: <?php echo json_encode($kpi); ?>,
                usuario: '<?php echo $idUsuario; ?>'
            };
            if(typeof PrintEngine !== 'undefined') {
                PrintEngine.show(dataDoc);
            } else {
                window.print();
            }
        }
    };
})();

// Buscador en tiempo real
document.getElementById('masterSearch').onkeyup = function() {
    let val = this.value.toLowerCase();
    document.querySelectorAll("#mainTable tbody tr").forEach(r => {
        r.style.display = (r.innerText.toLowerCase().includes(val) || r.className.includes(val)) ? "" : "none";
    });
};
</script>