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

$db_datos = $_SESSION['BD'] ?? "MS_Datos";
$idProp   = $_SESSION['IDUg'] ?? '3'; 
$prefijo  = "$idProp-"; 

// Tablas con comillas invertidas para evitar errores por el guion
$tb_os   = "`{$idProp}-Ordenes_Servicio`";
$fecha_mes = date('Y-m-d', strtotime('-1 month'));

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

    $sqlKpi = "SELECT 
                COUNT(*) as totales,
                SUM(CASE WHEN Estado NOT IN ('Listo', 'Entregado', 'Cancelado') THEN 1 ELSE 0 END) as pendientes,
                SUM(CASE WHEN Estado IN ('Listo', 'Entregado') THEN 1 ELSE 0 END) as terminados
               FROM $tb_os WHERE Fecha_Ingreso >= '{$fecha_mes} 00:00:00'";
    $resKpi = $pdo->query($sqlKpi)->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $resKpi = ['totales' => 0, 'pendientes' => 0, 'terminados' => 0]; }
?>

<meta charset="UTF-8">
<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>
    body { background-color: #f0f2f5; font-family: 'Segoe UI', sans-serif; }
    .main-content { padding: 25px; }
    
    /* KPIs */
    .card-kpi { border: none; border-radius: 12px; background: #fff; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
    .kpi-v { font-size: 1.8rem; font-weight: 800; display: block; }
    .kpi-l { font-size: 0.7rem; font-weight: 700; color: #94a3b8; text-transform: uppercase; }

    /* Tabla */
    .card-table { border: none; border-radius: 15px; background: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.05); overflow: hidden; margin-top: 20px; }
    .table thead th { background: #f8fafc; color: #64748b; font-size: 0.75rem; text-transform: uppercase; padding: 15px; border: none; }
    .row-os:hover { background-color: #f1f5f9; cursor: pointer; }

    /* DRAWER LATERAL */
    .modal.drawer .modal-dialog {
        position: fixed; margin: auto; width: 600px; height: 100%; right: -600px;
        transition: right 0.4s ease-in-out;
    }
    .modal.drawer.show .modal-dialog { right: 0; }
    .modal.drawer .modal-content { height: 100%; border: none; border-radius: 0; border-left: 5px solid #f26522; overflow-y: auto; }
    
    .dr-box { background: #f8fafc; border-radius: 10px; padding: 15px; margin-bottom: 15px; border: 1px solid #edf2f7; }
    .money-row { display: flex; justify-content: space-around; background: #1a202c; color: #fff; padding: 12px; border-radius: 8px; margin-bottom: 20px; }
</style>

<div class="main-content">
    <div class="row">
        <div class="col-md-4"><div class="card-kpi"><span class="kpi-l">Órdenes Mes</span><span class="kpi-v"><?php echo $resKpi['totales']; ?></span></div></div>
        <div class="col-md-4"><div class="card-kpi"><span class="kpi-l text-warning">Pendientes</span><span class="kpi-v text-warning"><?php echo $resKpi['pendientes']; ?></span></div></div>
        <div class="col-md-4"><div class="card-kpi"><span class="kpi-l text-success">Listos</span><span class="kpi-v text-success"><?php echo $resKpi['terminados']; ?></span></div></div>
    </div>

    <div class="input-group input-group-lg mt-4 shadow-sm">
        <div class="input-group-prepend"><span class="input-group-text bg-white border-0"><i class="fas fa-search text-muted"></i></span></div>
        <input type="text" id="os-search" class="form-control border-0" placeholder="Buscar por Folio, Cliente o Teléfono...">
    </div>

    <div class="card-table">
        <div class="table-responsive">
            <table class="table align-middle">
                <thead>
                    <tr>
                        <th class="pl-4">Folio / Fecha</th>
                        <th>Cliente</th>
                        <th>Equipo</th>
                        <th class="text-center">Estado</th>
                        <th class="text-right pr-4">Total</th>
                    </tr>
                </thead>
                <tbody id="os-tbody"></tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade drawer" id="drPanel" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content shadow-lg">
            <div class="modal-header bg-dark text-white">
                <h4 id="dr-folio-title" class="m-0 font-weight-bold">---</h4>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body p-4">
                <button class="btn btn-primary btn-block btn-lg mb-4 shadow" id="btn-reprint">
                    <i class="fas fa-print mr-2"></i> REIMPRIMIR ORDEN
                </button>

                <div class="money-row">
                    <div><small>Total</small><b id="dr-total">$0</b></div>
                    <div><small>Anticipo</small><b class="text-success" id="dr-anti">$0</b></div>
                    <div><small>Resta</small><b class="text-danger" id="dr-resta">$0</b></div>
                </div>

                <div class="dr-box">
                    <small class="text-muted font-weight-bold uppercase">Cliente</small>
                    <b id="dr-cliente" class="d-block h5">---</b>
                    <p id="dr-telefono" class="text-primary mb-0">---</p>
                </div>

                <div class="dr-box">
                    <small class="text-muted font-weight-bold uppercase">Equipo</small>
                    <p id="dr-equipo" class="mb-1">---</p>
                    <small id="dr-serie" class="text-info font-weight-bold">---</small>
                </div>

                <div class="dr-box" style="border-left-color: #e53e3e;">
                    <small class="text-danger font-weight-bold uppercase">Falla Reportada</small>
                    <p id="dr-falla" class="mb-0 text-dark italic">---</p>
                </div>

                <h6 class="font-weight-bold mt-4 mb-3"><i class="fas fa-history mr-2"></i> Historial</h6>
                <div id="dr-historial" style="border-left: 2px solid #eee; padding-left: 20px; margin-left: 10px;"></div>
            </div>
        </div>
    </div>
</div>

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

<script>
const APP = { db: "<?php echo $db_datos; ?>", px: "<?php echo $prefijo; ?>", mes: "<?php echo $fecha_mes; ?>" };

document.addEventListener('DOMContentLoaded', () => {
    cargarTabla();
    document.getElementById('os-search').addEventListener('keyup', (e) => cargarTabla(e.target.value.trim()));
});

function cargarTabla(q = "") {
    let where = `WHERE os.Fecha_Ingreso >= '${APP.mes} 00:00:00'`;
    if (q !== "") where = `WHERE (os.Folio LIKE '%${q}%' OR cli.Nombre LIKE '%${q}%' OR cli.Telefono LIKE '%${q}%' OR its.Modelo LIKE '%${q}%')`;

    const sql = `SELECT os.*, cli.Nombre, cli.Telefono, cli.Direccion, its.Marca, its.Modelo, its.Categoria, its.Serie_Placas, its.Problema_Reportado
                 FROM \`${APP.px}Ordenes_Servicio\` os 
                 LEFT JOIN \`${APP.px}Clientes\` cli ON os.IDC = cli.IDC 
                 LEFT JOIN \`${APP.px}Items_Servicio\` its ON os.ID_Orden = its.ID_Orden 
                 ${where} ORDER BY os.ID_Orden DESC LIMIT 100`;

    fetch('../librerias/AJAX/Select.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=${APP.db}`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} })
    .then(r => r.json()).then(res => {
        const tbody = document.getElementById('os-tbody'); tbody.innerHTML = '';
        if (res.data) res.data.forEach(o => {
            const tr = document.createElement('tr');
            tr.className = 'row-os';
            tr.onclick = () => abrirDrawer(o);
            tr.innerHTML = `
                <td class="pl-4"><b>${o.Folio}</b><br><small>${o.Fecha_Ingreso.substring(0,10)}</small></td>
                <td><b>${o.Nombre}</b></td>
                <td><span class="badge badge-light border">${o.Marca} ${o.Modelo}</span></td>
                <td class="text-center"><span class="badge badge-primary px-2">${o.Estado}</span></td>
                <td class="text-right pr-4 font-weight-bold">$${parseFloat(o.Total_Estimado).toLocaleString()}</td>`;
            tbody.appendChild(tr);
        });
    });
}

function abrirDrawer(o) {
    document.getElementById('dr-folio-title').innerText = o.Folio;
    document.getElementById('dr-cliente').innerText = o.Nombre;
    document.getElementById('dr-telefono').innerText = "📞 " + o.Telefono;
    document.getElementById('dr-equipo').innerText = `${o.Marca} ${o.Modelo} (${o.Categoria})`;
    document.getElementById('dr-serie').innerText = "S/N: " + (o.Serie_Placas || 'N/A');
    document.getElementById('dr-falla').innerText = o.Problema_Reportado || 'No detallada.';
    
    const t = parseFloat(o.Total_Estimado), a = parseFloat(o.Anticipo);
    document.getElementById('dr-total').innerText = '$' + t.toLocaleString();
    document.getElementById('dr-anti').innerText = '$' + a.toLocaleString();
    document.getElementById('dr-resta').innerText = '$' + (t - a).toLocaleString();

    document.getElementById('btn-reprint').onclick = () => ejecutarImpresion(o);

    // Historial
    const sqlH = `SELECT * FROM \`${APP.px}Ordenes_Historial\` WHERE ID_Orden = ${o.ID_Orden} ORDER BY Fecha_Cambio DESC`;
    fetch('../librerias/AJAX/Select.php', { method: 'POST', body: `sql=${encodeURIComponent(sqlH)}&db=${APP.db}`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} })
    .then(r => r.json()).then(res => {
        const hBox = document.getElementById('dr-historial'); hBox.innerHTML = '';
        if(res.data) res.data.forEach(h => {
            hBox.innerHTML += `<div class="mb-2"><small class="text-muted d-block">${h.Fecha_Cambio}</small><b>${h.Estado_Nuevo}</b>: ${h.Comentario || ''}</div>`;
        });
    });
    $('#drPanel').modal('show');
}

function ejecutarImpresion(o) {
    const t = parseFloat(o.Total_Estimado), a = parseFloat(o.Anticipo);
    const dataDoc = {
        isOS: true, reprint: true,
        folio: o.Folio, fecha: o.Fecha_Ingreso,
        cliente: o.Nombre, tel: o.Telefono,
        equipo: `${o.Marca} ${o.Modelo}`, serie: o.Serie_Placas || 'S/N',
        falla: o.Problema_Reportado || 'N/A',
        costo: t, adelanto: a, resta: (t - a)
    };
    if (typeof PrintEngine !== 'undefined') PrintEngine.show(dataDoc);
}

// ==========================================
// 🖨️ MOTOR DE IMPRESIÓN DINÁMICO (4 TAMAÑOS)
// ==========================================
if (typeof PrintEngine !== 'undefined') {
    PrintEngine.renderOriginal = PrintEngine.render;
    PrintEngine.render = function() {
        const info = this.saleInfo;
        if(!info.isOS) return this.renderOriginal(); 

        const sel = document.getElementById('pe-select-config');
        const conf = JSON.parse(sel.selectedOptions[0].dataset.conf);
        const hoja = document.getElementById('pe-hoja-digital');
        const money = n => new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(n);
        
        const papel = conf.Tipo_Papel.toLowerCase(); // 58mm, 80mm, a4, a5
        const ori = conf.Orientacion.toLowerCase(); // vertical, horizontal
        
        hoja.className = `pe-paper pe-p-${papel} ${ori}`;
        
        // Estilos base por tamaño
        let style = (papel.includes('mm')) 
            ? 'font-family:monospace; font-size:12px; padding:5px;' 
            : 'font-family:Arial; padding:40px;';

        const headerReprint = info.reprint ? `<div style="background:#000; color:#fff; text-align:center; padding:5px; font-weight:bold; margin-bottom:10px; font-size:14px;">*** REIMPRESIÓN ***</div>` : '';

        if (papel.includes('mm')) {
            // FORMATO TICKET (58mm / 80mm)
            hoja.innerHTML = `
                <div style="${style}">
                    ${headerReprint}
                    <center>
                        <b style="font-size:16px;">ORDEN DE SERVICIO</b><br>
                        <b>FOLIO: ${info.folio}</b><br>
                        ${info.fecha}<br>
                    </center>
                    --------------------------------<br>
                    <b>CLIENTE:</b> ${info.cliente}<br>
                    <b>TEL:</b> ${info.tel}<br>
                    --------------------------------<br>
                    <b>EQUIPO:</b> ${info.equipo}<br>
                    <b>SERIE:</b> ${info.serie}<br>
                    <b>FALLA:</b> ${info.falla}<br>
                    --------------------------------<br>
                    <table width="100%">
                        <tr><td>TOTAL:</td><td align="right">${money(info.costo)}</td></tr>
                        <tr><td>ANTICIPO:</td><td align="right">-${money(info.adelanto)}</td></tr>
                        <tr style="font-size:14px;"><td><b>RESTA:</b></td><td align="right"><b>${money(info.resta)}</b></td></tr>
                    </table>
                    <br><center>Favor de presentar este ticket<br>para recoger su equipo.</center>
                </div>`;
        } else {
            // FORMATO DOCUMENTO (A4 / A5)
            const isHorizontal = ori === 'horizontal';
            hoja.innerHTML = `
                <div style="${style}">
                    ${headerReprint}
                    <table width="100%" style="border-bottom:2px solid #333; padding-bottom:10px;">
                        <tr>
                            <td><h1 style="color:#f26522; margin:0;">ORDEN DE SERVICIO</h1></td>
                            <td align="right" valign="top">
                                <div style="background:#333; color:#fff; padding:10px; font-size:20px; font-weight:bold;">${info.folio}</div>
                                <span>Fecha: ${info.fecha}</span>
                            </td>
                        </tr>
                    </table>
                    <div style="display:flex; margin-top:30px; border:1px solid #eee; border-radius:10px; padding:20px; background:#fafafa;">
                        <div style="flex:1;">
                            <b style="text-transform:uppercase; color:#777;">Información del Cliente</b><br>
                            <span style="font-size:18px; font-weight:bold;">${info.cliente}</span><br>
                            Teléfono: ${info.tel}
                        </div>
                        <div style="flex:1; border-left:1px solid #ddd; padding-left:20px;">
                            <b style="text-transform:uppercase; color:#777;">Detalles del Equipo</b><br>
                            <b>Modelo:</b> ${info.equipo}<br>
                            <b>S/N:</b> ${info.serie}
                        </div>
                    </div>
                    <div style="margin-top:20px; padding:20px; border:1px solid #eee; border-radius:10px; min-height:100px;">
                        <b style="color:#e53e3e;">FALLA REPORTADA:</b><br>${info.falla}
                    </div>
                    <div style="display:flex; justify-content:space-between; margin-top:40px;">
                        <div style="width:50%; border-top:1px solid #333; text-align:center; padding-top:10px; margin-top:50px;">
                            Firma de Conformidad Cliente
                        </div>
                        <div style="width:40%;">
                            <table width="100%" style="font-size:16px;">
                                <tr><td>Subtotal Estimado:</td><td align="right">${money(info.costo)}</td></tr>
                                <tr><td>Anticipo Recibido:</td><td align="right">-${money(info.adelanto)}</td></tr>
                                <tr style="font-size:22px; font-weight:bold; color:red;"><td>TOTAL RESTANTE:</td><td align="right">${money(info.resta)}</td></tr>
                            </table>
                        </div>
                    </div>
                </div>`;
        }
    };
}
</script>