<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Retiros y Depósitos — 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:#eaecf4;
  --text:#111827;--text-2:#4b5563;--text-3:#9ca3af;
  --orange:#f97316;--orange-lt:rgba(249,115,22,.10);--orange-xlt:rgba(249,115,22,.06);
  --green:#10b981;--green-lt:rgba(16,185,129,.10);
  --red:#ef4444;--red-lt:rgba(239,68,68,.10);
  --blue:#2563eb;--blue-lt:rgba(37,99,235,.10);
  --shadow-sm:0 1px 3px rgba(17,24,39,.06);--shadow:0 2px 8px rgba(17,24,39,.08);
  --r:10px;
}
*{margin:0;padding:0;box-sizing:border-box;}
html,body{font-family:'Plus Jakarta Sans',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;font-size:13px;-webkit-font-smoothing:antialiased;}
button,input{font-family:'Plus Jakarta Sans',sans-serif;}
::-webkit-scrollbar{width:4px;}::-webkit-scrollbar-thumb{background:#d1d5db;border-radius:8px;}
@keyframes spin{to{transform:rotate(360deg);}}
@keyframes fadeUp{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}

.topbar{background:var(--surface);border-bottom:1px solid var(--border);height:58px;padding:0 20px;display:flex;align-items:center;gap:12px;box-shadow:var(--shadow-sm);position:sticky;top:0;z-index:20;}
.topbar-icon{width:34px;height:34px;border-radius:9px;flex-shrink:0;background:var(--orange);display:flex;align-items:center;justify-content:center;box-shadow:0 3px 10px rgba(249,115,22,.28);}
.topbar-icon svg{width:16px;height:16px;stroke:#fff;stroke-width:2.2;fill:none;}
.topbar h1{font-size:15px;font-weight:800;color:var(--text);letter-spacing:-.3px;flex:1;}

.container{max-width:1000px;margin:0 auto;padding:18px 18px 40px;}

.filters-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow-sm);padding:14px 18px;margin-bottom:14px;display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap;}
.fg{display:flex;flex-direction:column;gap:3px;}
.fl{font-size:9px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:var(--text-3);}
input[type=date]{padding:7px 10px;border:1px solid var(--border);border-radius:8px;font-size:12px;font-weight:600;color:var(--text);outline:none;transition:.15s;background:var(--surface);}
input:focus{border-color:var(--orange);}
.btn-primary{display:flex;align-items:center;gap:6px;padding:8px 18px;background:var(--orange);color:#fff;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;box-shadow:0 2px 8px rgba(249,115,22,.28);transition:.15s;}
.btn-primary:hover{transform:translateY(-1px);}
.btn-primary svg{width:13px;height:13px;stroke:#fff;stroke-width:2.2;fill:none;}

.stats-row{display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:12px;}
@media(min-width:600px){.stats-row{grid-template-columns:repeat(4,1fr);}}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:14px 16px;box-shadow:var(--shadow-sm);}
.stat-label{font-size:10px;color:var(--text-3);font-weight:600;margin-bottom:4px;text-transform:uppercase;letter-spacing:.06em;}
.stat-val{font-size:20px;font-weight:800;letter-spacing:-.4px;}
.stat-val.orange{color:var(--orange);}
.stat-val.red{color:var(--red);}
.stat-val.green{color:var(--green);}
.stat-val.blue{color:var(--blue);}
.stat-val.dark{color:var(--text);}

.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow-sm);overflow:hidden;margin-bottom:12px;animation:fadeUp .2s ease;}
.card-head{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--border);}
.card-title{font-size:12px;font-weight:800;color:var(--text);}
.card-badge{font-size:11px;font-weight:700;padding:3px 10px;border-radius:20px;background:var(--bg);color:var(--text-3);}

table{width:100%;border-collapse:collapse;font-size:12px;}
th{padding:9px 14px;text-align:left;font-size:10px;font-weight:700;color:var(--text-3);text-transform:uppercase;letter-spacing:.08em;border-bottom:1px solid var(--border);background:var(--bg);}
td{padding:9px 14px;border-bottom:1px solid var(--border);color:var(--text-2);}
tr:last-child td{border-bottom:none;}
tr:hover td{background:var(--bg);}
td.num{text-align:right;font-weight:700;}

.tipo-badge{display:inline-block;padding:2px 9px;border-radius:20px;font-size:10px;font-weight:700;}
.tipo-retiro{background:var(--red-lt);color:var(--red);}
.tipo-deposito{background:var(--green-lt);color:var(--green);}
.tipo-propina{background:var(--blue-lt);color:var(--blue);}
.tipo-otro{background:var(--bg);color:var(--text-3);}

