<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Mantenimiento de Ventas — ARKHON</title>
<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);
  --red:#ef4444;--red-lt:rgba(239,68,68,.10);--red-sel:#fef2f2;
  --green:#10b981;--green-lt:rgba(16,185,129,.10);
  --blue:#2563eb;--blue-lt:rgba(37,99,235,.10);
  --shadow-sm:0 1px 3px rgba(17,24,39,.06);--r:10px;--top-h:52px;
}
*{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;padding-bottom:80px;}
button,input,select{font-family:'Plus Jakarta Sans',sans-serif;}
::-webkit-scrollbar{width:4px;height:4px;}::-webkit-scrollbar-thumb{background:#d1d5db;border-radius:8px;}
@keyframes fadeUp{from{opacity:0;transform:translateY(6px);}to{opacity:1;transform:translateY(0);}}
@keyframes spin{to{transform:rotate(360deg);}}

/* TOPBAR */
.topbar{background:var(--surface);border-bottom:1px solid var(--border);height:var(--top-h);padding:0 18px;display:flex;align-items:center;gap:10px;position:sticky;top:0;z-index:20;box-shadow:var(--shadow-sm);}
.topbar-icon{width:32px;height:32px;border-radius:9px;background:var(--red);display:flex;align-items:center;justify-content:center;}
.topbar-icon svg{width:16px;height:16px;stroke:#fff;stroke-width:2.2;fill:none;}
.topbar h1{font-size:14px;font-weight:800;letter-spacing:-.3px;flex:1;}
.warning-pill{display:flex;align-items:center;gap:5px;padding:4px 10px;background:var(--red-lt);border-radius:20px;border:1px solid rgba(239,68,68,.2);}
.warning-pill svg{width:12px;height:12px;stroke:var(--red);stroke-width:2.5;fill:none;}
.warning-pill span{font-size:10px;font-weight:700;color:var(--red);}

/* TABS */
.tabs-bar{background:var(--surface);border-bottom:1px solid var(--border);padding:0 18px;display:flex;gap:0;overflow-x:auto;scrollbar-width:none;}
.tabs-bar::-webkit-scrollbar{display:none;}
.tab-btn{padding:10px 16px;border:none;border-bottom:2px solid transparent;background:transparent;font-size:12px;font-weight:700;color:var(--text-3);cursor:pointer;transition:.15s;display:flex;align-items:center;gap:6px;white-space:nowrap;flex-shrink:0;}
.tab-btn.active{color:var(--orange);border-bottom-color:var(--orange);}
.tab-btn svg{width:13px;height:13px;stroke:currentColor;stroke-width:2.2;fill:none;}

/* CONTAINER */
.container{max-width:1400px;margin:0 auto;padding:16px 18px 40px;}
.section{display:none;animation:fadeUp .2s ease;}
.section.active{display:block;}

/* CARDS */
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow-sm);margin-bottom:14px;}
.card-head{padding:12px 16px;display:flex;align-items:center;gap:10px;border-bottom:1px solid var(--border);flex-wrap:wrap;}
.card-title{font-size:13px;font-weight:800;color:var(--text);}
.card-body{padding:14px 16px;}

/* FILTERS */
.filters{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap;}
.fg{display:flex;flex-direction:column;gap:4px;}
.fl{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--text-3);}
.filters input[type=date],.filters select{padding:7px 10px;border:1px solid var(--border);border-radius:8px;font-size:12px;background:var(--surface);color:var(--text);}

