<?php
// 1. Forzamos la codificación desde el servidor
header('Content-Type: text/html; charset=utf-8');

session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso denegado."); }

$idPropietario = $_SESSION['IDUg'] ?? '1'; 
$idUsuarioActivo = $_SESSION['IDU'] ?? '1'; 
$dbName = $_SESSION['BD'] ?? "MS_Datos"; 
$prefijoTablas = "$idPropietario-"; 
$vendedor = $_SESSION['NombreUsuario'] ?? "Técnico Receptor";

try {
    // Aseguramos que la conexión a la base de datos también sea UTF-8
    $pdo = new PDO("mysql:host=localhost;dbname=$dbName;charset=utf8", "root", "33comRxXMysql");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $hoy = date('ymd'); 
    $prefijoFolio = "OS-" . $hoy . "-";
    $sqlF = "SELECT Folio FROM `{$prefijoTablas}Ordenes_Servicio` WHERE Folio LIKE '$prefijoFolio%' ORDER BY ID_Orden DESC LIMIT 1";
    $resF = $pdo->query($sqlF)->fetch(PDO::FETCH_ASSOC);
    $nuevoC = $resF ? intval(substr($resF['Folio'], -3)) + 1 : 1;
    $folioOS = $prefijoFolio . str_pad($nuevoC, 3, "0", STR_PAD_LEFT);
    
} catch (PDOException $e) { die("Error: " . $e->getMessage()); }
?>

<meta charset="UTF-8">