.bar-row{display:flex;align-items:center;gap:10px;padding:8px 16px;border-bottom:1px solid var(--border);}
.bar-row:last-child{border-bottom:none;}
.bar-left{flex:1;display:flex;align-items:center;gap:8px;}
.bar-label{font-size:11.5px;font-weight:700;color:var(--text);min-width:140px;}
.bar-track{flex:1;height:6px;background:var(--bg);border-radius:6px;overflow:hidden;}
.bar-fill{height:100%;border-radius:6px;}
.bar-fill.red{background:var(--red);}
.bar-fill.green{background:var(--green);}
.bar-fill.blue{background:var(--blue);}
.bar-fill.orange{background:var(--orange);}
.bar-val{font-size:11.5px;font-weight:800;min-width:85px;text-align:right;}
.bar-val.red{color:var(--red);}
.bar-val.green{color:var(--green);}
.bar-val.blue{color:var(--blue);}

.empty{padding:32px;text-align:center;color:var(--text-3);font-size:12px;font-weight:600;}
.spinner{width:22px;height:22px;border:2.5px solid var(--border);border-top-color:var(--orange);border-radius:50%;animation:spin .7s linear infinite;margin:28px auto;display:block;}
.error-box{padding:16px 18px;background:var(--red-lt);border-radius:var(--r);color:var(--red);font-size:12px;font-weight:600;margin-bottom:12px;}
.ovwrap{overflow-x:auto;}
.paginacion{display:flex;align-items:center;justify-content:space-between;padding:10px 16px;border-top:1px solid var(--border);background:var(--bg);}
.paginacion span{font-size:11px;color:var(--text-3);font-weight:600;}
.paginacion button{padding:5px 14px;border:1px solid var(--border);border-radius:6px;background:var(--surface);font-size:11px;font-weight:700;cursor:pointer;color:var(--text-2);transition:.15s;}
.paginacion button:disabled{opacity:.4;cursor:not-allowed;}
.paginacion button:not(:disabled):hover{border-color:var(--orange);color:var(--orange);}
</style>
<link rel="stylesheet" href="/css/responsive.css?v=406r"/>
</head>
<body>
<div class="topbar">
  <div class="topbar-icon"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg></div>
  <h1>Retiros y Depósitos de Caja</h1>
</div>

<div class="container">
  <div class="filters-card">
    <div class="fg"><div class="fl">Fecha inicio</div><input type="date" id="f-ini"/></div>
    <div class="fg"><div class="fl">Fecha fin</div><input type="date" id="f-fin"/></div>
    <button class="btn-primary" onclick="cargar(1)">
      <svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
      Consultar
    </button>
  </div>

  <div id="error-box" class="error-box" style="display:none;"></div>
  <div id="spinner" class="spinner" style="display:none;"></div>
  <div id="resultado"></div>
</div>

<script src="/js/arkhon-utils.js"></script>
<script>
var LOCAL_API_KEY = '';
// token via _initAuth() de arkhon-utils.js
// token loaded via _initAuth()
const fmtDate=s=>{if(!s)return'—';try{return new Date(s).toLocaleString('es-MX',{dateStyle:'short',timeStyle:'short'});}catch{return s;}};

let _currentPage=1;
let _totalPages=1;

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