/* BOTONES */
.btn{display:inline-flex;align-items:center;gap:5px;padding:7px 14px;border-radius:8px;font-size:11px;font-weight:700;cursor:pointer;border:none;transition:.15s;}
.btn svg{width:12px;height:12px;stroke:currentColor;stroke-width:2.2;fill:none;}
.btn-orange{background:var(--orange);color:#fff;}
.btn-orange:hover{background:#ea6c0a;}
.btn-red{background:var(--red);color:#fff;}
.btn-red:hover{background:#dc2626;}
.btn-del-row{background:none;border:none;cursor:pointer;color:#ef4444;padding:4px 6px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;transition:background .15s;}
.btn-del-row:hover{background:#fee2e2;}
/* Filtros forma de pago */
.filtros-pago{display:flex;flex-wrap:wrap;gap:6px 16px;padding:8px 0 4px;}
.filtro-chk{display:flex;align-items:center;gap:5px;font-size:12px;color:var(--text-2);cursor:pointer;user-select:none;}
.filtro-chk input{accent-color:var(--orange);width:14px;height:14px;cursor:pointer;}
.filtros-sep{width:100%;height:0;border-top:1px dashed var(--border);margin:4px 0;}
/* Re-foliador */
.refolio-card{max-width:480px;}
.refolio-actual{font-size:28px;font-weight:900;color:var(--orange);letter-spacing:-1px;}
.refolio-label{font-size:10px;font-weight:700;text-transform:uppercase;color:var(--text-3);margin-bottom:4px;}
.refolio-warning{background:#fef3c7;border:1px solid #f59e0b;border-radius:8px;padding:10px 14px;font-size:12px;color:#92400e;margin:12px 0;}
.btn-ghost{background:transparent;color:var(--text-2);border:1px solid var(--border);}
.btn-ghost:hover{background:var(--bg);}
.btn-green{background:var(--green);color:#fff;}
.btn:disabled{opacity:.45;cursor:not-allowed;}

/* STATS ROW */
.stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:14px;}
.stat{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:12px 14px;box-shadow:var(--shadow-sm);}
.stat-label{font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin-bottom:3px;}
.stat-val{font-size:20px;font-weight:800;letter-spacing:-.5px;}
.stat-val.red{color:var(--red);}
.stat-val.orange{color:var(--orange);}
.stat-val.green{color:var(--green);}

/* TABLA PRINCIPAL */
.tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;}
.main-tbl{width:100%;border-collapse:collapse;font-size:11.5px;}
.main-tbl th{background:var(--bg);padding:8px 10px;text-align:left;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);border-bottom:1px solid var(--border);white-space:nowrap;}
.main-tbl td{padding:7px 10px;border-bottom:1px solid var(--border);color:var(--text-2);vertical-align:middle;}
.main-tbl tr:last-child td{border-bottom:none;}
.main-tbl tr.sel td{background:var(--red-sel);color:var(--text);}
.main-tbl tr.sel .folio-num{color:var(--red);font-weight:800;}
.main-tbl tr:hover:not(.sel) td{background:var(--bg);}
.check-col{width:36px;text-align:center;}
.check-col input[type=checkbox]{width:14px;height:14px;cursor:pointer;accent-color:var(--red);}
.folio-num{font-weight:700;color:var(--text);font-family:monospace;}
.badge{display:inline-block;padding:2px 7px;border-radius:10px;font-size:9px;font-weight:700;}
.badge-green{background:var(--green-lt);color:var(--green);}
.badge-red{background:var(--red-lt);color:var(--red);}

/* BARRA DE ACCIONES (fija abajo) */
.action-bar{position:fixed;bottom:0;left:0;right:0;z-index:50;background:var(--surface);border-top:1px solid var(--border);padding:10px 18px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;box-shadow:0 -2px 12px rgba(17,24,39,.07);}
.action-bar-info{flex:1;display:flex;gap:16px;flex-wrap:wrap;}
.action-stat{display:flex;flex-direction:column;gap:1px;}
.action-stat-label{font-size:9px;font-weight:700;text-transform:uppercase;color:var(--text-3);}
.action-stat-val{font-size:13px;font-weight:800;color:var(--text);}
.action-stat-val.red{color:var(--red);}

/* MODAL CONFIRMACIÓN */
.modal-bg{display:none;position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:100;align-items:center;justify-content:center;}
.modal-bg.open{display:flex;}
.modal-box{background:var(--surface);border-radius:14px;padding:28px 28px 22px;max-width:440px;width:calc(100vw - 32px);box-shadow:0 20px 60px rgba(0,0,0,.18);animation:fadeUp .2s ease;}
.modal-icon{width:48px;height:48px;border-radius:14px;background:var(--red-lt);display:flex;align-items:center;justify-content:center;margin-bottom:14px;}
.modal-icon svg{width:22px;height:22px;stroke:var(--red);stroke-width:2.2;fill:none;}
.modal-title{font-size:16px;font-weight:800;margin-bottom:6px;}
.modal-desc{font-size:12px;color:var(--text-2);line-height:1.6;margin-bottom:18px;}
.modal-desc b{color:var(--red);}
.modal-pin{display:flex;flex-direction:column;gap:4px;margin-bottom:16px;}
.modal-pin label{font-size:10px;font-weight:700;text-transform:uppercase;color:var(--text-3);}
.modal-pin input{padding:9px 12px;border:1.5px solid var(--border);border-radius:8px;font-size:14px;font-weight:700;letter-spacing:.15em;text-align:center;}
.modal-pin input:focus{outline:none;border-color:var(--red);}
.modal-actions{display:flex;gap:8px;justify-content:flex-end;}
.modal-error{font-size:11px;color:var(--red);font-weight:600;margin-top:-10px;margin-bottom:12px;display:none;}

/* MODAL FOLIO */
.folio-modal-box{max-width:640px;}
.det-table{width:100%;border-collapse:collapse;font-size:11.5px;margin-top:10px;}
.det-table th{background:var(--bg);padding:7px 10px;text-align:left;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);border-bottom:1px solid var(--border);}
.det-table td{padding:7px 10px;border-bottom:1px solid var(--border);color:var(--text-2);}

/* BITÁCORA */
.bit-tbl{width:100%;border-collapse:collapse;font-size:11.5px;}
.bit-tbl th{background:var(--bg);padding:8px 10px;text-align:left;font-size:9.5px;font-weight:700;text-transform:uppercase;color:var(--text-3);border-bottom:1px solid var(--border);white-space:nowrap;}
.bit-tbl td{padding:7px 10px;border-bottom:1px solid var(--border);color:var(--text-2);}

/* SPINNER */
.spinner{width:28px;height:28px;border:3px solid var(--border);border-top-color:var(--orange);border-radius:50%;animation:spin .7s linear infinite;margin:24px auto;}
.empty{text-align:center;color:var(--text-3);font-size:12px;font-weight:600;padding:32px;}

/* RESPONSIVE */
@media(max-width:600px){
  /* Topbar */
  .topbar{padding:0 10px;gap:6px;}
  .topbar h1{font-size:12px;}
  .warning-pill span{display:none;}
  .warning-pill{padding:4px 6px;}

  /* Tabs */
  .tabs-bar{padding:0 10px;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none;flex-wrap:nowrap;}
  .tabs-bar::-webkit-scrollbar{display:none;}
  .tab-btn{padding:8px 11px;font-size:11px;flex-shrink:0;}

  /* Container */
  .container{padding:10px 10px 80px;}

  /* Stats */
  .stats-row{grid-template-columns:repeat(2,1fr);gap:6px;}
  .stat{padding:10px 12px;}
  .stat-val{font-size:16px;}

  /* Filtros */
  .filters{flex-direction:column;align-items:stretch;gap:6px;}
  .filters input,.filters select,.filters .btn{width:100%;box-sizing:border-box;}

  /* Tabla principal — scroll horizontal, ocultar cols secundarias */
  .tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;}
  .aj-tbl{min-width:520px;}
  .aj-tbl th,.aj-tbl td{padding:5px 7px;font-size:11px;}
  /* Ocultar efectivo/tarjeta/otros en móvil — solo mostrar total */
  .aj-tbl .col-efectivo,.aj-tbl .col-tarjeta,.aj-tbl .col-otros{display:none;}

  /* Barra de acciones */
  .action-bar{flex-direction:column;align-items:stretch;padding:8px 12px;}
  .action-bar-info{gap:8px;}
  .action-stat-val{font-size:12px;}
  #btn-aplicar{width:100%;justify-content:center;}

  /* Bitácora tabla */
  .bit-tbl{min-width:600px;}
  .bit-tbl th,.bit-tbl td{padding:5px 7px;font-size:11px;}

  /* Cards */
  .card-head{padding:10px 12px;flex-wrap:wrap;gap:6px;}
  .card-head .btn{font-size:11px;padding:6px 10px;}

  /* Folio detail */
  .folio-grid{grid-template-columns:1fr !important;}
  .det-tbl{min-width:380px;}

  /* Modal */
  .modal-box{width:calc(100vw - 20px);padding:16px;}
}
@media(max-width:380px){
  .tab-btn{padding:7px 8px;font-size:10px;}
  .stat-val{font-size:14px;}
}
</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"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a1 1 0 011-1h4a1 1 0 011 1v2"/></svg>
  </div>
  <h1>Mantenimiento de Ventas</h1>
  <div class="warning-pill">
    <svg viewBox="0 0 24 24"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
    <span>Operaciones irreversibles</span>
  </div>
</div>

<div class="tabs-bar">
  <button class="tab-btn active" id="tab-ajuste" onclick="showTab('ajuste',this)">
    <svg viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a1 1 0 011-1h4a1 1 0 011 1v2"/></svg>
    Ajuste masivo
  </button>
  <button class="tab-btn" id="tab-folio" onclick="showTab('folio',this)">
    <svg viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
    Modificar 1 folio
  </button>
  <button class="tab-btn" id="tab-refolio" onclick="showTab('refolio',this)">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 102.13-9.36L1 10"/></svg>
    Re-foliador
  </button>
  <button class="tab-btn" id="tab-bitacora" onclick="showTab('bitacora',this)">
    <svg viewBox="0 0 24 24"><path d="M2 3h6a4 4 0 014 4v14a3 3 0 00-3-3H2z"/><path d="M22 3h-6a4 4 0 00-4 4v14a3 3 0 013-3h7z"/></svg>
    Bitácora
  </button>
</div>

<div class="container">

  <!-- ═══ AJUSTE MASIVO ═══ -->
  <div class="section active" id="sec-ajuste">

    <div class="card">
      <div class="card-head">
        <svg viewBox="0 0 24 24" style="width:16px;height:16px;stroke:var(--orange);stroke-width:2.2;fill:none;"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
        <span class="card-title">Filtros de búsqueda</span>
      </div>
      <div class="card-body">
        <div class="filters">
          <div class="fg"><div class="fl">Fecha inicio</div><input type="date" id="aj-ini"/></div>
          <div class="fg"><div class="fl">Fecha fin</div><input type="date" id="aj-fin"/></div>
          <button class="btn btn-orange" onclick="buscarCuentas()">
            <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>
            Buscar cuentas
          </button>
          <button class="btn btn-ghost" onclick="seleccionarTodos()" id="btn-sel-all" style="display:none">Seleccionar todos</button>
          <button class="btn btn-ghost" onclick="deseleccionarTodos()" id="btn-desel-all" style="display:none">Deseleccionar</button>
        </div>
        <div class="filtros-pago">
          <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:var(--text-3);width:100%;margin-bottom:2px">Incluir formas de pago</span>
          <label class="filtro-chk"><input type="checkbox" id="flt-efectivo" checked> Efectivo</label>
          <label class="filtro-chk"><input type="checkbox" id="flt-tarjeta" checked> Tarjeta</label>
          <label class="filtro-chk"><input type="checkbox" id="flt-vales" checked> Vales / Monedero</label>
          <label class="filtro-chk"><input type="checkbox" id="flt-otros" checked> Otros</label>
          <div class="filtros-sep"></div>
          <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:var(--text-3);width:100%;margin-bottom:2px">Tipo de cuenta</span>
          <label class="filtro-chk"><input type="checkbox" id="flt-canceladas" checked> Incluir canceladas</label>
          <label class="filtro-chk"><input type="checkbox" id="flt-cortesias" checked> Incluir cortesías ($0)</label>
          <!-- flt-noreimpresas deshabilitado: columna reimpreso no existe en SR11 -->
          <label class="filtro-chk" style="opacity:.35;pointer-events:none;"><input type="checkbox" id="flt-noreimpresas" disabled> Solo NO reimpresas <span style="font-size:10px">(no disponible)</span></label>
        </div>
      </div>
    </div>

    <div id="aj-stats" style="display:none">
      <div class="stats-row">
        <div class="stat"><div class="stat-label">Total cuentas</div><div class="stat-val" id="st-total">0</div></div>
        <div class="stat"><div class="stat-label">Seleccionadas</div><div class="stat-val orange" id="st-sel">0</div></div>
        <div class="stat"><div class="stat-label">Importe anterior</div><div class="stat-val" id="st-imp-ant">$0.00</div></div>
        <div class="stat"><div class="stat-label">Importe a eliminar</div><div class="stat-val red" id="st-imp-sel">$0.00</div></div>
      </div>
    </div>

    <div class="card">
      <div class="card-head">
        <svg viewBox="0 0 24 24" style="width:16px;height:16px;stroke:var(--text-2);stroke-width:2;fill:none;"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 9h6M9 12h6M9 15h4"/></svg>
        <span class="card-title">Cuentas del período</span>
        <span id="aj-count-label" style="font-size:11px;color:var(--text-3);font-weight:600;margin-left:auto;"></span>
      </div>
      <div class="tbl-wrap">
        <div id="aj-spinner" class="spinner" style="display:none"></div>
        <div id="aj-empty" class="empty">Ingresa un rango de fechas y haz clic en Buscar</div>
        <table class="main-tbl" id="aj-tbl" style="display:none">
          <thead>
            <tr>
              <th class="check-col"><input type="checkbox" id="chk-all" onchange="toggleAll(this)"/></th>
              <th>Folio</th>
              <th>Fecha</th>
              <th>Mesa</th>
              <th>Mesero</th>
              <th>Total</th>
              <th class="col-efectivo">Efectivo</th>
              <th class="col-tarjeta">Tarjeta</th>
              <th class="col-otros">Otros</th>
              <th>Estado</th>
              <th>Eliminar</th>
            </tr>
          </thead>
          <tbody id="aj-tbody"></tbody>
        </table>
      </div>
    </div>

    <div class="action-bar" id="action-bar" style="display:none">
      <div class="action-bar-info">
        <div class="action-stat"><div class="action-stat-label">Cuentas totales</div><div class="action-stat-val" id="ab-total">0</div></div>
        <div class="action-stat"><div class="action-stat-label">A eliminar</div><div class="action-stat-val red" id="ab-sel">0</div></div>
        <div class="action-stat"><div class="action-stat-label">Importe anterior</div><div class="action-stat-val" id="ab-ant">$0.00</div></div>
        <div class="action-stat"><div class="action-stat-label">Importe nuevo</div><div class="action-stat-val green" id="ab-nuevo">$0.00</div></div>
      </div>
      <button class="btn btn-red" id="btn-aplicar" onclick="abrirConfirmacion()" disabled>
        <svg viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6"/></svg>
        APLICAR
      </button>
    </div>

  </div><!-- /sec-ajuste -->

  <!-- ═══ MODIFICAR 1 FOLIO ═══ -->
  <div class="section" id="sec-folio">
    <div class="card">
      <div class="card-head">
        <svg viewBox="0 0 24 24" style="width:16px;height:16px;stroke:var(--orange);stroke-width:2.2;fill:none;"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
        <span class="card-title">Buscar folio</span>
      </div>
      <div class="card-body">
        <div class="filters">
          <div class="fg"><div class="fl">Número de folio</div>
            <input type="number" id="folio-num" placeholder="Ej. 1605" style="padding:7px 10px;border:1px solid var(--border);border-radius:8px;font-size:13px;width:160px;"/>
          </div>
          <button class="btn btn-orange" onclick="buscarFolio()">
            <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>
            Buscar
          </button>
        </div>
      </div>
    </div>
    <div id="folio-spinner" class="spinner" style="display:none"></div>
    <div id="folio-result"></div>
  </div>

  <!-- ═══ RE-FOLIADOR ═══ -->
  <div class="section" id="sec-refolio">
    <div class="card refolio-card">
      <div class="card-head">
        <svg viewBox="0 0 24 24" style="width:16px;height:16px;stroke:var(--orange);stroke-width:2.2;fill:none;"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
        <span class="card-title">Re-foliador</span>
      </div>
      <div class="card-body">
        <div class="refolio-label">Último folio registrado en Soft Restaurant</div>
        <div class="refolio-actual" id="rf-actual">—</div>
        <div style="margin-top:16px;margin-bottom:6px">
          <div class="refolio-label">Reacomodar desde el folio</div>
          <div style="display:flex;gap:8px;align-items:center;margin-top:4px">
            <input type="number" id="rf-nuevo" min="1" style="width:140px;padding:8px 12px;border:1.5px solid var(--border);border-radius:8px;font-size:16px;font-weight:700;" placeholder="Ej: 4001"/>
            <button class="btn btn-orange" onclick="aplicarRefolio()">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15"><polyline points="20 6 9 17 4 12"/></svg>
              Aplicar
            </button>
          </div>
        </div>
        <div class="refolio-warning">
          <b>Importante:</b> Solo puedes re-foliar a un número menor al último folio eliminado. Si existen cuentas con folio mayor al que indiques, la operación será rechazada para evitar duplicados.
        </div>
      </div>
    </div>
  </div>

  <!-- ═══ BITÁCORA ═══ -->
  <div class="section" id="sec-bitacora">
    <div class="card">
      <div class="card-head">
        <span class="card-title">Historial de operaciones</span>
        <button class="btn btn-ghost" style="margin-left:auto" onclick="exportarBitacora()">
          <svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
          Exportar Excel
        </button>
      </div>
      <div class="tbl-wrap">
        <div id="bit-spinner" class="spinner" style="display:none"></div>
        <div id="bit-empty" class="empty">Sin operaciones registradas</div>
        <table class="bit-tbl" id="bit-tbl" style="display:none">
          <thead>
            <tr>
              <th>Fecha proceso</th>
              <th>Fecha inicial venta</th>
              <th>Fecha final venta</th>
              <th>Total cuentas</th>
              <th>Ctas. eliminadas</th>
              <th>Importe anterior</th>
              <th>Diferencia %</th>
              <th>Tipo</th>
              <th>Usuario</th>
              <th style="text-align:center">Folios / Reimprimir</th>
            </tr>
          </thead>
          <tbody id="bit-tbody"></tbody>
        </table>
      </div>
    </div>
  </div>

</div><!-- /container -->

<!-- ═══ MODAL CONFIRMACIÓN ═══ -->
<div class="modal-bg" id="modal-confirm">
  <div class="modal-box">
    <div class="modal-icon">
      <svg viewBox="0 0 24 24"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
    </div>
    <div class="modal-title">Confirmar eliminación</div>
    <div class="modal-desc" id="confirm-desc">
      Estás a punto de eliminar <b id="confirm-n">0</b> folios por un importe total de <b id="confirm-imp">$0.00</b>.<br><br>
      Esta operación es <b>irreversible</b> — los registros desaparecerán de la base de datos de SoftRestaurant.
    </div>
    <div class="modal-pin">
      <label>PIN de administrador para confirmar</label>
      <input type="password" id="confirm-pin" placeholder="••••" maxlength="10" oninput="document.getElementById('modal-error').style.display='none'"/>
    </div>
    <div class="modal-error" id="modal-error">PIN incorrecto</div>
    <div class="modal-actions">
      <button class="btn btn-ghost" onclick="cerrarConfirmacion()">Cancelar</button>
      <button class="btn btn-red" onclick="ejecutarEliminacion()">
        <svg viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6"/></svg>
        Eliminar definitivamente
      </button>
    </div>
  </div>
</div>

<!-- ═══ MODAL DETALLE FOLIO ═══ -->
<div class="modal-bg" id="modal-folio">
  <div class="modal-box folio-modal-box">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;">
      <div class="modal-title" id="modal-folio-title">Folio #0</div>
      <button class="btn btn-ghost" onclick="cerrarModalFolio()" style="padding:5px 10px;">✕</button>
    </div>
    <div id="modal-folio-body"></div>
    <div class="modal-actions" style="margin-top:16px;">
      <button class="btn btn-ghost" onclick="cerrarModalFolio()">Cerrar</button>
      <button class="btn btn-red" id="btn-del-folio" onclick="eliminarFolioIndividual()">
        <svg viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6"/></svg>
        Eliminar este folio
      </button>
    </div>
  </div>
</div>

<script src="/js/arkhon-utils.js"></script>
<script>
var LOCAL_API_KEY = '';
let cuentasData   = [];
let folioActual   = null;
let bitacoraData  = [];


const fmtD = d => { if(!d) return '—'; const dt=new Date(d); return dt.toLocaleDateString('es-MX',{day:'2-digit',month:'2-digit',year:'numeric'})+' '+dt.toLocaleTimeString('es-MX',{hour:'2-digit',minute:'2-digit'}); };


// ── Tabs ──────────────────────────────────────────────────────────────────────
function showTab(name, btn) {
  document.querySelectorAll('.section').forEach(s=>s.classList.remove('active'));
  document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
  document.getElementById('sec-'+name).classList.add('active');
  if(btn) btn.classList.add('active');
  if(name==='bitacora') cargarBitacora();
  if(name==='refolio') cargarUltimoFolio();
}

// ── AJUSTE MASIVO ─────────────────────────────────────────────────────────────
async function buscarCuentas() {
  const ini = document.getElementById('aj-ini').value;
  const fin = document.getElementById('aj-fin').value;
  if(!ini||!fin) return alert('Ingresa rango de fechas');
  if(ini>fin) return alert('La fecha inicio debe ser anterior al fin');

  document.getElementById('aj-spinner').style.display='block';
  document.getElementById('aj-empty').style.display='none';
  document.getElementById('aj-tbl').style.display='none';
  document.getElementById('aj-stats').style.display='none';
  document.getElementById('action-bar').style.display='none';
  document.getElementById('btn-sel-all').style.display='none';
  document.getElementById('btn-desel-all').style.display='none';

  try {
    const filtros = {
      efectivo:     document.getElementById('flt-efectivo').checked,
      tarjeta:      document.getElementById('flt-tarjeta').checked,
      vales:        document.getElementById('flt-vales').checked,
      otros:        document.getElementById('flt-otros').checked,
      canceladas:   document.getElementById('flt-canceladas').checked,
      cortesias:    document.getElementById('flt-cortesias').checked,
      noReimpresas: document.getElementById('flt-noreimpresas').checked,
    };
    const fStr = encodeURIComponent(JSON.stringify(filtros));
    cuentasData = await apiFetch(`/api/mantenimiento/cuentas?inicio=${ini}&fin=${fin}&filtros=${fStr}`);
    renderTabla(cuentasData);
  } catch(e) {
    document.getElementById('aj-empty').textContent = 'Error: '+e.message;
    document.getElementById('aj-empty').style.display='block';
  } finally {
    document.getElementById('aj-spinner').style.display='none';
  }
}

function renderTabla(data) {
  if(!data.length) {
    document.getElementById('aj-empty').textContent='Sin cuentas en este período';
    document.getElementById('aj-empty').style.display='block';
    return;
  }

  const tbody = document.getElementById('aj-tbody');
  tbody.innerHTML = data.map(c => `
    <tr id="row-${c.folio_interno || c.folio}" ${c._sel?'class="sel"':''}>
      <td class="check-col"><input type="checkbox" data-folio="${c.folio_interno || c.folio}" data-visible="${c.folio}" data-total="${c.total}" onchange="toggleFolio(this)" ${c._sel?'checked':''}/></td>
      <td><span class="folio-num">#${c.folio}</span></td>
      <td>${fmtD(c.fecha)}</td>
      <td>${c.mesa||'—'}</td>
      <td>${c.mesero||'—'}</td>
      <td style="font-weight:700">${fmt(c.total)}</td>
      <td class="col-efectivo">${fmt(c.efectivo)}</td>
      <td class="col-tarjeta">${fmt(c.tarjeta)}</td>
      <td class="col-otros">${fmt(c.otros)}</td>
      <td><span class="badge ${c.cancelado?'badge-red':'badge-green'}">${c.cancelado?'Cancelado':'Pagado'}</span></td>
      <td class="check-col">
        <button class="btn-del-row" onclick="confirmarEliminarFolio(${c.folio_interno || c.folio},${c.total},${c.folio})" title="Eliminar folio #${c.folio}">
          <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6"/><path d="M10 11v6M14 11v6"/></svg>
        </button>
      </td>
    </tr>`).join('');

  document.getElementById('aj-tbl').style.display='table';
  document.getElementById('aj-count-label').textContent = data.length+' cuentas encontradas';
  document.getElementById('btn-sel-all').style.display='';
  document.getElementById('btn-desel-all').style.display='';
  document.getElementById('action-bar').style.display='flex';
  document.getElementById('aj-stats').style.display='block';
  actualizarStats();
}

function toggleFolio(chk) {
  const folio = chk.dataset.folio;
  const idx   = cuentasData.findIndex(c=>String(c.folio_interno || c.folio)===String(folio));
  if(idx<0) return;
  cuentasData[idx]._sel = chk.checked;
  // Sincronizar ambos checkboxes de la fila
  const row = document.getElementById('row-'+folio);
  if(row) {
    row.querySelectorAll('input[type=checkbox]').forEach(cb=>cb.checked=chk.checked);
    row.className = chk.checked ? 'sel' : '';
  }
  actualizarStats();
}

function toggleAll(masterChk) {
  cuentasData.forEach(c=>c._sel=masterChk.checked);
  document.querySelectorAll('#aj-tbody input[type=checkbox]').forEach(cb=>{
    cb.checked=masterChk.checked;
    const row=document.getElementById('row-'+cb.dataset.folio);
    if(row) row.className=masterChk.checked?'sel':'';
  });
  actualizarStats();
}
function seleccionarTodos()   { document.getElementById('chk-all').checked=true;  toggleAll(document.getElementById('chk-all')); }
function deseleccionarTodos() { document.getElementById('chk-all').checked=false; toggleAll(document.getElementById('chk-all')); }

function actualizarStats() {
  const sel    = cuentasData.filter(c=>c._sel);
  const total  = cuentasData.length;
  const impAnt = cuentasData.reduce((a,c)=>a+(c.total||0),0);
  const impSel = sel.reduce((a,c)=>a+(c.total||0),0);
  const impNuevo = impAnt - impSel;

  document.getElementById('st-total').textContent  = total;
  document.getElementById('st-sel').textContent    = sel.length;
  document.getElementById('st-imp-ant').textContent= fmt(impAnt);
  document.getElementById('st-imp-sel').textContent= fmt(impSel);

  document.getElementById('ab-total').textContent  = total;
  document.getElementById('ab-sel').textContent    = sel.length;
  document.getElementById('ab-ant').textContent    = fmt(impAnt);
  document.getElementById('ab-nuevo').textContent  = fmt(impNuevo);

  document.getElementById('btn-aplicar').disabled  = sel.length===0;
}

// ── CONFIRMACIÓN ──────────────────────────────────────────────────────────────
function abrirConfirmacion() {
  const sel    = cuentasData.filter(c=>c._sel);
  const impSel = sel.reduce((a,c)=>a+(c.total||0),0);
  document.getElementById('confirm-n').textContent   = sel.length;
  document.getElementById('confirm-imp').textContent = fmt(impSel);
  document.getElementById('confirm-pin').value       = '';
  document.getElementById('modal-error').style.display='none';
  document.getElementById('modal-confirm').classList.add('open');
  setTimeout(()=>document.getElementById('confirm-pin').focus(),100);
}
function cerrarConfirmacion() { document.getElementById('modal-confirm').classList.remove('open'); }

async function ejecutarEliminacion() {
  const pin = document.getElementById('confirm-pin').value;
  if(!pin) { document.getElementById('modal-error').style.display='block'; return; }

  // Verificar PIN contra el servidor
  try {
    const r = await fetch('/api/auth/login-admin', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ pin })
    });
    const d = await r.json();
    if(!d.ok) { document.getElementById('modal-error').style.display='block'; return; }
  } catch(e) {
    document.getElementById('modal-error').textContent='Error al verificar PIN';
    document.getElementById('modal-error').style.display='block'; return;
  }

  const folios = cuentasData.filter(c=>c._sel).map(c=>c.folio_interno || c.folio);
  const ini    = document.getElementById('aj-ini').value;
  const fin    = document.getElementById('aj-fin').value;

  cerrarConfirmacion();
  document.getElementById('aj-spinner').style.display='block';
  document.getElementById('aj-tbl').style.display='none';

  try {
    const res = await apiFetch('/api/mantenimiento/folios', {
      method:'DELETE',
      body: JSON.stringify({ folios, inicio:ini, fin })
    });
    alert(`✓ ${res.eliminados} folios eliminados correctamente.\nImporte eliminado: ${fmt(res.importe_antes)}`);
    // Recargar la tabla
    await buscarCuentas();
  } catch(e) {
    alert('Error: '+e.message);
    document.getElementById('aj-spinner').style.display='none';
    document.getElementById('aj-tbl').style.display='table';
  }
}

