<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Corte de Caja Z</title>
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: Arial, sans-serif; font-size: 11px; background: #d0d0d0; padding: 20px; color: #111; }
  .cut-report-shell { width: 100%; overflow-x: auto; overflow-y: visible; -webkit-overflow-scrolling: touch; padding-bottom: 8px; }
  .page { background: white; width: 900px; min-width: 900px; margin: 0 auto; padding: 16px 20px 24px; box-shadow: 0 4px 24px rgba(0,0,0,0.25); }
  .cut-report-document { max-width: none; }
  .report-title { text-align: center; font-size: 15px; font-weight: bold; margin-bottom: 10px; }
  .filtro-bar { display: flex; align-items: center; gap: 10px; margin-bottom: 14px; padding: 8px 10px; background: #f5f5f5; border: 1px solid #ddd; border-radius: 3px; }
  .filtro-bar label { font-size: 11px; font-weight: bold; }
  .filtro-bar input[type=date] { border: 1px solid #ccc; border-radius: 3px; padding: 4px 8px; font-size: 11px; }
  .btn-consultar { padding: 5px 16px; background: #e67e22; color: white; border: none; border-radius: 3px; cursor: pointer; font-size: 11px; font-weight: bold; }
  .btn-consultar:hover { background: #cf6d17; }
  .btn-imprimir { padding: 5px 16px; background: #3a5a8a; color: white; border: none; border-radius: 3px; cursor: pointer; font-size: 11px; font-weight: bold; margin-left: auto; }
  .btn-imprimir:hover { background: #2e4a72; }
  .error-box { background: #fde8e8; border: 1px solid #e0a0a0; color: #c0392b; padding: 8px 12px; border-radius: 3px; margin-bottom: 10px; font-size: 11px; }
  .spinner { text-align: center; padding: 20px; color: #888; font-size: 11px; }
  .header-meta { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 6px; gap: 10px; }
  .logo-box { background: #e67e22; color: white; font-size: 13px; font-weight: bold; padding: 6px 14px; border-radius: 3px; letter-spacing: 1px; }
  .meta-right { text-align: right; font-size: 10.5px; line-height: 1.8; }
  .meta-right strong { margin-right: 4px; }
  .sucursal-line { font-size: 9.5px; color: #666; max-width: 340px; margin-top: 2px; }
  .empresa-title { text-align: center; font-size: 14px; font-weight: bold; margin: 8px 0 4px; }
  .section-header { background: #3a5a8a; color: white; text-align: center; font-weight: bold; font-size: 11.5px; padding: 4px; }
  .resumen-table { width: 100%; border-collapse: collapse; border: 1px solid #3a5a8a; margin-bottom: 8px; }
  .resumen-table td { border: 1px solid #b0bcd0; padding: 5px 8px; vertical-align: middle; }
  .td-venta-total { background: #e67e22; color: white; text-align: center; width: 130px; }
  .td-venta-total .vtl { font-size: 10px; display: block; }
  .td-venta-total .vta { font-size: 20px; font-weight: bold; display: block; line-height: 1.2; }
  .td-prom { background: #3a5a8a; color: white; text-align: center; width: 115px; font-size: 10px; line-height: 1.7; }
  .td-prom .pl { font-size: 9px; opacity: 0.8; display: block; }
  .td-prom .pv { font-size: 13px; font-weight: bold; display: block; }
  .td-data { text-align: center; font-size: 10.5px; }
  .td-data .da { font-weight: bold; font-size: 12px; display: block; }
  .td-data .dl { font-size: 9.5px; color: #555; display: block; }
  .three-cols { display: grid; grid-template-columns: 195px 1fr 210px; border: 1px solid #aaa; margin-bottom: 6px; }
  .col-box { border-right: 1px solid #aaa; }
  .col-box:last-child { border-right: none; }
  .col-hdr { background: #3a5a8a; color: white; text-align: center; font-weight: bold; font-size: 10.5px; padding: 3px 6px; }
  .col-hdr.green { background: #229954; }
  .col-body { padding: 5px 8px; }
  .row2 { display: flex; justify-content: space-between; padding: 1.5px 0; font-size: 10.5px; }
  .row2.bold { font-weight: bold; }
  .row2.border-t { border-top: 1px dashed #bbb; margin-top: 3px; padding-top: 3px; }
  .inner-hdr { background: #3a5a8a; color: white; text-align: center; font-size: 9.5px; font-weight: bold; padding: 2px 6px; margin: 5px -8px; }
  .cat-row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 10.5px; border-bottom: 1px dotted #ddd; }
  .cat-row:last-child { border-bottom: none; }
  .cat-right { text-align: right; }
  .pct-tag { color: #888; font-size: 9.5px; margin-left: 4px; }
  .hora-table { width: 100%; border-collapse: collapse; margin-bottom: 7px; font-size: 10.5px; }
  .hora-table th { background: #3a5a8a; color: white; padding: 3px 8px; text-align: left; font-size: 10px; }
  .hora-table th:last-child { text-align: right; }
  .hora-table td { border: 1px solid #ddd; padding: 3px 8px; }
  .hora-table td:last-child { text-align: right; font-weight: bold; }
  .hora-table tr.pico { background: #fff3e0; }
  .hora-table tfoot td { background: #f5f5f5; font-weight: bold; border-top: 2px solid #aaa; }
  .stats-table { width: 100%; border-collapse: collapse; margin-bottom: 7px; font-size: 10.5px; }
  .stats-table td { border: 1px solid #bbb; padding: 3px 7px; }
  .stats-table .sl { font-weight: bold; background: #f5f5f5; width: 155px; }
  .stats-table .sq { width: 40px; text-align: center; }
  .stats-table .sa { width: 95px; text-align: right; }
  .stats-table .se { color: #444; }
  .four-cols { display: grid; grid-template-columns: repeat(4, 1fr); border: 1px solid #aaa; margin-bottom: 6px; }
  .fc { border-right: 1px solid #aaa; }
  .fc:last-child { border-right: none; }
  .fc-hdr { background: #229954; color: white; text-align: center; font-weight: bold; font-size: 9.5px; padding: 3px; }
  .fc-body { padding: 4px 6px; font-size: 10px; }
  .fc-row { display: flex; justify-content: space-between; padding: 1px 0; }
  .fc-row .fv { font-weight: bold; }
  .report-footer { text-align: right; font-size: 9px; color: #888; margin-top: 8px; border-top: 1px solid #ddd; padding-top: 4px; }
  @media print { body { background: white; padding: 0; } .cut-report-shell { overflow: visible; padding-bottom: 0; } .page { box-shadow: none; width: 900px; min-width: 900px; } .filtro-bar { display: none; } }

  /* -- Mobile responsive for Corte Z/X -- */
  @media (max-width: 820px) {
    body { padding: 8px; padding-bottom: calc(80px + env(safe-area-inset-bottom, 0px)); background: #e8e8e8; }
    .cut-report-shell { margin: 0 -2px; padding: 0 2px 8px; }
    .page { width: 900px !important; min-width: 900px !important; padding: 14px 16px 20px; box-shadow: 0 2px 12px rgba(0,0,0,.15); }
    .report-title { font-size: 14px; word-break: normal; white-space: normal; }
    .filtro-bar { flex-wrap: wrap; gap: 8px; padding: 8px 10px; align-items: center; }
    .filtro-bar label { font-size: 10px; }
    .filtro-bar input[type=date], .filtro-bar select { font-size: 12px; min-height: 36px; flex: 0 0 auto; min-width: 120px; }
    .btn-consultar, .btn-imprimir { font-size: 10px; padding: 6px 10px; min-height: 36px; flex: 0 0 auto; }
    .header-meta { flex-direction: row; gap: 10px; }
    .meta-right { text-align: right; font-size: 10px; }
    .empresa-title { font-size: 12px; }
    .section-header { font-size: 10px; padding: 3px 6px; }
    .resumen-table,
    .hora-table,
    .stats-table { min-width: 100%; }
    .stats-table td { white-space: nowrap; font-size: 10px; padding: 3px 5px; }
  }

  @media (max-width: 430px) {
    body { padding: 4px; }
    .cut-report-shell { margin: 0; padding-bottom: 6px; }
    .page { width: 900px !important; min-width: 900px !important; padding: 12px 14px 18px; }
    .report-title { font-size: 12px; }
    .filtro-bar { padding: 4px 6px; }
    .btn-consultar, .btn-imprimir { padding: 5px 8px; font-size: 10px; }
  }
</style>
</head>
<body class="main-container cut-report-view">
<div class="cut-report-shell">
<div class="page cut-report-document">
  <div class="report-title">REPORTE DE CORTE DE CAJA Z &mdash; CIERRE DIARIO</div>
  <div class="filtro-bar header-report filtros no-print">
    <label for="f-fecha">FECHA:</label>
    <input type="date" id="f-fecha" onchange="cargarTurnos()">
    <label for="f-turno" style="margin-left:6px;">TURNO:</label>
    <select id="f-turno" class="select-full" style="border:1px solid #ccc;border-radius:3px;padding:4px 8px;font-size:11px;min-width:130px;">
      <option value="">Todos los turnos</option>
    </select>
    <button class="btn-consultar" type="button" onclick="volverCortes()" style="background:#fff;color:#3a5a8a;border:1px solid #3a5a8a;">Volver</button>
    <button class="btn-consultar" onclick="cargar()">Consultar</button>
    <button class="btn-consultar" type="button" onclick="cargar()" style="background:#3a5a8a;">Actualizar</button>
    <button class="btn-imprimir" onclick="window.print()">Imprimir</button>
  </div>
  <div id="error-box" class="error-box" style="display:none;"></div>
  <div id="spinner" class="spinner" style="display:none;">Cargando datos...</div>
  <div id="resultado" style="display:none;"></div>
</div>
</div>

<script src="/js/arkhon-utils.js"></script>
<script>
var LOCAL_API_KEY = '';


const pct = (a,b) => b>0 ? ((a/b)*100).toFixed(2)+'%' : '0.00%';
const dtFull = () => new Date().toLocaleString('es-MX',{day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',second:'2-digit'});

document.getElementById('f-fecha').value = hoy();


// Carga los turnos disponibles para la fecha seleccionada
async function cargarTurnos(){
  const fecha = document.getElementById('f-fecha').value;
  const sel   = document.getElementById('f-turno');
  sel.innerHTML = '<option value="">Todos los turnos</option>';
  if(!fecha) return;
  try {
    const data = await api(`/turnos/historial?fecha=${fecha}`);
    const lista = Array.isArray(data) ? data : (data.turnos || data || []);
    lista.forEach((t,i) => {
      const opt = document.createElement('option');
      opt.value = t.idturno;
      const hora = t.apertura ? new Date(t.apertura).toLocaleTimeString('es-MX',{hour:'2-digit',minute:'2-digit'}) : '';
      opt.textContent = (t.nombre_turno || `Turno ${i+1}`) + (hora ? ' · ' + hora : '');
      sel.appendChild(opt);
    });
  } catch(_) {}
}

async function cargar(){
  const fecha   = document.getElementById('f-fecha').value;
  const idturno = document.getElementById('f-turno').value;
  if(!fecha){ showError('Selecciona una fecha'); return; }
  document.getElementById('error-box').style.display='none';
  document.getElementById('resultado').style.display='none';
  document.getElementById('spinner').style.display='block';
  try { await _initAuth(); } catch(_){}
  try {
    if(idturno){
      // -- Turno específico: usar corte-z real por idturno --------------
      const [cx, retiros] = await Promise.all([
        api(`/reportes/corte-z?idturno=${idturno}`),
        api(`/retiros-caja?inicio=${fecha}&fin=${fecha}&pageSize=200`).catch(()=>null),
      ]);
      renderCorteZ(cx, cx.ventasPorHora || [], retiros, fecha, cx.top_productos || [], idturno, cx.turno);
    } else {
      // -- Sin turno: corte-z preview/definitivo como fuente principal --------
      const [repRaw, horaRaw2, retiros] = await Promise.all([
        api(`/reportes/corte-z?fecha=${fecha}`).catch(()=>null),
        api(`/dashboard/ventas-hora?fecha=${fecha}`).catch(()=>null),
        api(`/retiros-caja?inicio=${fecha}&fin=${fecha}&pageSize=200`).catch(()=>null),
      ]);
      if(!repRaw) throw new Error('No se pudo cargar Corte Z desde /api/reportes/corte-z');
      renderCorteZ(repRaw, repRaw.ventasPorHora || horaRaw2, retiros, fecha, repRaw.top_productos || [], repRaw.turno?.idturno || null, repRaw.turno || null);
    }
  } catch(e){ showError('Error: '+e.message); }
  finally { document.getElementById('spinner').style.display='none'; }
}

function showError(msg){
  document.getElementById('spinner').style.display='none';
  const eb=document.getElementById('error-box'); eb.textContent=msg; eb.style.display='block';
}

function volverCortes(){
  if (window.self !== window.top) {
    window.parent.postMessage({ tipo: 'nav_dashboard' }, '*');
    return;
  }
  if (window.history.length > 1) {
    window.history.back();
    return;
  }
  window.location.href = '/';
}

function renderCorteZ(rep, hora, retiros, fecha, topProdsTurno, idturno, turnoInfo){
  const r   = rep||{};
  const sections = r.sections || {};
  const v = r.ventas || {};
  const tot = r.totales || {
    venta_total: v.venta_total || 0,
    venta_neta: v.subtotal || 0,
    subtotal: v.subtotal || 0,
    tickets: v.tickets || 0,
    cuentas_pagadas: v.tickets || 0,
    descuentos: v.descuentos || 0,
    total_descuentos: v.descuentos || 0,
    impuesto: v.impuestos || 0,
    impuestos: v.impuestos || 0,
    alimentos: v.alimentos || 0,
    bebidas: v.bebidas || 0,
    otros: v.otros || 0,
    venta_con_impuesto: v.venta_total || 0,
  };
  const venta     = tot.venta_total||tot.venta_con_impuesto||0;
  const ventaNeta = tot.venta_neta||tot.subtotal||0;
  const tickets   = tot.tickets||tot.cuentas_pagadas||0;
  if(venta===0 && tickets===0){ document.getElementById("resultado").innerHTML='<div style="padding:30px;text-align:center;color:#888;font-size:12px;">Sin datos para esta fecha.<br><small>No se encontraron cuentas pagadas en el período seleccionado.</small></div>'; document.getElementById("resultado").style.display="block"; return; }
  const desc      = tot.descuentos||tot.total_descuentos||0;
  const alimentos = tot.alimentos||0;
  const bebidas   = tot.bebidas||0;
  const otros     = tot.otros||0;
  const impuesto  = tot.impuesto||tot.impuestos||(venta-ventaNeta)||0;
  const fp        = sections.paymentMethodsSales?.lines || r.formasPago||r.formas_pago||[];
  const vs        = sections.serviceTypeBreakdown?.lines || r.ventasServicio||r.ventas_servicio||[];
  const ticketProm= tickets>0 ? venta/tickets : 0;

  const horaRaw = Array.isArray(hora)?hora:(hora?.filas||[]);
  const horas   = horaRaw.filter(h=>(h.venta||0)>0).sort((a,b)=>Number(a.hora)-Number(b.hora));
  const picHora = horas.length ? horas.reduce((mx,h)=>h.venta>mx.venta?h:mx,horas[0]) : null;

  const retRes  = retiros?.resumen||{};
  const retMovs = retiros?.movimientos||[];
  const retTot  = retRes.total_retiros||0;
  const depTot  = retRes.total_depositos||0;
  const propTot = retRes.total_propinas||0;

  const fecLabel = new Date(fecha+'T12:00:00').toLocaleDateString('es-MX',{weekday:'long',day:'numeric',month:'long',year:'numeric'});
  const fecCorta = new Date(fecha+'T12:00:00').toLocaleDateString('es-MX',{day:'2-digit',month:'2-digit',year:'numeric'});

  const fmtHora = d => { try { return new Date(d).toLocaleTimeString('es-MX',{hour:'2-digit',minute:'2-digit'}); } catch(_){ return '—'; } };
  const turnoLabel = turnoInfo
    ? ` &mdash; ${turnoInfo.cajero||'Turno'} &nbsp;·&nbsp; ${fmtHora(turnoInfo.apertura)}${turnoInfo.cierre?' – '+fmtHora(turnoInfo.cierre):' (abierto)'}`
    : '';
  const titleLabel = new URLSearchParams(window.location.search).get('tipo') === 'X' ? 'X' : 'Z';
  const statusLabel = sections.header?.status || (turnoInfo && !turnoInfo.cierre ? 'Preview / Turno abierto' : 'Definitivo / Turno cerrado');
  const corteLabel = idturno ? `${titleLabel} (Turno #${idturno})${turnoLabel}` : `${titleLabel} &mdash; Cierre Diario`;

  const getSvc = k => { const s=vs.find(x=>((x.area||x.servicio||'').toLowerCase()).includes(k)); return s?(s.total||s.venta||0):0; };

  const paymentKind = p => {
    const id = String(p.idformadepago || '').trim().toLowerCase();
    const name = String(p.forma_pago || '').trim().toLowerCase();
    const brand = String(p.cardBrand || '').trim().toLowerCase();
    const tipo = Number(p.tipo || 0);
    if (id === 'ef' || id === 'dll' || name.includes('efectivo') || name.includes('dolares')) return 'cash';
    if (tipo === 2 || ['visa','mc','amex','tc','td'].includes(id) || /visa|mastercard|american|tarjeta|debito|débito|credito|crédito/.test(name + ' ' + brand)) return 'card';
    return 'other';
  };
  let sumEf=0, sumTar=0, sumOt=0;
  fp.forEach(p=>{
    const amount = Number(p.total || 0);
    const kind = paymentKind(p);
    if (kind === 'cash') sumEf += amount;
    else if (kind === 'card') sumTar += amount;
    else sumOt += amount;
  });

  const svcRows = vs.map(s=>`<div class="cat-row"><span>${s.area || s.servicio || 'Sin area'}:</span><span class="cat-right"><strong>${fmt(s.total||s.venta||0)}</strong><span class="pct-tag">(${pct(s.total||s.venta||0,ventaNeta)})</span></span></div>`).join('');

  const movRows = retMovs.slice(0,6).map(m=>{ const c=(m.tipo_label||'')==='retiro'?'#c0392b':(m.tipo_label||'')==='deposito'?'#27ae60':'#333'; return `<div class="row2"><span style="max-width:110px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${m.concepto||'&#8212;'}</span><span style="color:${c}">${fmt(m.importe||0)}</span></div>`; }).join('');

  const horaRows = horas.map(h=>`<tr${picHora&&h.hora==picHora.hora?' class="pico"':''}><td>${String(h.hora).padStart(2,'0')}:00 hrs</td><td>${h.tickets||0}</td><td>${fmt(h.venta||0)}</td></tr>`).join('');

  const fpRows = fp.map(p=>`<div class="fc-row"><span>${p.forma_pago}</span><span class="fv">${fmt(p.total)}</span></div>`).join('');
  const tipRows = (sections.paymentMethodsTips?.lines || fp.filter(p => (p.propina||0) > 0)).map(p=>`<div class="fc-row"><span>${p.forma_pago}</span><span class="fv">${fmt(p.propina)}</span></div>`).join('');
  const areaRows = sections.areaSales?.lines || vs;
  const vsRows = areaRows.map(s=>`<div class="fc-row"><span>${s.area || s.servicio}</span><span class="fv">${fmt(s.total||s.venta||0)}</span></div>`).join('');
  const cortesX = Array.isArray(r.cortesX) ? r.cortesX : [];
  const cortesXRows = cortesX.map(c=>`<tr>
    <td>${c.estacion || '—'}</td>
    <td style="text-align:center;font-weight:bold">#${c.idturno || '—'}</td>
    <td>${fmtHora(c.apertura)}${c.cierre ? ' – '+fmtHora(c.cierre) : ' · ABIERTO'}</td>
    <td style="text-align:center">${c.tickets || 0}</td>
    <td>${fmt(c.efectivo || 0)}</td>
    <td>${fmt(c.tarjeta || 0)}</td>
    <td>${fmt(c.depositos || 0)}</td>
    <td>${fmt(c.retiros || 0)}</td>
    <td>${fmt(c.venta_total || 0)}</td>
  </tr>`).join('');

  document.getElementById('resultado').innerHTML = `
    <div class="header-meta">
      <div><div class="logo-box">ARKHON</div></div>
      <div class="meta-right">
        <div><strong>Fecha:</strong> DEL: ${fecCorta} AL: ${fecCorta}</div>
        <div><strong>Corte:</strong> ${corteLabel}</div>
        <div><strong>Estado:</strong> ${statusLabel}</div>
        <div class="sucursal-line">${fecLabel.charAt(0).toUpperCase()+fecLabel.slice(1)}</div>
      </div>
    </div>
    <div class="empresa-title">CORTE DE CAJA ${titleLabel} &mdash; ${idturno ? 'TURNO #'+idturno : 'CIERRE DIARIO'}</div>
    ${statusLabel.includes('Preview') ? '<div class="error-box" style="display:block;background:#fff3cd;border-color:#f59e0b;color:#78350f;">PREVIEW - TURNO ABIERTO. No es Corte Z definitivo hasta cerrar el turno.</div>' : ''}

    ${cortesX.length ? `<div class="section-header">CORTES X INCLUIDOS &mdash; SEPARADOS POR ESTACIÓN Y TURNO</div>
    <table class="hora-table cortes-x-table">
      <thead><tr><th>Estación</th><th>Turno</th><th>Horario</th><th>Tickets</th><th>Efectivo</th><th>Tarjeta</th><th>Depósitos</th><th>Retiros</th><th>Venta X</th></tr></thead>
      <tbody>${cortesXRows}</tbody>
      <tfoot><tr><td colspan="3">TOTAL CORTE Z · ${cortesX.length} CORTE${cortesX.length===1?'':'S'} X</td><td style="text-align:center">${tickets}</td><td>${fmt(sumEf)}</td><td>${fmt(sumTar)}</td><td>${fmt(depTot)}</td><td>${fmt(retTot)}</td><td>${fmt(venta)}</td></tr></tfoot>
    </table>` : ''}

    <div class="section-header">RESUMEN DEL DIA</div>
    <table class="resumen-table">
      <tr>
        <td rowspan="3" class="td-venta-total"><span class="vtl">VENTA TOTAL</span><span class="vta">${fmt(venta)}</span></td>
        <td class="td-prom" rowspan="3"><span class="pl">CUENTA PROMEDIO</span><span class="pv">${fmt(ticketProm)}</span><span class="pl">TICKET PROMEDIO</span><span class="pv">${fmt(ticketProm)}</span></td>
        <td class="td-data"><span class="da">${fmt(sumEf)}</span><span class="dl">EFECTIVO</span></td>
        <td class="td-data"><span class="da">${fmt(alimentos)}</span><span class="dl">ALIMENTOS</span></td>
        <td class="td-data"><span class="da">${fmt(getSvc('comedor'))} (${pct(getSvc('comedor'),venta)})</span><span class="dl">COMEDOR</span></td>
      </tr>
      <tr>
        <td class="td-data"><span class="da">${fmt(sumTar)}</span><span class="dl">TARJETAS</span></td>
        <td class="td-data"><span class="da">${fmt(bebidas)}</span><span class="dl">BEBIDAS</span></td>
        <td class="td-data"><span class="da">${fmt(getSvc('domicilio'))} (${pct(getSvc('domicilio'),venta)})</span><span class="dl">DOMICILIO</span></td>
      </tr>
      <tr>
        <td class="td-data"><span class="da">${fmt(sumOt)}</span><span class="dl">OTROS</span></td>
        <td class="td-data"><span class="da">${fmt(otros)}</span><span class="dl">OTROS</span></td>
        <td class="td-data"><span class="da">${fmt(getSvc('rapido')||getSvc('r\u00e1pido'))} (${pct(getSvc('rapido')||getSvc('r\u00e1pido'),venta)})</span><span class="dl">RAPIDO</span></td>
      </tr>
    </table>

    <div class="three-cols">
      <div class="col-box">
        <div class="col-hdr">CAJA</div>
        <div class="col-body">
          <div class="row2"><span>+EFECTIVO:</span><span>${fmt(sumEf)}</span></div>
          <div class="row2"><span>+TARJETA:</span><span>${fmt(sumTar)}</span></div>
          <div class="row2"><span>+OTROS:</span><span>${fmt(sumOt)}</span></div>
          <div class="row2"><span>+DEPOSITOS EFECTIVO:</span><span>${fmt(depTot)}</span></div>
          <div class="row2"><span>-RETIROS EFECTIVO:</span><span>${fmt(retTot)}</span></div>
          <div class="row2"><span>-PROPINAS PAGADAS:</span><span>${fmt(propTot)}</span></div>
          <div style="border-top:1px dashed #aaa;margin:4px 0"></div>
          <div class="row2 bold"><span>SALDO FINAL:</span><span>${fmt(venta)}</span></div>
        </div>
      </div>
      <div class="col-box">
        <div class="col-hdr">VENTA (SIN IMPUESTO)</div>
        <div class="col-body">
          <div class="cat-row"><span><strong>ALIMENTOS:</strong></span><span class="cat-right"><strong>${fmt(alimentos)}</strong><span class="pct-tag">(${pct(alimentos,ventaNeta)})</span></span></div>
          <div class="cat-row"><span><strong>BEBIDAS:</strong></span><span class="cat-right"><strong>${fmt(bebidas)}</strong><span class="pct-tag">(${pct(bebidas,ventaNeta)})</span></span></div>
          <div class="cat-row"><span><strong>OTROS:</strong></span><span class="cat-right"><strong>${fmt(otros)}</strong><span class="pct-tag">(${pct(otros,ventaNeta)})</span></span></div>
          <div class="inner-hdr">POR TIPO DE SERVICIO</div>
          ${svcRows}
          <div style="border-top:1px solid #aaa;margin:4px 0;padding-top:4px">
            <div class="row2"><span>SUBTOTAL:</span><span>${fmt(ventaNeta)}</span></div>
            <div class="row2"><span>- DESCUENTOS:</span><span>${fmt(desc)}</span></div>
            <div class="row2 bold border-t"><span>VENTA NETA:</span><span>${fmt(ventaNeta-desc)}</span></div>
          </div>
          <div style="border-top:1px solid #aaa;border-bottom:1px solid #aaa;margin:4px 0;padding:4px 0">
            <div class="row2 bold"><span>IMPUESTO TOTAL:</span><span>${fmt(impuesto)}</span></div>
          </div>
          <div class="row2 bold" style="font-size:12px"><span>VENTA CON IMP.:</span><span>${fmt(venta)}</span></div>
          <div class="inner-hdr">FACTURACION ARKHON CLOUD</div>
          <div class="row2"><span>FUENTE:</span><span>Arkhon Cloud / Me-Facturo</span></div>
          <div class="row2"><span>VENTA FACTURADA:</span><span>${sections.cloudBilling?.synced ? fmt(sections.cloudBilling.ventaFacturada||0) : 'No confirmado'}</span></div>
          <div class="row2"><span>VENTA NO FACTURADA:</span><span>${sections.cloudBilling?.synced ? fmt(sections.cloudBilling.ventaNoFacturada||0) : 'No confirmado'}</span></div>
          <div class="row2"><span>FACTURAS EMITIDAS:</span><span>${sections.cloudBilling?.synced ? (sections.cloudBilling.facturasEmitidas||0) : 'No confirmado'}</span></div>
          <div class="row2"><span>UUID:</span><span>${sections.cloudBilling?.synced ? (sections.cloudBilling.uuidCount||0) : 'No confirmado'}</span></div>
          <div class="row2"><span>WARNING:</span><span>${sections.cloudBilling?.warning || 'Sin warning'}</span></div>
        </div>
      </div>
      <div class="col-box">
        <div class="col-hdr">MOVIMIENTOS DE CAJA</div>
        <div class="col-body">
          <div class="row2"><span>RETIROS:</span><span style="color:#c0392b">${fmt(retTot)}</span></div>
          <div class="row2"><span>DEPOSITOS:</span><span style="color:#27ae60">${fmt(depTot)}</span></div>
          <div class="row2"><span>PROPINAS:</span><span>${fmt(propTot)}</span></div>
          <div style="border-top:1px dashed #aaa;margin:4px 0"></div>
          <div class="row2 bold"><span>TOTAL MOV.:</span><span>${retMovs.length}</span></div>
          ${retMovs.length ? '<div class="inner-hdr">DETALLE</div>'+movRows : '<div style="color:#888;font-size:9.5px;padding:3px 0">Sin movimientos</div>'}
        </div>
      </div>
    </div>

    ${horas.length ? `
    <div class="section-header">VENTAS POR HORA${picHora?' &mdash; PICO: '+String(picHora.hora).padStart(2,'0')+':00 hrs  '+fmt(picHora.venta):''}</div>
    <table class="hora-table">
      <thead><tr><th>Hora</th><th>Tickets</th><th style="text-align:right">Venta</th></tr></thead>
      <tbody>${horaRows}</tbody>
      <tfoot><tr><td colspan="2" style="padding:4px 8px">Total acumulado del dia</td><td style="text-align:right;padding:4px 8px">${fmt(venta)}</td></tr></tfoot>
    </table>` : ''}

    <table class="stats-table">
      <tr><td class="sl">Total de cuentas</td><td class="sq">${tickets}</td><td class="sa">${fmt(venta)}</td><td class="se">Ticket promedio</td><td class="sa">${fmt(ticketProm)}</td></tr>
      <tr><td class="sl">Descuentos</td><td class="sq">&#8212;</td><td class="sa">${fmt(desc)}</td><td class="se">Impuesto total</td><td class="sa">${fmt(impuesto)}</td></tr>
      <tr><td class="sl">Retiros efectivo</td><td class="sq">${retMovs.filter(m=>m.tipo_label==='retiro').length}</td><td class="sa">${fmt(retTot)}</td><td class="se">Depositos efectivo</td><td class="sa">${fmt(depTot)}</td></tr>
    </table>

    <div class="four-cols">
      <div class="fc"><div class="fc-hdr">FORMAS DE PAGO VENTAS</div><div class="fc-body">${fpRows||'<span style="color:#888">&#8212;</span>'}</div></div>
      <div class="fc"><div class="fc-hdr">FORMAS DE PAGO PROPINAS</div><div class="fc-body">${tipRows || '<span style="color:#888">$0.00 confirmado</span>'}</div></div>
      <div class="fc"><div class="fc-hdr">VENTAS POR AREA</div><div class="fc-body">${vsRows||'<span style="color:#888">&#8212;</span>'}</div></div>
      <div class="fc"><div class="fc-hdr">VENTA RAPIDA POR TIPO</div><div class="fc-body"><span style="color:#888">&#8212;</span></div></div>
    </div>

    <div class="report-footer">REPORTE GENERADO &mdash; ${dtFull()}</div>
  ` + (topProdsTurno && topProdsTurno.length ? `
    <div class="section-header" style="margin-top:6px;">TOP PRODUCTOS DEL ${idturno ? 'TURNO' : 'DIA'}</div>
    <table class="hora-table" style="margin-bottom:8px;">
      <thead><tr><th>Producto</th><th style="text-align:center">Cantidad</th><th style="text-align:right">Venta</th></tr></thead>
      <tbody>${topProdsTurno.map((p,i)=>`<tr${i===0?' class="pico"':''}><td>${p.producto||'—'}</td><td style="text-align:center">${p.cantidad||0}</td><td style="text-align:right;font-weight:bold">${fmt(p.total_venta||0)}</td></tr>`).join('')}</tbody>
    </table>` : '');

  document.getElementById('resultado').style.display='block';
  window._lastCorteZ = { rep, retiros, fecha };
}

// postMessage desde dashboard (modulo Turnos)
window.addEventListener('message', function(ev){
  if(!ev.data || ev.data.tipo !== 'set_turno') return;
  const idturno = ev.data.idturno;
  if(!idturno) return;
  
  // Ocultar topbar si corre dentro de un iframe
  if (window.self !== window.top) {
    const tb = document.querySelector('.topbar');
    if (tb) tb.style.display = 'none';
  }
(async()=>{
    try{
      const rawLista = await api('/turnos/historial?desde=2020-01-01&hasta=2099-12-31');
      if(rawLista){
        // La API devuelve data directamente (array o { turnos: [] })
        const lista = Array.isArray(rawLista) ? rawLista : (rawLista.turnos || []);
        const t = lista.find(x=>String(x.idturno)===String(idturno));
        if(t){
          // apertura puede llegar como Date serializado "2024-01-15T06:00:00.000Z"
          // o como string "2024-01-15T06:00:00" — ambos se manejan aquí
          const aperturaStr = String(t.apertura || t.fecha_apertura || '');
          const fecha = aperturaStr.split('T')[0].split(' ')[0];
          if(fecha){
            document.getElementById('f-fecha').value = fecha;
            await cargarTurnos();
            // Asignar el turno en el select y disparar el reporte
            document.getElementById('f-turno').value = String(idturno);
            cargar();
          }
        }
      }
    }catch(_){}
  })();
});

// Iniciar: obtener token ? si hay ?idturno en la URL cargarlo directo, si no cargar hoy
(async()=>{
  try {
    await _initAuth();

  // Leer idturno desde los query params de la URL (ej: /corte-z?idturno=211)
  const urlParams = new URLSearchParams(window.location.search);
  const idturnoURL = urlParams.get('idturno');

  if(idturnoURL){
    const titleLabel = urlParams.get('tipo') === 'X' ? 'X' : 'Z';
    document.querySelector('.report-title').innerHTML = 'REPORTE DE CORTE DE CAJA ' + titleLabel + ' &mdash; ' + (idturnoURL ? 'TURNO' : 'CIERRE DIARIO');
    document.title = `Corte de Caja ${titleLabel}`;

    // Modo "turno específico" — buscar su fecha y cargarlo directamente
    try{
      const d = await api(`/turnos/historial?desde=2020-01-01&hasta=2099-12-31`);
      const lista = Array.isArray(d) ? d : (d?.turnos || []);
      const t = lista.find(x => String(x.idturno) === String(idturnoURL));
      if(t){
        const aperturaStr = String(t.apertura || t.fecha_apertura || '');
        const fecha = aperturaStr.split('T')[0].split(' ')[0];
        if(fecha){
          document.getElementById('f-fecha').value = fecha;
          await cargarTurnos();
          document.getElementById('f-turno').value = String(idturnoURL);
          cargar();
          return; // salir aquí, no ejecutar el cargar() de hoy
        }
      }
    }catch(_){}
    // Si falla la búsqueda, caer al comportamiento normal
  }

  // Modo normal: cargar turnos de hoy y el reporte del día
  await cargarTurnos();
  cargar();
  } catch(e) { showError('Error al iniciar: ' + e.message); }
})();
</script>
</body>
</html>