async function cargar(page=1){
  const ini=document.getElementById('f-ini').value;
  const fin=document.getElementById('f-fin').value;
  if(!ini||!fin){showError('Selecciona un período');return;}
  _currentPage=page;
  document.getElementById('error-box').style.display='none';
  document.getElementById('resultado').innerHTML='';
  document.getElementById('spinner').style.display='block';
  try{
    const d=await api(`/retiros-caja?inicio=${ini}&fin=${fin}&page=${page}&pageSize=100`);
    renderResultado(d);
  }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 tipoClass(tl){
  if(tl==='retiro') return 'red';
  if(tl==='deposito') return 'green';
  if(tl==='propina') return 'blue';
  return 'orange';
}

function getTipoMovimiento(mov){
  const tipo = String(mov?.tipo_label || mov?.tipo || mov?.tipomov || '').trim().toLowerCase();
  if (tipo.includes('retiro') || tipo === '1') return 'retiro';
  if (tipo.includes('deposito') || tipo.includes('depósito') || tipo === '2') return 'deposito';
  if (tipo.includes('propina') || tipo === '3') return 'propina';
  return 'otro';
}

function renderResultado(d){
  const res=document.getElementById('resultado');
  if(!d){res.innerHTML='<div class="empty">Sin datos</div>';return;}

  const rs=d.resumen||{};
  const movs=d.movimientos||[];
  const pc=d.porConcepto||[];
  const pu=d.porUsuario||[];
  const pag=d.paginacion||{};
  _totalPages=pag.paginas||1;

  
  const retiros=pc.filter(c=>getTipoMovimiento(c)==='retiro');
  const depositos=pc.filter(c=>getTipoMovimiento(c)==='deposito');
  const totalRetiros=rs.total_retiros||0;
  const totalDepositos=rs.total_depositos||0;
  const totalPropinas=rs.total_propinas||0;
  const saldoNeto = Number(totalDepositos || 0) - Number(totalRetiros || 0) - Number(totalPropinas || 0);

  let html=`
    <div class="stats-row">
      <div class="stat-card"><div class="stat-label">Total retiros</div><div class="stat-val red">${fmt(totalRetiros)}</div></div>
      <div class="stat-card"><div class="stat-label">Total depósitos</div><div class="stat-val green">${fmt(totalDepositos)}</div></div>
      <div class="stat-card"><div class="stat-label">Propinas</div><div class="stat-val blue">${fmt(totalPropinas)}</div></div>
      <div class="stat-card"><div class="stat-label">Saldo neto</div><div class="stat-val ${saldoNeto < 0 ? 'red' : saldoNeto > 0 ? 'green' : 'dark'}">${fmt(saldoNeto)}</div></div>
    </div>`;

  
  if(retiros.length){
    const maxR=Math.max(...retiros.map(c=>c.importe_total||0),1);
    html+=`<div class="card">
      <div class="card-head"><span class="card-title">Retiros por concepto</span><span class="card-badge">${retiros.length} conceptos</span></div>
      ${retiros.map(c=>{const pct=Math.round(((c.importe_total||0)/maxR)*100);return`
        <div class="bar-row">
          <div class="bar-left">
            <div class="bar-label">${c.concepto}</div>
            <div class="bar-track"><div class="bar-fill red" style="width:${pct}%"></div></div>
          </div>
          <span style="font-size:10px;color:var(--text-3);margin-right:6px;">${c.cantidad}</span>
          <div class="bar-val red">${fmt(c.importe_total||0)}</div>
        </div>`}).join('')}
    </div>`;
  }

  
  if(depositos.length){
    const maxD=Math.max(...depositos.map(c=>c.importe_total||0),1);
    html+=`<div class="card">
      <div class="card-head"><span class="card-title">Depósitos por concepto</span><span class="card-badge">${depositos.length} conceptos</span></div>
      ${depositos.map(c=>{const pct=Math.round(((c.importe_total||0)/maxD)*100);return`
        <div class="bar-row">
          <div class="bar-left">
            <div class="bar-label">${c.concepto}</div>
            <div class="bar-track"><div class="bar-fill green" style="width:${pct}%"></div></div>
          </div>
          <span style="font-size:10px;color:var(--text-3);margin-right:6px;">${c.cantidad}</span>
          <div class="bar-val green">${fmt(c.importe_total||0)}</div>
        </div>`}).join('')}
    </div>`;
  }

  
  if(pu.length){
    html+=`<div class="card">
      <div class="card-head"><span class="card-title">Por usuario autorizante</span></div>
      <div class="ovwrap"><table>
        <thead><tr><th>Usuario</th><th>Movimientos</th><th style="text-align:right">Total</th></tr></thead>
        <tbody>${pu.map(u=>`<tr>
          <td style="font-weight:700;color:var(--text)">${u.usuario}</td>
          <td>${u.cantidad}</td>
          <td class="num" style="color:var(--text)">${fmt(u.importe_total||0)}</td>
        </tr>`).join('')}</tbody>
      </table></div>
    </div>`;
  }

  
  html+=`<div class="card">
    <div class="card-head">
      <span class="card-title">Todos los movimientos</span>
      <span class="card-badge">${pag.total||movs.length} registros</span>
    </div>
    <div class="ovwrap"><table>
      <thead><tr><th>Fecha/Hora</th><th>Concepto</th><th>Referencia</th><th>Usuario</th><th>Tipo</th><th style="text-align:right">Importe</th></tr></thead>
      <tbody>${movs.length?movs.map(m=>{
        const tl=getTipoMovimiento(m);
        const tc=tipoClass(tl);
        const colorStyle=tc==='red'?'color:var(--red)':tc==='green'?'color:var(--green)':tc==='blue'?'color:var(--blue)':'';
        return`<tr>
          <td style="font-size:11px;">${fmtDate(m.fecha)}</td>
          <td style="font-weight:600;color:var(--text)">${m.concepto}</td>
          <td>${m.referencia||'—'}</td>
          <td>${m.usuario}</td>
          <td><span class="tipo-badge tipo-${tl}">${tl.charAt(0).toUpperCase()+tl.slice(1)}</span></td>
          <td class="num" style="${colorStyle}">${fmt(m.importe||0)}</td>
        </tr>`;}).join(''):'<tr><td colspan="6" class="empty">Sin movimientos</td></tr>'}
      </tbody>
    </table></div>
    ${_totalPages>1?`<div class="paginacion">
      <span>Página ${_currentPage} de ${_totalPages} (${pag.total} registros)</span>
      <div style="display:flex;gap:6px;">
        <button onclick="cargar(${_currentPage-1})" ${_currentPage<=1?'disabled':''}>← Anterior</button>
        <button onclick="cargar(${_currentPage+1})" ${_currentPage>=_totalPages?'disabled':''}>Siguiente →</button>
      </div>
    </div>`:''}
  </div>`;

  res.innerHTML=html;
}

(async()=>{await _initAuth();cargar(1);})();
</script>
</body>
</html>