// ── MODIFICAR 1 FOLIO ─────────────────────────────────────────────────────────
async function buscarFolio() {
  const num = document.getElementById('folio-num').value;
  if(!num) return alert('Ingresa un número de folio');

  document.getElementById('folio-spinner').style.display='block';
  document.getElementById('folio-result').innerHTML='';

  try {
    const data = await apiFetch('/api/mantenimiento/folio/'+parseInt(num));
    folioActual = data;
    renderDetalleFolio(data);
  } catch(e) {
    document.getElementById('folio-result').innerHTML=`<div class="empty">Error: ${e.message}</div>`;
  } finally {
    document.getElementById('folio-spinner').style.display='none';
  }
}

function renderDetalleFolio(data) {
  const { cheque, detalle, pagos } = data;
  const html = `
    <div class="card">
      <div class="card-head">
        <span class="card-title">Folio #${cheque.folio}</span>
        <span style="font-size:11px;color:var(--text-3);margin-left:auto">${fmtD(cheque.fecha)} · Mesa ${cheque.mesa||'—'} · ${cheque.mesero}</span>
      </div>
      <div class="card-body">
        <div class="stats-row" style="grid-template-columns:repeat(3,1fr)">
          <div class="stat"><div class="stat-label">Total</div><div class="stat-val orange">${fmt(cheque.total)}</div></div>
          <div class="stat"><div class="stat-label">Estado</div><div class="stat-val" style="font-size:14px">${cheque.cancelado?'Cancelado':'Pagado'}</div></div>
          <div class="stat"><div class="stat-label">Turno</div><div class="stat-val" style="font-size:14px">#${cheque.idturno||'—'}</div></div>
        </div>

        <div style="margin-bottom:12px">
          <div class="fl" style="margin-bottom:6px">Productos (${detalle.length})</div>
          <div class="tbl-wrap">
            <table class="det-table">
              <thead><tr><th>Clave</th><th>Descripción</th><th>Cant.</th><th>Precio</th><th>Importe</th></tr></thead>
              <tbody>
                ${detalle.map(d=>`
                  <tr>
                    <td style="font-family:monospace">${d.idproducto}</td>
                    <td>${d.descripcion}</td>
                    <td>${d.cantidad}</td>
                    <td>${fmt(d.precio)}</td>
                    <td style="font-weight:700">${fmt(d.importe)}</td>
                  </tr>`).join('')}
              </tbody>
            </table>
          </div>
        </div>

        <div>
          <div class="fl" style="margin-bottom:6px">Formas de pago</div>
          <div style="display:flex;gap:10px;flex-wrap:wrap">
            ${pagos.map(p=>`<div class="stat" style="padding:8px 12px;min-width:140px"><div class="stat-label">${p.forma_pago}</div><div class="stat-val" style="font-size:16px">${fmt(p.importe)}</div></div>`).join('')}
          </div>
        </div>

        <div style="margin-top:14px;padding-top:12px;border-top:1px solid var(--border);display:flex;justify-content:flex-end;">
          <button class="btn btn-red" onclick="confirmarEliminarFolio(${cheque.folio_interno || cheque.folio},${cheque.total},${cheque.folio})">
            <svg viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6"/></svg>
            Eliminar folio #${cheque.folio}
          </button>
        </div>
      </div>
    </div>`;
  document.getElementById('folio-result').innerHTML = html;
}

