<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Auditoría de Cortesías y Beneficios - ARKHON</title>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet"/>
<style>
:root{--bg:#f7f8fc;--surface:#fff;--border:#e5e7ef;--text:#111827;--muted:#8b95a7;--orange:#f97316;--orange-lt:rgba(249,115,22,.10);--red:#dc2626;--red-lt:rgba(220,38,38,.10);--green:#0f9f6e;--green-lt:rgba(15,159,110,.10);--amber:#d97706;--amber-lt:rgba(217,119,6,.10);--blue:#2563eb;--blue-lt:rgba(37,99,235,.10);--shadow:0 10px 30px rgba(17,24,39,.08);--r:12px}
*{box-sizing:border-box}body{margin:0;background:var(--bg);font-family:'Plus Jakarta Sans',Arial,sans-serif;color:var(--text);font-size:13px}button,input,select{font:inherit}.topbar{height:58px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 20px;position:sticky;top:0;z-index:10}.topbar h1{font-size:15px;font-weight:800;margin:0;flex:1}.icon{width:34px;height:34px;border-radius:10px;background:var(--orange);display:grid;place-items:center;box-shadow:0 6px 16px rgba(249,115,22,.25)}.icon svg{width:18px;height:18px;stroke:#fff;fill:none;stroke-width:2}.btn{border:1px solid var(--border);background:var(--surface);border-radius:10px;padding:9px 13px;font-size:12px;font-weight:800;cursor:pointer;display:inline-flex;align-items:center;gap:7px;color:var(--text)}.btn.primary{border-color:var(--orange);background:var(--orange);color:#fff;box-shadow:0 6px 16px rgba(249,115,22,.22)}.btn svg{width:15px;height:15px;stroke:currentColor;fill:none;stroke-width:2.2}.report-container{width:100%;padding:18px}.report-content{max-width:1440px;margin:0 auto}.filters{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);padding:14px;margin-bottom:14px;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px;align-items:end}.fg{display:flex;flex-direction:column;gap:4px;min-width:0}.fg label{font-size:9.5px;text-transform:uppercase;letter-spacing:.08em;font-weight:800;color:var(--muted)}.fg input,.fg select{width:100%;min-height:38px;border:1px solid var(--border);border-radius:9px;padding:8px 10px;background:#fff;color:var(--text);font-size:12px;font-weight:700}.checks{display:flex;flex-wrap:wrap;gap:12px;align-items:center;grid-column:span 5;min-height:38px}.check{display:flex;align-items:center;gap:7px;color:var(--text);font-size:12px;font-weight:700}.kpis{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px;margin-bottom:14px}.kpi{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:14px;box-shadow:var(--shadow);min-width:0}.kpi small{display:block;color:var(--muted);font-size:9.5px;text-transform:uppercase;letter-spacing:.08em;font-weight:800;margin-bottom:5px}.kpi strong{display:block;font-size:20px;font-weight:800;letter-spacing:-.02em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.kpi.danger strong{color:var(--red)}.kpi.warn strong{color:var(--amber)}.kpi.ok strong{color:var(--green)}.grid-rank{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:12px;margin-bottom:14px}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden}.card-head{padding:12px 14px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:10px}.card-title{font-size:12px;font-weight:800}.badge{background:var(--orange-lt);color:var(--orange);font-size:10px;font-weight:800;padding:4px 8px;border-radius:999px}.table-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch}table{width:100%;border-collapse:collapse;font-size:12px}th{background:#f8fafc;color:var(--muted);font-size:9.5px;text-transform:uppercase;letter-spacing:.08em;text-align:left;padding:10px 12px;border-bottom:1px solid var(--border);white-space:nowrap}td{padding:10px 12px;border-bottom:1px solid var(--border);color:#374151;vertical-align:top}td.num{text-align:right;font-weight:800;color:var(--text);white-space:nowrap}td.red{color:var(--red)}td.green{color:var(--green)}.empty{padding:28px;text-align:center;color:var(--muted);font-weight:700}.error{display:none;margin-bottom:12px;padding:12px 14px;border-radius:var(--r);background:var(--red-lt);color:var(--red);font-weight:700}.loading{display:none;margin:18px auto;width:24px;height:24px;border:3px solid var(--border);border-top-color:var(--orange);border-radius:50%;animation:spin .8s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.bar{display:grid;grid-template-columns:28px minmax(0,1fr) 90px;gap:10px;align-items:center;padding:10px 14px;border-bottom:1px solid var(--border)}.bar:last-child{border-bottom:0}.rank{font-weight:800;color:var(--orange)}.name{font-weight:800;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.amount{text-align:right;font-weight:800;color:var(--text)}.tag{display:inline-block;padding:3px 6px;border-radius:6px;font-size:10px;font-weight:800;text-transform:uppercase}.tag.red{background:var(--red-lt);color:var(--red)}.tag.amber{background:var(--amber-lt);color:var(--amber)}.tag.green{background:var(--green-lt);color:var(--green)}.tag.blue{background:var(--blue-lt);color:var(--blue)}.tag.gray{background:#f1f5f9;color:#64748b}
@media(max-width:1200px){.filters{grid-template-columns:repeat(4,minmax(0,1fr))}.kpis{grid-template-columns:repeat(4,minmax(0,1fr))}}
@media(max-width:980px){.filters{grid-template-columns:repeat(3,minmax(0,1fr))}.kpis{grid-template-columns:repeat(3,minmax(0,1fr))}}
@media(max-width:640px){.topbar{padding:0 12px}.topbar h1{font-size:14px}.report-container{padding:12px}.filters{grid-template-columns:1fr}.kpis{grid-template-columns:1fr 1fr}.kpi strong{font-size:17px}.btn{width:100%;justify-content:center}.topbar .btn{width:auto}}
@media print{
  @page{size:landscape;margin:10mm}
  body{background:#fff!important;print-color-adjust:exact;-webkit-print-color-adjust:exact}
  .sidebar,.navbar,.topbar,.no-print{display:none!important}
  .report-container{width:100%;margin:0 auto;padding:0;display:flex;justify-content:center}
  .report-content{width:100%;max-width:100%;margin:0 auto}
  .filters{display:none!important}
  .card,.kpi{box-shadow:none!important;break-inside:avoid}
  .table-wrap{overflow:visible!important}
  table{font-size:9.5px}
  .grid-rank{grid-template-columns:1fr 1fr}
}
</style>
<link rel="stylesheet" href="/css/responsive.css?v=410c"/>
</head>
<body>
<div class="topbar no-print header-report">
  <div class="icon"><svg viewBox="0 0 24 24"><path d="M20 12v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"/><path d="M2 7h20v5H2z"/><path d="M12 22V7"/></svg></div>
  <h1 class="header-title">Auditoria de Beneficios de Casino</h1>
  <div class="header-actions">
    <button class="btn" onclick="window.print()"><svg viewBox="0 0 24 24"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>Imprimir</button>
  </div>
</div>

<div class="report-container main-container">
  <main class="report-content">
    <section class="filters filtros no-print">
      <div class="fg"><label>Fecha inicio</label><input type="date" id="f-ini"/></div>
      <div class="fg"><label>Fecha fin</label><input type="date" id="f-fin"/></div>
      <div class="fg"><label>Turno</label><select id="f-turno" class="select-full"><option value="">Todos</option></select></div>
      <div class="fg"><label>Mesero</label><select id="f-mesero" class="select-full"><option value="">Todos</option></select></div>
      <div class="fg"><label>Producto</label><select id="f-producto" class="select-full"><option value="">Todos</option></select></div>
      <div class="fg"><label>Tipo descuento</label><select id="f-tipo" class="select-full"><option value="">Todos</option></select></div>
      <div class="fg"><label>Usuario autorizo</label><select id="f-usuario" class="select-full"><option value="">Todos</option></select></div>
      <div class="fg"><label>Origen de cuenta</label><select id="f-origen" class="select-full">
        <option value="">Todos</option>
        <option value="ABIERTA_TEMPORAL">Cuenta Abierta</option>
        <option value="CERRADA">Cuenta Cerrada</option>
      </select></div>
      <div class="fg"><label>Tipo de auditoria</label><select id="f-auditoria" class="select-full">
        <option value="">Todos</option>
        <option value="CORTESIA_FORMAL">Cortesía Formal</option>
        <option value="CORTESIA_OPERATIVA">Cortesía Operativa</option>
        <option value="DESCUENTO_AUDITABLE">Descuento Auditable</option>
      </select></div>
      <div class="fg" style="display:flex;align-items:flex-end;">
        <button class="btn primary" style="width:100%;height:38px;justify-content:center;" onclick="cargar()"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>Consultar</button>
      </div>
      <div class="checks">
        <label class="check"><input type="checkbox" id="f-sin-motivo"/> Sin motivo</label>
        <label class="check"><input type="checkbox" id="f-sin-auth"/> Sin autorizacion</label>
        <label class="check"><input type="checkbox" id="f-sin-costo"/> Sin costo</label>
      </div>
    </section>
    <div id="error" class="error"></div>
    <div id="loading" class="loading"></div>
    <section id="resultado"></section>
  </main>
</div>

<script src="/js/arkhon-utils.js"></script>
<script>
var LOCAL_API_KEY = '';
const $id = id => document.getElementById(id);
const escapeHtml = v => String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const fdt = v => { try { return new Date(v).toLocaleString('es-MX',{dateStyle:'short',timeStyle:'short'}); } catch { return ''; } };
$id('f-ini').value = hoy();
$id('f-fin').value = hoy();

function fillSelect(id, items, labelAll){
  const el = $id(id);
  if(!el) return;
  const current = el.value;
  el.innerHTML = `<option value="">${labelAll}</option>` + (items || []).map(it => {
    const value = escapeHtml(it.id ?? it.nombre ?? '');
    const label = escapeHtml(it.nombre ?? it.id ?? '');
    return `<option value="${value}">${label}</option>`;
  }).join('');
  if ([...el.options].some(o => o.value === current)) el.value = current;
}

async function cargarCatalogos(){
  try{
    const q = new URLSearchParams();
    if($id('f-ini').value) q.set('inicio', $id('f-ini').value);
    if($id('f-fin').value) q.set('fin', $id('f-fin').value);
    const cats = await api('/reportes/cortesias/catalogos?' + q.toString());
    fillSelect('f-turno', cats.turnos, 'Todos');
    fillSelect('f-mesero', cats.meseros, 'Todos');
    fillSelect('f-producto', cats.productos, 'Todos');
    fillSelect('f-tipo', cats.tiposDescuento, 'Todos');
    fillSelect('f-usuario', cats.usuarios, 'Todos');
  }catch(e){
    console.warn('[cortesias catalogos]', e.message);
  }
}

async function cargar(){
  $id('error').style.display='none';
  $id('resultado').innerHTML='';
  $id('loading').style.display='block';
  try{
    const q = new URLSearchParams();
    const turno = $id('f-turno').value.trim();
    if(turno) q.set('idturno', turno);
    else {
      q.set('inicio', $id('f-ini').value);
      q.set('fin', $id('f-fin').value);
    }
    [['mesero','f-mesero'],['producto','f-producto'],['tipoDescuento','f-tipo'],
     ['usuario','f-usuario'],['origenCuenta','f-origen'],['tipoAuditoria','f-auditoria']].forEach(([k,id])=>{
      const v=$id(id).value.trim(); if(v) q.set(k,v);
    });
    if($id('f-sin-motivo').checked) q.set('soloSinMotivo','1');
    if($id('f-sin-auth').checked) q.set('soloSinAutorizacion','1');
    if($id('f-sin-costo').checked) q.set('soloSinCosto','1');

    const d = await api('/reportes/cortesias?' + q.toString());
    render(d);
  }catch(e){
    const box=$id('error');
    box.textContent = e.message || 'Error al cargar reporte';
    box.style.display='block';
  }finally{$id('loading').style.display='none'}
}

function renderBars(items, emptyText, formatFunc = fmt){
  if(!items || !items.length) return `<div class="empty">${emptyText}</div>`;
  return items.map((it,i)=>`<div class="bar ranking-item">
    <div class="rank ranking-rank">${i+1}</div>
    <div class="name ranking-name">${escapeHtml(it.nombre)}</div>
    <div class="amount ranking-meta">${formatFunc(it.importe)}</div>
  </div>`).join('');
}

function tagType(type) {
  if(type === 'CORTESIA_FORMAL') return '<span class="tag blue">FORMAL</span>';
  if(type === 'CORTESIA_OPERATIVA') return '<span class="tag red">OPERATIVA</span>';
  if(type === 'DESCUENTO_AUDITABLE') return '<span class="tag amber">DESCUENTO</span>';
  return `<span class="tag gray">${type}</span>`;
}

function tagStatus(status) {
  if(status === 'COMPLETO') return '<span class="tag green">OK</span>';
  if(status === 'SIN_USUARIO_AUTORIZADOR') return '<span class="tag red">SIN AUTH</span>';
  if(status === 'SIN_MOTIVO') return '<span class="tag amber">SIN MOTIVO</span>';
  if(status === 'SIN_COSTO') return '<span class="tag gray">SIN COSTO</span>';
  return `<span class="tag gray">${status}</span>`;
}

function render(d){
  const r = d?.resumen || {};
  const det = d?.detalle || [];
  const rank = d?.rankings || {};
  
  let html = `<div class="kpis">
    <div class="kpi danger"><small>Importe Descontado</small><strong>${fmt(r.totalImporteDescontado)}</strong></div>
    <div class="kpi danger"><small>100% Regalado</small><strong>${fmt(r.totalRegalado)}</strong></div>
    <div class="kpi warn"><small>Desc. Parciales</small><strong>${fmt(r.totalDescuentosParciales)}</strong></div>
    <div class="kpi"><small>Costo Estimado</small><strong>${fmt(r.costoTotalEstimado)}</strong></div>
    <div class="kpi danger"><small>Margen Perdido</small><strong>${fmt(r.margenPerdidoEstimado)}</strong></div>
    
    <div class="kpi"><small>Cuentas Afectadas</small><strong>${r.cuentasAfectadas||0}</strong></div>
    <div class="kpi"><small>Cuentas Abiertas</small><strong>${r.cuentasAbiertasAfectadas||0}</strong></div>
    <div class="kpi"><small>Productos Regalados</small><strong>${r.productosRegalados||0}</strong></div>
    <div class="kpi danger"><small>Sin Autorización</small><strong>${r.cortesiasSinUsuario||0}</strong></div>
    <div class="kpi warn"><small>Sin Motivo</small><strong>${r.cortesiasSinMotivo||0}</strong></div>
  </div>
  
  <div class="grid-rank">
    <div class="card"><div class="card-head"><span class="card-title">Top Productos</span></div>${renderBars(rank.porProducto,'Sin productos')}</div>
    <div class="card"><div class="card-head"><span class="card-title">Top Meseros</span></div>${renderBars(rank.porMesero,'Sin meseros')}</div>
    <div class="card"><div class="card-head"><span class="card-title">Top Autorizadores</span></div>${renderBars(rank.porUsuarioAutorizador,'Sin usuarios')}</div>
    <div class="card"><div class="card-head"><span class="card-title">Por Tipo Auditoría</span></div>${renderBars(rank.porTipoAuditoria,'Sin datos')}</div>
  </div>`;

  if(!det.length){
    html += `<div class="card"><div class="empty">Sin beneficios en el periodo seleccionado</div></div>`;
  } else {
    html += `<div class="card"><div class="card-head"><span class="card-title">Detalle de Beneficios Otorgados</span><span class="badge">${det.length} registros</span></div><div class="table-wrap"><table>
      <thead><tr>
        <th>Fecha</th>
        <th>Origen</th>
        <th>Folio / Cuenta</th>
        <th>Producto</th>
        <th>Cant.</th>
        <th>Precio Reg.</th>
        <th>% Desc</th>
        <th>Imp. Desc</th>
        <th>Costo Est.</th>
        <th>Margen Per.</th>
        <th>Tipo Auditoría</th>
        <th>Estatus</th>
        <th>Usuario Autorizó</th>
        <th>Motivo</th>
      </tr></thead>
      <tbody>${det.map(x=>`<tr>
        <td>${fdt(x.fecha)}</td>
        <td><span style="font-weight:700;color:${x.origenCuenta==='ABIERTA_TEMPORAL'?'#d97706':'#0f9f6e'}">${x.origenCuenta==='ABIERTA_TEMPORAL'?'ABIERTA':'CERRADA'}</span></td>
        <td>${escapeHtml(x.numcheque)}</td>
        <td><strong>${escapeHtml(x.productoNombre)}</strong></td>
        <td class="num">${x.cantidad}</td>
        <td class="num">${fmt(x.ventaOriginal)}</td>
        <td class="num">${x.porcentajeDescuento}%</td>
        <td class="num red">${fmt(x.importeDescuento)}</td>
        <td class="num">${fmt(x.costoTotalEstimado)}</td>
        <td class="num red">${fmt(x.margenPerdidoEstimado)}</td>
        <td>${tagType(x.tipoAuditoria)}</td>
        <td>${tagStatus(x.estatusAuditoria)}</td>
        <td>${escapeHtml(x.usuarioAutorizo)}</td>
        <td>${escapeHtml(x.motivo)}</td>
      </tr>`).join('')}</tbody></table></div></div>`;
  }
  $id('resultado').innerHTML = html;
}

['f-ini','f-fin'].forEach(id => $id(id).addEventListener('change', cargarCatalogos));

(async()=>{try{await _initAuth(); await cargarCatalogos(); await cargar();}catch(e){$id('error').textContent=e.message;$id('error').style.display='block';}})();
</script>
</body>
</html>