<style>
    .wiz-container { display: flex; background: #fff; min-height: 85vh; border-radius: 12px; overflow: hidden; box-shadow: 0 5px 20px rgba(0,0,0,0.1); margin: -10px; }
    .wiz-sidebar { width: 260px; background: #2c3e50; padding: 40px 20px; position: relative; }
    .wiz-sidebar::after { content: ""; position: absolute; left: 37px; top: 60px; bottom: 60px; width: 2px; background: rgba(255,255,255,0.1); z-index: 1; }
    .wiz-step { display: flex; align-items: center; margin-bottom: 40px; position: relative; z-index: 2; color: rgba(255,255,255,0.4); cursor: pointer; transition: 0.3s; }
    .wiz-step.active { color: #fff; }
    .wiz-step.completed { color: #f26522; }
    .wiz-sphere { width: 34px; height: 34px; border-radius: 50%; background: #34495e; border: 2px solid #5d6d7e; display: flex; align-items: center; justify-content: center; margin-right: 15px; font-weight: bold; }
    .wiz-step.active .wiz-sphere { border-color: #f26522; background: #f26522; color: #fff; box-shadow: 0 0 15px rgba(242,101,34,0.4); }
    .wiz-step.completed .wiz-sphere { background: #f26522; border-color: #f26522; color: #fff; }
    .wiz-label { font-size: 0.8rem; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; }
    .wiz-body { flex: 1; padding: 40px; background: #fdfdfd; display: flex; flex-direction: column; overflow-y: auto; }
    .pane-title { border-bottom: 2px solid #f26522; padding-bottom: 10px; margin-bottom: 25px; font-weight: 800; color: #333; }
    .visual-btn { border: 2px solid #e9ecef; border-radius: 12px; padding: 15px 10px; cursor: pointer; transition: 0.2s; text-align: center; font-weight: 700; background: #fff; color: #495057; width: 100%; display: block; }
    .visual-btn i { font-size: 28px; display: block; margin-bottom: 8px; }
    .visual-btn:hover { border-color: #adb5bd; background: #f8f9fa; }
    .visual-btn.active { border-color: #f26522 !important; background: rgba(242,101,34,0.08) !important; color: #f26522 !important; }
    .st-mojado.active { border-color: #dc3545 !important; background: #fff5f5 !important; color: #dc3545 !important; }
    .st-enciende.active { border-color: #28a745 !important; background: #f0fff4 !important; color: #28a745 !important; }

    @media (max-width: 991px) {
        .wiz-container { flex-direction: column; }
        .wiz-sidebar { width: 100%; padding: 15px; display: flex; overflow-x: auto; }
        .wiz-sidebar::after { display: none; }
        .wiz-step { margin-bottom: 0; margin-right: 20px; white-space: nowrap; }
    }
</style>

<div class="container-fluid">
    <div class="wiz-container">
        <div class="wiz-sidebar">
            <div class="wiz-step active" onclick="osEngine.goTo(1)" id="step-1"><div class="wiz-sphere">1</div><span class="wiz-label">Cliente</span></div>
            <div class="wiz-step" onclick="osEngine.goTo(2)" id="step-2"><div class="wiz-sphere">2</div><span class="wiz-label">Equipo</span></div>
            <div class="wiz-step" onclick="osEngine.goTo(3)" id="step-3"><div class="wiz-sphere">3</div><span class="wiz-label">Recepción</span></div>
            <div class="wiz-step" onclick="osEngine.goTo(4)" id="step-4"><div class="wiz-sphere">4</div><span class="wiz-label">Diagnóstico</span></div>
            <div class="wiz-step" onclick="osEngine.goTo(5)" id="step-5"><div class="wiz-sphere">5</div><span class="wiz-label">Finalizar</span></div>
        </div>

        <div class="wiz-body">
            <div class="d-flex justify-content-between mb-4">
                <h3 class="pane-title" id="txtStepTitle">Registro de Cliente</h3>
                <span class="badge badge-dark p-2 h-100" style="font-size: 1rem;">FOLIO: <?php echo $folioOS; ?></span>
            </div>

            <form id="formOSMaster">
                <div class="pane-content" id="pane-1">
                    <div class="row">
                        <div class="col-md-9 mb-3">
                            <label class="font-weight-bold">Buscador de Clientes</label>
                            <div class="input-group input-group-lg">
                                <div class="input-group-prepend"><span class="input-group-text bg-white"><i class="feather icon-search"></i></span></div>
                                <input type="text" id="busCli" class="form-control" placeholder="Nombre o Teléfono...">
                            </div>
                            <div id="resCli" class="list-group position-absolute w-100 shadow-lg" style="z-index: 1000; display:none;"></div>
                        </div>
                        <div class="col-md-3 mb-3 d-flex align-items-end">
                            <button type="button" class="btn btn-primary btn-block btn-lg" onclick="$('#modalNuevoCliente').modal('show')">NUEVO</button>
                        </div>
                    </div>
                    <div id="cliSelected" class="alert alert-success d-none">
                        <div class="d-flex justify-content-between align-items-center">
                            <div><h5 class="m-0 font-weight-bold" id="lblCliNom"></h5><p class="m-0" id="lblCliTel"></p></div>
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="osEngine.clearClient()">Quitar</button>
                        </div>
                    </div>
                </div>

                <div class="pane-content d-none" id="pane-2">
                    <div class="row">
                        <div class="col-md-4 mb-3"><label class="font-weight-bold">Categoría</label>
                            <select id="eqCat" class="form-control form-control-lg"><option>Smartphone</option><option>Laptop</option><option>Tablet</option><option>PC</option><option>Consola</option></select>
                        </div>
                        <div class="col-md-4 mb-3"><label class="font-weight-bold">Marca</label><input type="text" id="eqMarca" class="form-control form-control-lg" placeholder="Ej: Samsung"></div>
                        <div class="col-md-4 mb-3"><label class="font-weight-bold">Modelo</label><input type="text" id="eqModelo" class="form-control form-control-lg" placeholder="Ej: S23 Ultra"></div>
                        <div class="col-md-6 mb-3"><label class="font-weight-bold">Serie / IMEI</label><input type="text" id="eqSerie" class="form-control" placeholder="Identificador único"></div>
                        <div class="col-md-6 mb-3"><label class="font-weight-bold">Pass / Patrón</label><input type="text" id="eqPass" class="form-control" placeholder="Clave de acceso"></div>
                    </div>
                </div>

                <div class="pane-content d-none" id="pane-3">
                    <h6 class="font-weight-bold text-muted mb-3">Accesorios Recibidos</h6>
                    <div class="row mb-4">
                        <div class="col-4"><div class="visual-btn" onclick="osEngine.toggleBtn(this)"><i class="feather icon-battery-charging"></i>Cargador<input type="checkbox" name="accesorios" value="Cargador" class="d-none"></div></div>
                        <div class="col-4"><div class="visual-btn" onclick="osEngine.toggleBtn(this)"><i class="feather icon-smartphone"></i>Funda<input type="checkbox" name="accesorios" value="Funda" class="d-none"></div></div>
                        <div class="col-4"><div class="visual-btn" onclick="osEngine.toggleBtn(this)"><i class="feather icon-shopping-bag"></i>Mochila<input type="checkbox" name="accesorios" value="Mochila" class="d-none"></div></div>
                    </div>
                    <h6 class="font-weight-bold text-muted mb-3">Estado Físico del Equipo</h6>
                    <div class="row text-center mb-3">
                        <div class="col-6 col-md-3 mb-2"><div class="visual-btn st-mojado" onclick="osEngine.toggleBtn(this)"><i class="feather icon-droplet"></i>Mojado<input type="checkbox" id="stMojado" class="d-none"></div></div>
                        <div class="col-6 col-md-3 mb-2"><div class="visual-btn st-enciende" onclick="osEngine.toggleBtn(this)"><i class="feather icon-power"></i>Enciende<input type="checkbox" id="stEnciende" class="d-none"></div></div>
                        <div class="col-6 col-md-3 mb-2"><div class="visual-btn" onclick="osEngine.toggleBtn(this)"><i class="feather icon-grid"></i>Estrellado<input type="checkbox" id="stEstrellado" class="d-none"></div></div>
                        <div class="col-6 col-md-3 mb-2"><div class="visual-btn" onclick="osEngine.toggleBtn(this)"><i class="feather icon-package"></i>Roto<input type="checkbox" id="stRoto" class="d-none"></div></div>
                    </div>
                    <label class="font-weight-bold">Notas Estéticas Adicionales</label>
                    <textarea id="eqEstetica" class="form-control" rows="2" placeholder="Rayones, golpes, etc."></textarea>
                </div>

                <div class="pane-content d-none" id="pane-4">
                    <label class="font-weight-bold text-danger h6">Falla que Reporta el Cliente</label>
                    <textarea id="eqFalla" class="form-control mb-3" rows="3" placeholder="Describa el problema..."></textarea>
                    <label class="font-weight-bold">Diagnóstico Técnico Preliminar</label>
                    <textarea id="eqDiag" class="form-control" rows="2" placeholder="Visible solo en taller..."></textarea>
                </div>

                <div class="pane-content d-none" id="pane-5">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <label class="font-weight-bold">Costo Estimado $</label><input type="number" id="txtTotal" class="form-control form-control-lg mb-3" value="0.00">
                            <label class="font-weight-bold text-success">Anticipo / Adelanto $</label><input type="number" id="txtAnticipo" class="form-control form-control-lg border-success text-success" value="0.00">
                        </div>
                        <div class="col-md-6 text-center">
                            <div class="p-4 bg-white rounded border shadow-sm">
                                <h6 class="text-muted small uppercase">Resta por Pagar</h6>
                                <h1 class="text-danger font-weight-bold" id="lblResta">$0.00</h1>
                            </div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-success btn-block btn-lg mt-5 py-3 shadow font-weight-bold" onclick="osEngine.saveOS()">REGISTRAR E IMPRIMIR ORDEN</button>
                </div>
            </form>

            <div class="mt-auto pt-4 d-flex justify-content-between border-top">
                <button type="button" class="btn btn-outline-secondary btn-lg px-5" id="btnAtras" disabled onclick="osEngine.move(-1)">Anterior</button>
                <button type="button" class="btn btn-dark btn-lg px-5 shadow" id="btnSig" onclick="osEngine.move(1)">Siguiente</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalNuevoCliente" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content shadow-lg border-0">
            <div class="modal-body p-4 text-center">
                <h5 class="font-weight-bold">Nuevo Cliente</h5>
                <input type="text" id="nc_nombre" class="form-control mb-2" placeholder="Nombre completo">
                <input type="number" id="nc_tel" class="form-control mb-3" placeholder="Teléfono">
                <button type="button" class="btn btn-primary btn-block" onclick="osEngine.saveQuickClient()">GUARDAR</button>
            </div>
        </div>
    </div>
</div>

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

<script>
const TERMINOS_SERVICIO = `
1. No hay garantía en equipos mojados o con rastro de humedad.
2. La garantía es de 30 días sobre la mano de obra reportada.
3. No nos hacemos responsables por pérdida de información.
4. Equipos no reclamados en 60 días causan abandono.
`;

const osEngine = (function() {
    const CFG = { 
        fol: '<?php echo $folioOS; ?>', 
        db: '<?php echo $dbName; ?>', 
        px: '<?php echo $prefijoTablas; ?>', 
        tech: '<?php echo $vendedor; ?>', 
        idu: '<?php echo $idUsuarioActivo; ?>' 
    };

    let step = 1, client = null;
    const titles = ["Registro de Cliente", "Detalles del Equipo", "Estado y Accesorios", "Falla y Diagnóstico", "Finalización"];

    return {
        init: function() {
            this.calc();
            document.getElementById('txtTotal').oninput = () => this.calc();
            document.getElementById('txtAnticipo').oninput = () => this.calc();
            
            document.getElementById('busCli').onkeyup = async (e) => {
                const v = e.target.value; if(v.length < 3) return;
                const fd = new FormData(); 
                fd.append('sql', `SELECT IDC, Nombre, Telefono FROM \`${CFG.px}Clientes\` WHERE Nombre LIKE '%${v}%' OR Telefono LIKE '%${v}%' LIMIT 5`); 
                fd.append('db', CFG.db);
                const r = await fetch(`../librerias/AJAX/Select.php`, {method:'POST', body:fd}).then(res => res.json());
                const box = document.getElementById('resCli'); box.innerHTML = '';
                if(r.data.length) {
                    box.style.display = 'block';
                    r.data.forEach(c => {
                        const b = document.createElement('button'); b.className = 'list-group-item list-group-item-action py-3';
                        b.innerHTML = `<b>${c.Nombre}</b><br><small>${c.Telefono}</small>`;
                        b.onclick = (ev) => { ev.preventDefault(); client = c; this.renderClient(); box.style.display='none'; };
                        box.appendChild(b);
                    });
                }
            };
        },
        goTo: function(s) { if(s < step || (client && s > step)) { while(step !== s) { this.move(s > step ? 1 : -1); } } },
        move: function(dir) {
            if(dir === 1 && step === 1 && !client) return alert("Seleccione un cliente primero.");
            document.getElementById(`pane-${step}`).classList.add('d-none');
            document.getElementById(`step-${step}`).classList.remove('active');
            if(dir === 1) document.getElementById(`step-${step}`).classList.add('completed');
            step += dir;
            document.getElementById(`pane-${step}`).classList.remove('d-none');
            document.getElementById(`step-${step}`).classList.add('active');
            document.getElementById('txtStepTitle').innerText = titles[step-1];
            document.getElementById('btnAtras').disabled = step === 1;
            document.getElementById('btnSig').style.display = step === 5 ? 'none' : 'block';
        },
        toggleBtn: function(el) { el.classList.toggle('active'); const ck = el.querySelector('input'); if(ck) ck.checked = !ck.checked; },
        calc: function() {
            const t = parseFloat(document.getElementById('txtTotal').value) || 0;
            const a = parseFloat(document.getElementById('txtAnticipo').value) || 0;
            document.getElementById('lblResta').innerText = new Intl.NumberFormat('es-MX', {style:'currency', currency:'MXN'}).format(t - a);
        },
        renderClient: function() {
            document.getElementById('lblCliNom').innerText = client.Nombre;
            document.getElementById('lblCliTel').innerText = "📞 " + client.Telefono;
            document.getElementById('cliSelected').classList.remove('d-none');
            document.getElementById('busCli').value = '';
        },
        clearClient: function() { client = null; document.getElementById('cliSelected').classList.add('d-none'); },
        
        saveQuickClient: async function() {
            const n = document.getElementById('nc_nombre').value.trim();
            const t = document.getElementById('nc_tel').value.trim();
            if(!n || !t) return alert("Escriba nombre y teléfono.");
            
            const fd = new FormData(); 
            fd.append('db', CFG.db); 
            fd.append('sql', `INSERT INTO \`${CFG.px}Clientes\` (IDU, Nombre, Telefono) VALUES ('${CFG.idu}', '${n}', '${t}')`);
            
            const r = await fetch(`../librerias/AJAX/Execute.php`, {method:'POST', body:fd}).then(res => res.json());
            if(r.status === 'success' || r.last_id) { 
                client = {IDC: r.last_id, Nombre: n, Telefono: t}; 
                this.renderClient(); 
                $('#modalNuevoCliente').modal('hide'); 
            } else {
                alert("Error al guardar: " + r.message);
            }
        },

        saveOS: async function() {
            if(!client) return alert("Falta cliente");
            const acc = Array.from(document.querySelectorAll('input[name="accesorios"]:checked')).map(i => i.value);
            const total = parseFloat(document.getElementById('txtTotal').value) || 0;
            const ant = parseFloat(document.getElementById('txtAnticipo').value) || 0;
            const eq = `${document.getElementById('eqCat').value} ${document.getElementById('eqMarca').value} ${document.getElementById('eqModelo').value}`;

            const sqlCab = `INSERT INTO \`${CFG.px}Ordenes_Servicio\` (IDC, Folio, Tipo_Servicio, Anticipo, Total_Estimado, ID_Usuario_Recibe, Notas_Cliente) VALUES (${client.IDC}, '${CFG.fol}', '${eq}', ${ant}, ${total}, '${CFG.idu}', '${document.getElementById('eqFalla').value}')`;
            const fd1 = new FormData(); fd1.append('db', CFG.db); fd1.append('sql', sqlCab);
            const r1 = await fetch(`../librerias/AJAX/Execute.php`, {method:'POST', body:fd1}).then(res => res.json());

            if(r1.status === 'success' || r1.last_id) {
                const idO = r1.last_id;
                const sqlItm = `INSERT INTO \`${CFG.px}Items_Servicio\` (ID_Orden, Categoria, Marca, Modelo, Serie_Placas, Problema_Reportado, Diagnostico_Tecnico) VALUES (${idO}, '${document.getElementById('eqCat').value}', '${document.getElementById('eqMarca').value}', '${document.getElementById('eqModelo').value}', '${document.getElementById('eqSerie').value}', '${document.getElementById('eqFalla').value}', '${document.getElementById('eqDiag').value}')`;
                const fd2 = new FormData(); fd2.append('db', CFG.db); fd2.append('sql', sqlItm);
                await fetch(`../librerias/AJAX/Execute.php`, {method:'POST', body:fd2});

                const dataDoc = {
                    folio: CFG.fol, fecha: new Date().toLocaleDateString(), hora: new Date().toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'}),
                    cliente: client.Nombre, tel: client.Telefono, dir: client.Direccion || 'N/D',
                    equipo: eq, serie: document.getElementById('eqSerie').value || 'S/N', pass: document.getElementById('eqPass').value || 'N/A',
                    falla: document.getElementById('eqFalla').value, diag: document.getElementById('eqDiag').value || 'Pte.',
                    accesorios: acc.join(', ') || 'Ninguno', costo: total, adelanto: ant, resta: (total - ant), tech: CFG.tech,
                    status: { enciende: document.getElementById('stEnciende').checked, mojado: document.getElementById('stMojado').checked, estrellado: document.getElementById('stEstrellado').checked, roto: document.getElementById('stRoto').checked, obs: document.getElementById('eqEstetica').value || 'Ninguna' },
                    tu: CFG.idu, td: CFG.fol, isOS: true
                };

                // --- INTEGRACIÓN: GUARDAR EN DOCUMENTOS GENERADOS PARA IMPRESIÓN AUTOMÁTICA ---
                const selectPrint = document.getElementById('pe-select-config');
                const configId = selectPrint ? selectPrint.value : 1; // Toma el ID de la impresora seleccionada en el modal
                
                const jsonPrint = JSON.stringify(dataDoc).replace(/'/g, "\\'"); // Escapamos comillas simples para SQL
                const uuid = 'DOC-' + Date.now();
                
                const sqlPrint = `INSERT INTO \`1-Documentos_Generados\` 
                                (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado) 
                                VALUES ('${uuid}', 'OrdenServicio', ${idO}, ${configId}, '${jsonPrint}', 'PENDIENTE')`;
                
                const fdPrint = new FormData(); 
                fdPrint.append('db', 'MS_Datos'); // Se guarda en la tabla general de documentos
                fdPrint.append('sql', sqlPrint);
                await fetch(`../librerias/AJAX/Execute.php`, {method:'POST', body:fdPrint});
                // --- FIN INTEGRACIÓN ---

                PrintEngine.show(dataDoc);
            }
        }
    };
})();
window.addEventListener('load', () => osEngine.init());


// --- MOTOR DE IMPRESIÓN ---
window.addEventListener('load', function() {
    if (typeof PrintEngine !== 'undefined') {
        PrintEngine.renderOriginal = PrintEngine.render;
        PrintEngine.render = function() {
            const info = this.saleInfo;
            if(!info.isOS) return this.renderOriginal(); 
            const conf = JSON.parse(document.getElementById('pe-select-config').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(); 
            const isTicket = papel.includes('mm');
            hoja.className = `pe-paper pe-p-${papel} ${conf.Orientacion.toLowerCase()}`;
            const apiQR = `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent('https://tusitio.com/check.php?f='+info.td)}`;

            if(isTicket) {
                hoja.innerHTML = `<div style="font-family:monospace; font-size:11px; text-align:center; padding:5px;">
                    <div style="font-weight:bold; font-size:14px; border-bottom:1px dashed #000; padding:5px 0;">ORDEN DE SERVICIO</div>
                    <div style="text-align:left; margin-top:10px;">
                        <b>FOLIO: ${info.folio}</b><br>FECHA: ${info.fecha}<br>CLIENTE: ${info.cliente}<br>TEL: ${info.tel}<br>
                        --------------------------------<br><b>EQUIPO:</b> ${info.equipo}<br>S/N: ${info.serie}<br>
                        --------------------------------<br><b>FALLA:</b> ${info.falla}<br>--------------------------------<br>
                        TOTAL: ${money(info.costo)}<br>ANT: ${money(info.adelanto)}<br><b>RESTA: ${money(info.resta)}</b>
                    </div>
                    <br><img src="${apiQR}" style="width:100px; height:100px;"><br>
                    <div style="font-size:8px; text-align:justify; margin-top:10px;">${TERMINOS_SERVICIO}</div>
                </div>`;
            } else {
                hoja.innerHTML = `<div style="font-family:Arial; padding:40px; color:#333;">
                    <table width="100%" style="border-bottom:3px solid #f26522; padding-bottom:10px;">
                        <tr>
                            <td><h2 style="color:#f26522; margin:0;">ORDEN DE SERVICIO</h2></td>
                            <td align="right" valign="top"><div style="background:#333; color:#fff; padding:15px; font-weight:bold; font-size:1.5em;">${info.folio}</div></td>
                        </tr>
                    </table>
                    <table width="100%" style="margin-top:20px;">
                        <tr>
                            <td width="50%"><b>CLIENTE:</b><br>${info.cliente}<br>Tel: ${info.tel}</td>
                            <td width="50%"><b>EQUIPO:</b><br>${info.equipo}<br>S/N: ${info.serie}</td>
                        </tr>
                    </table>
                    <div style="border:1px solid #ddd; padding:15px; margin-top:10px;">
                        <b>ESTADO FÍSICO:</b> [${info.status.enciende?'X':' '}] Enciende | [${info.status.mojado?'X':' '}] Mojado<br>
                        <b>Accesorios:</b> ${info.accesorios}
                    </div>
                    <div style="border:1px solid #ddd; padding:15px; margin-top:10px; min-height:80px;"><b>FALLA:</b> ${info.falla}</div>
                    <div style="display:flex; justify-content:space-between; margin-top:30px;">
                        <div style="width:60%; font-size:10px;">${TERMINOS_SERVICIO.replace(/\n/g, '<br>')}</div>
                        <div style="width:35%; text-align:right;">
                            <table width="100%">
                                <tr><td>Costo:</td><td align="right">${money(info.costo)}</td></tr>
                                <tr><td>Anticipo:</td><td align="right">-${money(info.adelanto)}</td></tr>
                                <tr style="font-weight:bold; color:red;"><td>RESTA:</td><td align="right">${money(info.resta)}</td></tr>
                            </table>
                        </div>
                    </div>
                </div>`;
            }
        };
    }
});
</script>