async function confirmarEliminarFolio(folio, total, folioVisible) {
  const folioMostrar = folioVisible || folio;
  const pin = prompt(`Folio #${folioMostrar} · ${fmt(total)}\n\nEsta operación es IRREVERSIBLE.\nIngresa tu PIN de administrador para confirmar:`);
  if(!pin) return;

  try {
    const r = await fetch('/api/auth/login-admin', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ pin })
    });
    const d = await r.json();
    if(!d.ok) { alert('PIN incorrecto'); return; }
  } catch(e) { alert('Error al verificar PIN'); return; }

  try {
    const res = await apiFetch('/api/mantenimiento/folios', {
      method:'DELETE',
      body: JSON.stringify({ folios:[folio] })
    });
    alert(`✓ Folio #${folioMostrar} eliminado correctamente.`);
    // Si venimos del tab de ajuste masivo, refrescar la tabla
    if(cuentasData.length) {
      cuentasData = cuentasData.filter(c=>(c.folio_interno || c.folio)!==folio);
      renderTabla(cuentasData);
      actualizarStats();
    }
    // Si venimos de modificar 1 folio, limpiar
    document.getElementById('folio-result').innerHTML='';
    document.getElementById('folio-num').value='';
    folioActual=null;
  } catch(e) { alert('Error: '+e.message); }
}

function cerrarModalFolio() { document.getElementById('modal-folio').classList.remove('open'); }

// ── BITÁCORA ──────────────────────────────────────────────────────────────────
async function cargarBitacora() {
  document.getElementById('bit-spinner').style.display='block';
  document.getElementById('bit-tbl').style.display='none';
  document.getElementById('bit-empty').style.display='none';
  try {
    bitacoraData = await apiFetch('/api/mantenimiento/bitacora');
    if(!bitacoraData.length) { document.getElementById('bit-empty').style.display='block'; return; }
    document.getElementById('bit-tbody').innerHTML = bitacoraData.map(b=>`
      <tr>
        <td>${fmtD(b.fecha_proceso)}</td>
        <td>${fmtD(b.fecha_ini_venta)}</td>
        <td>${fmtD(b.fecha_fin_venta)}</td>
        <td style="text-align:center">${b.total_cuentas}</td>
        <td style="text-align:center;color:var(--red);font-weight:700">${b.cuentas_eliminadas}</td>
        <td>${fmt(b.importe_anterior)}</td>
        <td style="color:var(--red);font-weight:700">${b.diferencia_pct}%</td>
        <td><span class="badge badge-green">${b.tipo_eliminacion}</span></td>
        <td>${b.usuario}</td>
        <td style="text-align:center">
          ${b.folios_json && JSON.parse(b.folios_json||'[]').length
            ? `<button class="btn btn-ghost" style="font-size:11px;padding:3px 8px" onclick='reimprimirFolios(${b.id}, ${b.folios_json})'>
                <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
                ${JSON.parse(b.folios_json||'[]').length} folios
              </button>`
            : '—'
          }
        </td>
      </tr>`).join('');
    document.getElementById('bit-tbl').style.display='table';
  } catch(e) {
    document.getElementById('bit-empty').textContent='Error cargando bitácora: '+e.message;
    document.getElementById('bit-empty').style.display='block';
  } finally { document.getElementById('bit-spinner').style.display='none'; }
}

async function reimprimirFolios(bitacoraId, folios) {
  if(!folios || !folios.length) return;
  const btn = event.target.closest('button');
  const orig = btn.innerHTML;
  btn.disabled = true;
  btn.innerHTML = '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/></svg> Generando...';

  try {
    // Obtener detalle de cada folio en paralelo (máx 10 a la vez)
    const detalles = [];
    for(let i=0; i<folios.length; i+=10) {
      const batch = folios.slice(i, i+10);
      const results = await Promise.all(
        batch.map(f => apiFetch('/api/mantenimiento/folio/'+f).catch(()=>null))
      );
      detalles.push(...results.filter(Boolean));
    }

    if(!detalles.length) { alert('No se encontraron detalles de los folios'); return; }

    // Generar HTML para imprimir
    const html = `<!DOCTYPE html><html><head><meta charset="utf-8">
      <title>Respaldo folios eliminados</title>
      <style>
        body{font-family:monospace;font-size:12px;margin:20px;}
        h2{font-size:14px;border-bottom:1px solid #000;padding-bottom:4px;margin-top:20px;}
        table{width:100%;border-collapse:collapse;margin-bottom:8px;}
        th,td{padding:2px 6px;text-align:left;border-bottom:1px dotted #ccc;}
        th{font-weight:bold;}
        .total{font-weight:bold;font-size:13px;}
        .header{font-size:11px;color:#666;}
        @media print{h2{page-break-before:always;} h2:first-child{page-break-before:avoid;}}
      </style></head><body>
      <div style="text-align:center;margin-bottom:16px">
        <b style="font-size:15px">ARKHON — Respaldo de folios eliminados</b><br>
        <span class="header">Bitácora ID: ${bitacoraId} · Generado: ${new Date().toLocaleString('es-MX')}</span>
      </div>
      ${detalles.map(d => `
        <h2>Folio #${d.cheque.folio} — ${new Date(d.cheque.fecha).toLocaleString('es-MX')} · Mesa ${d.cheque.mesa||'—'} · ${d.cheque.mesero}</h2>
        <table>
          <thead><tr><th>Producto</th><th>Cant.</th><th>Precio</th><th>Importe</th></tr></thead>
          <tbody>
            ${d.detalle.map(p=>`<tr><td>${p.descripcion}</td><td>${p.cantidad}</td><td>$${Number(p.precio).toFixed(2)}</td><td>$${Number(p.importe).toFixed(2)}</td></tr>`).join('')}
          </tbody>
        </table>
        <div>Formas de pago: ${d.pagos.map(p=>`${p.forma_pago} $${Number(p.importe).toFixed(2)}`).join(' · ')}</div>
        <div class="total">TOTAL: $${Number(d.cheque.total).toFixed(2)}</div>
      `).join('')}
      </body></html>`;

    // FIX: usar Blob URL en lugar de document.write para evitar XSS en ventana de impresión
    try {
      const blob = new Blob([html], { type: 'text/html;charset=utf-8' });
      const blobUrl = URL.createObjectURL(blob);
      const win = window.open(blobUrl, '_blank', 'width=800,height=600');
      if (win) {
        win.addEventListener('load', () => { URL.revokeObjectURL(blobUrl); setTimeout(() => win.print(), 300); });
        setTimeout(() => URL.revokeObjectURL(blobUrl), 30000);
      } else {
        URL.revokeObjectURL(blobUrl);
        alert('Permite ventanas emergentes para imprimir.');
      }
    } catch(_) {
      const win = window.open('','_blank','width=800,height=600');
      win.document.write(html);
      win.document.close();
      win.focus();
      setTimeout(()=>win.print(), 500);
    }

  } catch(e) {
    alert('Error generando respaldo: '+e.message);
  } finally {
    btn.disabled = false;
    btn.innerHTML = orig;
  }
}

function exportarBitacora() {
  if(!bitacoraData.length) return;
  const rows = [['Fecha proceso','Fecha ini venta','Fecha fin venta','Total cuentas','Ctas eliminadas','Importe anterior','Diferencia %','Tipo','Usuario']];
  bitacoraData.forEach(b=>rows.push([b.fecha_proceso,b.fecha_ini_venta,b.fecha_fin_venta,b.total_cuentas,b.cuentas_eliminadas,b.importe_anterior,b.diferencia_pct,b.tipo_eliminacion,b.usuario]));
  const csv = rows.map(r=>r.join('\t')).join('\n');
  const a   = document.createElement('a');
  a.href    = 'data:text/tab-separated-values;charset=utf-8,'+encodeURIComponent(csv);
  a.download= `ARKHON-bitacora-mantenimiento-${hoy()}.xls`;
  a.click();
}

// ── Init ──────────────────────────────────────────────────────────────────────
(async () => {
  await _initAuth();
  if (window.self !== window.top) {
    const tb = document.querySelector('.topbar');
    if (tb) tb.style.display = 'none';
  }
  document.getElementById('aj-ini').value = (() => { const d=new Date(); d.setDate(1); const p=n=>String(n).padStart(2,'0'); return `${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())}`; })();
  document.getElementById('aj-fin').value = hoy();
})();

// ── RE-FOLIADOR ───────────────────────────────────────────────────────────────
let _rfActual = null;

async function cargarUltimoFolio() {
  const el = document.getElementById('rf-actual');
  el.textContent = '…';
  try {
    const d = await apiFetch('/api/mantenimiento/refoliador');
    _rfActual = d.ultimofolio;
    el.textContent = _rfActual.toLocaleString();
  } catch(e) {
    el.textContent = 'Error';
    console.error(e);
  }
}

async function aplicarRefolio() {
  const val = parseInt(document.getElementById('rf-nuevo').value);
  if (!val || val < 1) return alert('Ingresa un número de folio válido');
  const pin = prompt('Ingresa tu PIN de administrador para continuar:');
  if (!pin) return;

  // Verificar PIN
  try {
    const vrf = await fetch('/api/auth/login-admin', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ pin })
    });
    const vd = await vrf.json();
    if (!vd.ok) return alert('PIN incorrecto');
  } catch(e) {
    return alert('Error verificando PIN: ' + e.message);
  }

  if (!confirm(`¿Confirmas reacomodar automáticamente los folios visibles desde el número ${val}?\n\nArkhon ordenará las cuentas por cierre y folio interno, actualizará numcheque y dejará el consecutivo listo para el siguiente folio.\n\nEsta acción es irreversible.`)) return;

  try {
    const data = await apiFetch('/api/mantenimiento/refoliador', {
      method: 'POST',
      body: JSON.stringify({ folioNuevo: val })
    });
    const final = data.folioFinal || val;
    _rfActual = final;
    document.getElementById('rf-actual').textContent = final.toLocaleString();
    document.getElementById('rf-nuevo').value = '';
    alert(`Re-foliador aplicado correctamente.\nCuentas re-foliadas: ${data.cuentasRefoliadas || 0}\nRango aplicado: ${data.folioInicial || val} - ${final}\nSiguiente folio esperado: ${final + 1}`);
  } catch(e) {
    alert('Error: ' + e.message);
  }
}
</script>
</body>
</html>
