<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Compras — 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);
  --red:#ef4444;--red-lt:rgba(239,68,68,.10);
  --green:#10b981;--green-lt:rgba(16,185,129,.10);
  --blue:#2563eb;--blue-lt:rgba(37,99,235,.10);
  --yellow:#f59e0b;--yellow-lt:rgba(245,158,11,.10);
  
  --shadow-sm:0 1px 3px rgba(17,24,39,.06);--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,select,textarea{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(6px);}to{opacity:1;transform:translateY(0);}}
@keyframes fadeIn{from{opacity:0;}to{opacity:1;}}

/* TOPBAR */
.topbar{background:var(--surface);border-bottom:1px solid var(--border);height:52px;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(--orange);display:flex;align-items:center;justify-content:center;}
.topbar h1{font-size:14px;font-weight:800;letter-spacing:-.3px;flex:1;}
.topbar-btn{display:flex;align-items:center;gap:5px;padding:6px 12px;border:1px solid var(--border);border-radius:8px;background:var(--surface);color:var(--text-2);font-size:11px;font-weight:700;cursor:pointer;transition:.15s;text-decoration:none;}
.topbar-btn:hover{background:var(--bg);}
.btn-primary{background:var(--orange);color:#fff;border:none;box-shadow:0 2px 8px rgba(249,115,22,.28);}
.btn-primary:hover{opacity:.9;transform:translateY(-1px);}

/* TABS */
.tabs-bar{background:var(--surface);border-bottom:1px solid var(--border);padding:0 18px;display:flex;gap:0;}
.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;}
.tab-btn.active{color:var(--orange);border-bottom-color:var(--orange);}
.tab-btn:hover:not(.active){color:var(--text);}

/* LAYOUT */
.content{padding:16px 18px;max-width:1200px;}
.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);overflow:hidden;margin-bottom:14px;}
.card-head{padding:12px 16px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px;}
.card-title{font-size:13px;font-weight:800;flex:1;}
.card-body{padding:16px;}

/* FORMULARIO */
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;}
.form-grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;}
.form-group{display:flex;flex-direction:column;gap:4px;}
.form-group label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--text-3);}
input,select,textarea{width:100%;padding:8px 10px;border:1px solid var(--border);border-radius:8px;font-size:12px;color:var(--text);background:var(--surface);transition:.15s;outline:none;}
input:focus,select:focus{border-color:var(--orange);box-shadow:0 0 0 3px var(--orange-lt);}
input[readonly]{background:var(--bg);color:var(--text-3);}

/* BOTONES */
.btn{display:inline-flex;align-items:center;gap:5px;padding:7px 14px;border-radius:8px;font-size:11px;font-weight:700;cursor:pointer;transition:.15s;border:none;}
.btn-orange{background:var(--orange);color:#fff;box-shadow:0 2px 8px rgba(249,115,22,.25);}
.btn-orange:hover{opacity:.9;transform:translateY(-1px);}
.btn-outline{background:transparent;border:1px solid var(--border);color:var(--text-2);}
.btn-outline:hover{background:var(--bg);}
.btn-red{background:var(--red-lt);color:var(--red);border:1px solid rgba(239,68,68,.2);}
.btn-red:hover{background:var(--red);color:#fff;}
.btn-green{background:var(--green-lt);color:var(--green);border:1px solid rgba(16,185,129,.2);}
.btn-green:hover{background:var(--green);color:#fff;}
.btn-sm{padding:4px 10px;font-size:10px;}
.btn:disabled{opacity:.5;cursor:not-allowed;transform:none!important;}

/* TABLA LÍNEAS */
.lineas-wrap{overflow-x:auto;}
table.lineas-tbl{width:100%;border-collapse:collapse;}
table.lineas-tbl thead th{padding:7px 10px;text-align:left;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--text-3);background:var(--bg);border-bottom:1px solid var(--border);}
table.lineas-tbl tbody tr{border-bottom:1px solid var(--border);}
table.lineas-tbl tbody tr:hover{background:var(--bg);}
table.lineas-tbl tbody td{padding:6px 8px;font-size:12px;vertical-align:middle;}
table.lineas-tbl tfoot td{padding:8px 10px;font-size:11px;font-weight:700;background:var(--bg);border-top:2px solid var(--border);}
table.lineas-tbl td input,table.lineas-tbl td select{padding:5px 8px;font-size:11px;}
.td-r{text-align:right;}
.td-del{width:32px;text-align:center;}

/* TABLA DE DATOS */
table.data-tbl{width:100%;border-collapse:collapse;}
table.data-tbl thead th{padding:9px 12px;text-align:left;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--text-3);background:var(--bg);border-bottom:1px solid var(--border);}
table.data-tbl tbody tr{border-bottom:1px solid var(--border);transition:.1s;cursor:pointer;}
table.data-tbl tbody tr:hover{background:var(--bg);}
table.data-tbl tbody td{padding:9px 12px;font-size:12px;color:var(--text-2);}
table.data-tbl tbody td.r{text-align:right;font-weight:700;color:var(--text);}
table.data-tbl tbody td.bold{font-weight:700;color:var(--text);}

/* BADGES */
.badge{display:inline-flex;align-items:center;padding:2px 8px;border-radius:20px;font-size:10px;font-weight:700;}
.badge-green{background:var(--green-lt);color:var(--green);}
.badge-red{background:var(--red-lt);color:var(--red);}
.badge-yellow{background:var(--yellow-lt);color:var(--yellow);}
.badge-blue{background:var(--orange-lt);color:var(--blue);}

/* TOTALES */
.totales-box{background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:12px 16px;}
.totales-row{display:flex;justify-content:space-between;align-items:center;padding:3px 0;}
.totales-row.total{border-top:1px solid var(--border);margin-top:4px;padding-top:8px;}
.totales-row.total .t-label{font-size:14px;font-weight:800;}
.totales-row.total .t-val{font-size:18px;font-weight:800;color:var(--orange);}
.t-label{font-size:11px;color:var(--text-3);font-weight:600;}
.t-val{font-size:12px;font-weight:700;color:var(--text);}

/* CONCILIACION */
.conc-diff-pos{color:var(--green);font-weight:700;}
.conc-diff-neg{color:var(--red);font-weight:700;}
.conc-diff-zero{color:var(--text-3);}
.conc-input{width:90px;}

/* HISTORIAL DETALLE */
.detalle-row{background:var(--bg);border-top:1px solid var(--border);padding:10px 16px;}
.detalle-tbl{width:100%;border-collapse:collapse;font-size:11px;}
.detalle-tbl td,.detalle-tbl th{padding:5px 10px;}
.detalle-tbl th{font-weight:700;color:var(--text-3);text-align:left;font-size:10px;text-transform:uppercase;}

/* MODAL */
.modal-overlay{display:none;position:fixed;inset:0;background:rgba(17,24,39,.5);z-index:100;align-items:center;justify-content:center;animation:fadeIn .15s;}
.modal-overlay.open{display:flex;}
.modal{background:var(--surface);border-radius:14px;padding:24px;width:460px;max-width:95vw;box-shadow:0 20px 60px rgba(17,24,39,.18);animation:fadeUp .2s ease;}
.modal h3{font-size:15px;font-weight:800;margin-bottom:16px;}
.modal-footer{display:flex;gap:8px;justify-content:flex-end;margin-top:20px;}

/* FILTROS */
.filtros-bar{display:flex;gap:8px;align-items:flex-end;flex-wrap:wrap;margin-bottom:14px;}
.filtros-bar .form-group{min-width:140px;}

/* EMPTY */
.empty{text-align:center;padding:40px;color:var(--text-3);font-size:12px;}

/* SPIN */
.spin{display:inline-block;width:14px;height:14px;border:2px solid var(--border);border-top-color:var(--orange);border-radius:50%;animation:spin .7s linear infinite;}

/* SEPARADOR SECCIÓN */
.sec-title{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 10px;}

/* ═══════════════════════════════════════════════════════
   RESPONSIVE COMPRAS — móvil primero
═══════════════════════════════════════════════════════ */

@media(max-width:600px){
  /* Topbar */
  .topbar{padding:0 10px;gap:6px;}
  .topbar h1{font-size:12px;}
  .topbar-btn span{display:none;}
  .topbar-btn{padding:6px 9px;min-width:32px;justify-content:center;}

  /* Tabs — scroll horizontal */
  .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 60px;}

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

  /* Form filas — 1 columna en móvil */
  .form-grid-2{grid-template-columns:1fr !important;}
  .form-row{flex-direction:column;gap:6px;}
  .form-group{width:100%;}
  label{font-size:10px;}
  input,select{font-size:13px;padding:8px 10px;}

  /* Tabla de líneas de compra — scroll horizontal */
  .lineas-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;}
  .lineas-tbl{min-width:640px;}
  .lineas-tbl th,.lineas-tbl td{padding:5px 7px;font-size:11px;}

  /* Totales — compacto */
  .totales-box{padding:10px 12px;}
  .total-row{font-size:12px;}
  .total-final{font-size:16px;}

  /* Historial tabla — scroll */
  .hist-tbl{min-width:520px;}
  .hist-wrap{overflow-x:auto;}
  .hist-tbl th,.hist-tbl td{padding:5px 7px;font-size:11px;}

  /* Conciliación tabla — scroll */
  .conc-tbl{min-width:480px;}
  .conc-wrap{overflow-x:auto;}

  /* Proveedores tabla — scroll */
  .prov-tbl{min-width:500px;}
  .prov-wrap{overflow-x:auto;}

  /* Botón guardar — full width */
  .btn-guardar{width:100%;justify-content:center;}

  /* Alertas / mensajes */
  .msg-box{font-size:11px;padding:8px 12px;}
}

@media(max-width:380px){
  .tab-btn{padding:7px 8px;font-size:10px;}
  .lineas-tbl{min-width:560px;}
}
</style>
<link rel="stylesheet" href="/css/responsive.css?v=406r"/>
</head>
<body>

<!-- TOPBAR -->
<div class="topbar">
  <div class="topbar-icon">
    <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
      <path d="M6 2 3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 01-8 0"/>
    </svg>
  </div>
  <h1>Compras e Inventario</h1>
  <a href="/" class="topbar-btn">← Dashboard</a>
  <a href="/inventario" class="topbar-btn">Almacén</a>
</div>

<!-- TABS -->
<div class="tabs-bar">
  <button class="tab-btn active" onclick="showTab('nueva',this)">
       <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M6 2 3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 01-8 0"/></svg>
       Nueva compra</button>
  <button class="tab-btn" onclick="showTab('historial',this)">
       <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><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"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
       Historial</button>
  <button class="tab-btn" onclick="showTab('conciliacion',this)">
       <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><line x1="12" y1="20" x2="12" y2="10"/><line x1="18" y1="20" x2="18" y2="4"/><line x1="6" y1="20" x2="6" y2="16"/></svg>
       Conciliación</button>
  <button class="tab-btn" onclick="showTab('proveedores',this)">
       <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v16"/></svg>
       Proveedores</button>
</div>

<div class="content">

<!-- ═══ TAB: NUEVA COMPRA ══════════════════════════════════════════════════════ -->
<div class="section active" id="sec-nueva">

  <div class="card">
    <div class="card-head">
      <span style="width:28px;height:28px;border-radius:8px;background:var(--orange-lt);display:flex;align-items:center;justify-content:center;flex-shrink:0"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--orange)" stroke-width="2.2" stroke-linecap="round"><path d="M6 2 3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 01-8 0"/></svg></span>
      <span class="card-title">Registrar compra</span>
      <span id="folio-preview" style="font-size:11px;color:var(--text-3);font-weight:600;"></span>
    </div>
    <div class="card-body">

      <!-- Cabecera -->
      <div class="form-grid" style="margin-bottom:12px;">
        <div class="form-group">
          <label>Proveedor *</label>
          <select id="inp-proveedor">
            <option value="">Cargando...</option>
          </select>
        </div>
        <div class="form-group">
          <label>Referencia / Nota</label>
          <input type="text" id="inp-referencia" placeholder="Opcional" maxlength="50"/>
        </div>
      </div>
      <div class="form-grid-3" style="margin-bottom:16px;">
        <div class="form-group">
          <label>Fecha de aplicación *</label>
          <input type="date" id="inp-fechaapp"/>
        </div>
        <div class="form-group">
          <label>Fecha factura</label>
          <input type="date" id="inp-fechafact"/>
        </div>
        <div class="form-group">
          <label>Folio factura</label>
          <input type="text" id="inp-foliofact" placeholder="Ej: A-12345" maxlength="15"/>
        </div>
      </div>

      <!-- Líneas -->
      <div class="sec-title">Líneas de compra</div>
      <div class="lineas-wrap" style="margin-bottom:10px;">
        <table class="lineas-tbl" id="tbl-lineas">
          <thead>
            <tr>
              <th style="min-width:200px">Presentación / Insumo</th>
              <th style="width:100px">Almacén</th>
              <th style="width:85px">Cantidad</th>
              <th style="width:100px">Costo unit.</th>
              <th style="width:60px">IVA %</th>
              <th style="width:100px" class="td-r">Subtotal</th>
              <th style="width:80px" class="td-r">Total c/IVA</th>
              <th class="td-del"></th>
            </tr>
          </thead>
          <tbody id="lineas-body">
            <!-- filas dinámicas -->
          </tbody>
          <tfoot>
            <tr>
              <td colspan="5" style="text-align:right;color:var(--text-3);">Subtotal sin IVA</td>
              <td class="td-r" id="foot-subtotal">$0.00</td>
              <td></td><td></td>
            </tr>
            <tr>
              <td colspan="5" style="text-align:right;color:var(--text-3);">IVA</td>
              <td class="td-r" id="foot-iva">$0.00</td>
              <td></td><td></td>
            </tr>
            <tr>
              <td colspan="5" style="text-align:right;font-size:13px;font-weight:800;">TOTAL</td>
              <td class="td-r" style="font-size:14px;font-weight:800;color:var(--orange);" id="foot-total">$0.00</td>
              <td></td><td></td>
            </tr>
          </tfoot>
        </table>
      </div>

      <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;">
        <button class="btn btn-outline" onclick="agregarLinea()">Agregar línea</button>
        <div style="display:flex;gap:8px;">
          <button class="btn btn-outline" onclick="limpiarForm()">Limpiar</button>
          <button class="btn btn-orange" id="btn-guardar" onclick="guardarCompra()">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17,21 17,13 7,13 7,21"/><polyline points="7,3 7,8 15,8"/></svg>
            Guardar compra en SR
          </button>
        </div>
      </div>
    </div>
  </div>

  <div id="msg-nueva"></div>
</div>

<!-- ═══ TAB: HISTORIAL ════════════════════════════════════════════════════════ -->
<div class="section" id="sec-historial">

  <div class="filtros-bar">
    <div class="form-group">
      <label>Desde</label>
      <input type="date" id="h-desde"/>
    </div>
    <div class="form-group">
      <label>Hasta</label>
      <input type="date" id="h-hasta"/>
    </div>
    <div class="form-group">
      <label>Proveedor</label>
      <select id="h-proveedor" style="min-width:160px;">
        <option value="">Todos</option>
      </select>
    </div>
    <button class="btn btn-orange" onclick="cargarHistorial()">Buscar</button>
  </div>

  <div class="card">
    <div class="card-head">
      <span class="card-title">Compras registradas</span>
      <span id="hist-count" style="font-size:11px;color:var(--text-3);font-weight:600;"></span>
    </div>
    <div id="hist-wrap">
      <div class="empty">Selecciona un rango de fechas y presiona Buscar</div>
    </div>
  </div>
</div>

<!-- ═══ TAB: CONCILIACIÓN ════════════════════════════════════════════════════ -->
<div class="section" id="sec-conciliacion">

  <div class="card" style="margin-bottom:14px;">
    <div class="card-head">
      <span style="width:28px;height:28px;border-radius:8px;background:var(--orange-lt);display:flex;align-items:center;justify-content:center;flex-shrink:0"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--orange)" stroke-width="2.2" stroke-linecap="round"><line x1="12" y1="20" x2="12" y2="10"/><line x1="18" y1="20" x2="18" y2="4"/><line x1="6" y1="20" x2="6" y2="16"/></svg></span>
      <span class="card-title">Conciliación de inventario físico</span>
    </div>
    <div class="card-body">
      <div style="display:flex;gap:12px;align-items:flex-end;margin-bottom:14px;">
        <div class="form-group" style="min-width:180px;">
          <label>Almacén</label>
          <select id="conc-almacen">
            <option value="">Todos los almacenes</option>
          </select>
        </div>
        <button class="btn btn-outline" onclick="cargarStock()">Cargar stock actual</button>
      </div>
      <div style="background:var(--yellow-lt);border:1px solid rgba(245,158,11,.3);border-radius:8px;padding:10px 14px;font-size:11px;color:#92400e;margin-bottom:14px;">
        <strong>Importante:</strong> El conteo físico que ingreses se comparará con el stock calculado por SR.
        Si hay diferencia, se registrará un ajuste <strong>(EDA)</strong> en movtosalmacen de SoftRestaurant.
        Solo aplica diferencias distintas de cero.
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-head">
      <span class="card-title">Stock vs. Conteo físico</span>
      <span id="conc-resumen" style="font-size:11px;color:var(--text-3);font-weight:600;"></span>
      <button class="btn btn-green" id="btn-conciliar" onclick="guardarConciliacion()" style="display:none;">
        Aplicar ajustes a SR
      </button>
    </div>
    <div id="conc-wrap">
      <div class="empty">Selecciona un almacén y presiona "Cargar stock actual"</div>
    </div>
  </div>
</div>

<!-- ═══ TAB: PROVEEDORES ═════════════════════════════════════════════════════ -->
<div class="section" id="sec-proveedores">

  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;">
    <div style="font-size:13px;font-weight:800;">Proveedores registrados en SR</div>
    <button class="btn btn-orange" onclick="abrirModalProveedor()">+ Nuevo proveedor</button>
  </div>

  <div class="card">
    <div id="prov-wrap">
      <div class="empty"><div class="spin"></div></div>
    </div>
  </div>
</div>

</div><!-- /content -->

<!-- ═══ MODAL PROVEEDOR ═══════════════════════════════════════════════════════ -->
<div class="modal-overlay" id="modal-proveedor">
  <div class="modal">
    <h3>Nuevo proveedor</h3>
    <div class="form-grid" style="margin-bottom:10px;">
      <div class="form-group">
        <label>Clave * (máx 15 car.)</label>
        <input type="text" id="mp-id" placeholder="Ej: PROV001" maxlength="15" style="text-transform:uppercase;"/>
      </div>
      <div class="form-group">
        <label>Nombre *</label>
        <input type="text" id="mp-nombre" placeholder="Nombre comercial" maxlength="50"/>
      </div>
    </div>
    <div class="form-group" style="margin-bottom:10px;">
      <label>Razón social</label>
      <input type="text" id="mp-rs" placeholder="Razón social (opcional)" maxlength="100"/>
    </div>
    <div class="form-grid" style="margin-bottom:10px;">
      <div class="form-group">
        <label>RFC</label>
        <input type="text" id="mp-rfc" placeholder="RFC" maxlength="15" style="text-transform:uppercase;"/>
      </div>
      <div class="form-group">
        <label>Teléfono</label>
        <input type="text" id="mp-tel" placeholder="Teléfono" maxlength="20"/>
      </div>
    </div>
    <div class="form-group" style="margin-bottom:4px;">
      <label>Email</label>
      <input type="email" id="mp-email" placeholder="correo@proveedor.com" maxlength="150"/>
    </div>
    <div id="mp-error" style="color:var(--red);font-size:11px;margin-top:8px;display:none;"></div>
    <div class="modal-footer">
      <button class="btn btn-outline" onclick="cerrarModalProveedor()">Cancelar</button>
      <button class="btn btn-orange" onclick="guardarProveedor()">Guardar en SR</button>
    </div>
  </div>
</div>

<!-- ═══ MODAL DETALLE COMPRA ════════════════════════════════════════════════ -->
<div class="modal-overlay" id="modal-detalle">
  <div class="modal" style="width:640px;">
    <h3 id="det-titulo">Detalle de compra</h3>
    <div id="det-body"></div>
    <div class="modal-footer">
      <button class="btn btn-outline" onclick="cerrarModalDetalle()">Cerrar</button>
      <button class="btn btn-red" id="btn-cancelar-compra" onclick="confirmarCancelar()">Cancelar compra</button>
    </div>
  </div>
</div>

<script src="/js/arkhon-utils.js"></script>
<script>
// ─── Estado global ────────────────────────────────────────────────────────────
let presentaciones = [];
let almacenes      = [];
let proveedores    = [];
let lineasCount    = 0;
let detalleActual  = null;  // compra abierta en modal

var LOCAL_API_KEY = '';

const fmtN = v => Number(v||0).toLocaleString('es-MX',{minimumFractionDigits:4,maximumFractionDigits:4});
const fechaTxt = v => {
  const d = v ? new Date(v) : null;
  return d && !Number.isNaN(d.getTime()) ? d.toLocaleDateString('es-MX') : '—';
};

// ─── 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==='historial')     cargarHistorial();
  if(name==='proveedores')   cargarProveedores();
  if(name==='conciliacion')  cargarAlmacenesConciliacion();
}

// ─── Init ─────────────────────────────────────────────────────────────────────
async function init() {
  await _initAuth();
  // Ocultar topbar si está dentro de un iframe
  if (window.self !== window.top) {
    const tb = document.querySelector('.topbar');
    if (tb) tb.style.display = 'none';
  }
  // Fecha hoy en inputs
  const hoy = new Date().toLocaleDateString('sv-SE');
  document.getElementById('inp-fechaapp').value = hoy;
  document.getElementById('inp-fechafact').value = hoy;
  document.getElementById('h-desde').value = hoy;
  document.getElementById('h-hasta').value = hoy;

  // Cargar catálogos en paralelo
  const [pres, alms, provs] = await Promise.all([
    apiFetch('/api/compras/presentaciones').catch(()=>[]),
    apiFetch('/api/compras/almacenes').catch(()=>[]),
    apiFetch('/api/compras/proveedores').catch(()=>[]),
  ]);

  presentaciones = Array.isArray(pres) ? pres : [];
  almacenes      = Array.isArray(alms) ? alms : [];
  proveedores    = Array.isArray(provs) ? provs : [];

  // Poblar selector de proveedor
  const selProv = document.getElementById('inp-proveedor');
  selProv.innerHTML = '<option value="">— Selecciona proveedor —</option>' +
    proveedores.map(p=>`<option value="${p.idproveedor}">${p.nombre} (${p.idproveedor})</option>`).join('');

  // Poblar selector historial
  const hProv = document.getElementById('h-proveedor');
  hProv.innerHTML = '<option value="">Todos</option>' +
    proveedores.map(p=>`<option value="${p.idproveedor}">${p.nombre}</option>`).join('');

  // Agregar primera línea
  agregarLinea();
}

// ─── Nueva compra — líneas ────────────────────────────────────────────────────
function agregarLinea() {
  const id = ++lineasCount;
  const tbody = document.getElementById('lineas-body');
  const tr = document.createElement('tr');
  tr.id = 'linea-'+id;
  tr.dataset.id = id;

  const optsPres = presentaciones.map(p=>
    `<option value="${p.idinsumospresentaciones}" data-costo="${p.ultimo_costo||0}" data-iva="${Number(p.impuesto1||0)}">
      ${p.insumo} — ${p.presentacion} (${p.unidad})
    </option>`
  ).join('');

  const optsAlm = almacenes.map(a=>
    `<option value="${a.idalmacen}">${a.nombre||a.idalmacen}</option>`
  ).join('');

  tr.innerHTML = `
    <td><select class="l-pres" onchange="onPresChange(${id})"><option value="">— Seleccionar —</option>${optsPres}</select></td>
    <td><select class="l-alm">${optsAlm}</select></td>
    <td><input type="number" class="l-cant" value="1" min="0.0001" step="0.0001" oninput="recalcular()"/></td>
    <td><input type="number" class="l-costo" value="0" min="0" step="0.01" oninput="recalcular()"/></td>
    <td>
      <select class="l-iva" onchange="recalcular()">
        <option value="16">16%</option>
        <option value="0">0%</option>
      </select>
    </td>
    <td class="td-r l-sub">$0.00</td>
    <td class="td-r l-tot">$0.00</td>
    <td class="td-del"><button class="btn btn-sm btn-red" onclick="quitarLinea(${id})" title="Quitar"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button></td>
  `;
  tbody.appendChild(tr);
  recalcular();
}

function onPresChange(id) {
  const tr = document.getElementById('linea-'+id);
  const sel = tr.querySelector('.l-pres');
  const opt = sel.options[sel.selectedIndex];
  const costo = parseFloat(opt.dataset.costo||0);
  const iva = parseFloat(opt.dataset.iva||0);
  tr.querySelector('.l-costo').value = costo.toFixed(4);
  const ivaSel = tr.querySelector('.l-iva');
  if(ivaSel) ivaSel.value = iva > 0 ? '16' : '0';
  recalcular();
}

function quitarLinea(id) {
  const tr = document.getElementById('linea-'+id);
  if(tr) tr.remove();
  recalcular();
}

function recalcular() {
  let subtotal = 0, iva = 0;
  document.querySelectorAll('#lineas-body tr').forEach(tr=>{
    const cant  = parseFloat(tr.querySelector('.l-cant')?.value||0);
    const costo = parseFloat(tr.querySelector('.l-costo')?.value||0);
    const ivaPct= parseFloat(tr.querySelector('.l-iva')?.value||0)/100;
    const sub   = cant*costo;
    const tot   = sub*(1+ivaPct);
    subtotal += sub;
    iva      += sub*ivaPct;
    if(tr.querySelector('.l-sub')) tr.querySelector('.l-sub').textContent = fmt(sub);
    if(tr.querySelector('.l-tot')) tr.querySelector('.l-tot').textContent = fmt(tot);
  });
  document.getElementById('foot-subtotal').textContent = fmt(subtotal);
  document.getElementById('foot-iva').textContent      = fmt(iva);
  document.getElementById('foot-total').textContent    = fmt(subtotal+iva);
}

function limpiarForm() {
  document.getElementById('inp-proveedor').selectedIndex=0;
  document.getElementById('inp-referencia').value='';
  document.getElementById('inp-foliofact').value='';
  const hoy=new Date().toLocaleDateString('sv-SE');
  document.getElementById('inp-fechaapp').value=hoy;
  document.getElementById('inp-fechafact').value=hoy;
  document.getElementById('lineas-body').innerHTML='';
  lineasCount=0;
  agregarLinea();
  showMsg('nueva','','');
}

function showMsg(tab, tipo, texto) {
  const el = document.getElementById('msg-'+tab);
  if(!el) return;
  if(!texto){el.innerHTML='';return;}
  const bg = tipo==='ok'?'var(--green-lt)':tipo==='err'?'var(--red-lt)':'var(--orange-lt)';
  const color = tipo==='ok'?'var(--green)':tipo==='err'?'var(--red)':'var(--blue)';
  el.innerHTML = `<div style="background:${bg};border-radius:8px;padding:10px 14px;font-size:12px;color:${color};font-weight:600;margin-top:8px;">${texto}</div>`;
}

async function guardarCompra() {
  const idproveedor   = document.getElementById('inp-proveedor').value;
  const fechaaplicacion = document.getElementById('inp-fechaapp').value;
  const fechafactura  = document.getElementById('inp-fechafact').value;
  const foliofactura  = document.getElementById('inp-foliofact').value;
  const referencia    = document.getElementById('inp-referencia').value;

  if(!idproveedor) { showMsg('nueva','err','Selecciona un proveedor'); return; }
  if(!fechaaplicacion) { showMsg('nueva','err','Fecha de aplicación requerida'); return; }

  const lineas = [];
  let valido = true;
  document.querySelectorAll('#lineas-body tr').forEach(tr=>{
    const ipid  = tr.querySelector('.l-pres')?.value;
    const cant  = parseFloat(tr.querySelector('.l-cant')?.value||0);
    const costo = parseFloat(tr.querySelector('.l-costo')?.value||0);
    const iva   = parseFloat(tr.querySelector('.l-iva')?.value||0);
    const alm   = tr.querySelector('.l-alm')?.value;
    if(!ipid){ valido=false; showMsg('nueva','err','Todas las líneas deben tener una presentación seleccionada'); return; }
    if(cant<=0){ valido=false; showMsg('nueva','err','La cantidad debe ser mayor a 0'); return; }
    lineas.push({ idinsumospresentaciones:ipid, cantidad:cant, costoUnitario:costo, iva, idalmacen:alm });
  });
  if(!valido || !lineas.length) { if(!lineas.length) showMsg('nueva','err','Agrega al menos una línea'); return; }

  const btn = document.getElementById('btn-guardar');
  btn.disabled=true;
  btn.innerHTML='<span class="spin"></span> Guardando en SR...';
  showMsg('nueva','','');

  try {
    const r = await apiFetch('/api/compras', {
      method:'POST',
      body: JSON.stringify({ idproveedor, fechaaplicacion, fechafactura, foliofactura, referencia, lineas })
    });
    if(r.ok) {
      showMsg('nueva','ok', `Compra registrada en SoftRestaurant — Folio: <strong>${r.folio}</strong> · ID: ${r.idcompra}`);
      limpiarForm();
    } else {
      showMsg('nueva','err',r.error);
    }
  } catch(e) {
    showMsg('nueva','err','Error de red: '+e.message);
  }

  btn.disabled=false;
  btn.innerHTML='<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17,21 17,13 7,13 7,21"/><polyline points="7,3 7,8 15,8"/></svg> Guardar compra en SR';
}

// ─── Historial ────────────────────────────────────────────────────────────────
async function cargarHistorial() {
  const desde = document.getElementById('h-desde').value;
  const hasta = document.getElementById('h-hasta').value;
  const prov  = document.getElementById('h-proveedor').value;

  const wrap = document.getElementById('hist-wrap');
  wrap.innerHTML = '<div class="empty"><div class="spin"></div></div>';

  let url = `/api/compras?desde=${desde}&hasta=${hasta}`;
  if(prov) url += `&idproveedor=${prov}`;

  const data = await apiFetch(url).catch(()=>[]);
  const rows = Array.isArray(data) ? data : [];

  document.getElementById('hist-count').textContent = rows.length + ' compras';

  if(!rows.length){
    wrap.innerHTML='<div class="empty">Sin compras en el período seleccionado</div>';
    return;
  }

  wrap.innerHTML = `
    <table class="data-tbl">
      <thead><tr>
        <th>Folio</th><th>Fecha</th><th>Proveedor</th>
        <th>Ref. Factura</th><th class="r">Subtotal</th>
        <th class="r">IVA</th><th class="r">Total</th>
        <th>Estado</th><th></th>
      </tr></thead>
      <tbody>
        ${rows.map(c=>`
          <tr onclick="verDetalle(${c.idcompra})">
            <td class="bold">${c.folio}</td>
            <td>${fechaTxt(c.fechaaplicacion)}</td>
            <td class="bold">${c.proveedor_nombre}</td>
            <td style="color:var(--text-3)">${c.foliofactura||'—'}</td>
            <td class="r">${fmt(c.subtotal)}</td>
            <td class="r">${fmt(c.impuesto1)}</td>
            <td class="r" style="color:var(--orange);font-weight:800;">${fmt(c.total)}</td>
            <td>${c.cancelado
              ? '<span class="badge badge-red">Cancelada</span>'
              : '<span class="badge badge-green">Activa</span>'
            }</td>
            <td><button class="btn btn-sm btn-outline" onclick="event.stopPropagation();verDetalle(${c.idcompra})">Ver</button></td>
          </tr>
        `).join('')}
      </tbody>
    </table>
  `;
}

async function verDetalle(idcompra) {
  detalleActual = idcompra;
  document.getElementById('det-titulo').textContent = 'Cargando...';
  document.getElementById('det-body').innerHTML = '<div class="empty"><div class="spin"></div></div>';
  document.getElementById('btn-cancelar-compra').style.display = 'none';
  document.getElementById('modal-detalle').classList.add('open');

  let detalle;
  try {
    detalle = await apiFetch(`/api/compras/${idcompra}/detalle`);
  } catch (e) {
    document.getElementById('det-titulo').textContent = 'No se pudo cargar la compra';
    document.getElementById('det-body').innerHTML = `<div class="empty">${e.message || 'Error al consultar el detalle'}</div>`;
    return;
  }

  const comp = detalle?.compra || null;
  const lins = Array.isArray(detalle?.lineas)
    ? detalle.lineas
    : (Array.isArray(detalle) ? detalle : []);

  if(!comp){
    detalleActual = null;
    document.getElementById('det-titulo').textContent = 'Compra no encontrada';
    document.getElementById('det-body').innerHTML = '<div class="empty">El folio ya no existe en SoftRestaurant o no esta disponible para este usuario.</div>';
    return;
  }

  const cancelado = comp.cancelado;
  document.getElementById('btn-cancelar-compra').style.display = cancelado ? 'none' : '';
  document.getElementById('det-titulo').textContent =
    `Compra #${comp.folio} — ${comp.proveedor_nombre}`;

  document.getElementById('det-body').innerHTML = `
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:14px;font-size:11px;">
      <div><span style="color:var(--text-3)">Fecha aplicación:</span> <strong>${fechaTxt(comp.fechaaplicacion)}</strong></div>
      <div><span style="color:var(--text-3)">Factura:</span> <strong>${comp.foliofactura||'—'}</strong></div>
      <div><span style="color:var(--text-3)">Usuario:</span> <strong>${comp.usuario}</strong></div>
      <div><span style="color:var(--text-3)">Estado:</span> ${cancelado?'<span class="badge badge-red">Cancelada</span>':'<span class="badge badge-green">Activa</span>'}</div>
    </div>
    <table class="detalle-tbl" style="margin-bottom:12px;">
      <thead><tr><th>Insumo</th><th>Presentación</th><th>Unidad</th><th style="text-align:right">Cant.</th><th style="text-align:right">Costo unit.</th><th style="text-align:right">Subtotal</th></tr></thead>
      <tbody>
        ${lins.length ? lins.map(l=>`<tr>
          <td>${l.insumo}</td><td>${l.presentacion}</td><td>${l.unidad}</td>
          <td style="text-align:right">${fmtN(l.cantidad)}</td>
          <td style="text-align:right">${fmt(l.costo_unitario)}</td>
          <td style="text-align:right;font-weight:700">${fmt(l.subtotal_linea)}</td>
        </tr>`).join('') : '<tr><td colspan="6" style="padding:18px;text-align:center;color:var(--text-3);">Sin lineas de inventario registradas para esta compra.</td></tr>'}
      </tbody>
    </table>
    <div style="text-align:right;font-size:11px;">
      <span style="color:var(--text-3)">Subtotal: </span><strong>${fmt(comp.subtotal)}</strong>
      &nbsp;&nbsp;<span style="color:var(--text-3)">IVA: </span><strong>${fmt(comp.impuesto1)}</strong>
      &nbsp;&nbsp;<span style="font-size:14px;font-weight:800;color:var(--orange)">Total: ${fmt(comp.total)}</span>
    </div>
  `;
}

function cerrarModalDetalle(){ document.getElementById('modal-detalle').classList.remove('open'); }

async function confirmarCancelar() {
  if(!detalleActual) return;
  if(!confirm('¿Cancelar esta compra?\n\nNota: el stock NO se revertirá automáticamente. SR marcará la compra como cancelada y tú ajustas el inventario manualmente si es necesario.')) return;

  const r = await apiFetch(`/api/compras/${detalleActual}/cancelar`, { method:'POST' });
  if(r.ok){
    cerrarModalDetalle();
    cargarHistorial();
    alert('Compra cancelada en SoftRestaurant.');
  } else {
    alert('Error: '+r.error);
  }
}

// ─── Conciliación ─────────────────────────────────────────────────────────────
async function cargarAlmacenesConciliacion() {
  const sel = document.getElementById('conc-almacen');
  sel.innerHTML = '<option value="">Todos los almacenes</option>' +
    almacenes.map(a=>`<option value="${a.idalmacen}">${a.nombre||a.idalmacen}</option>`).join('');
}

async function cargarStock() {
  const alm  = document.getElementById('conc-almacen').value;
  const wrap = document.getElementById('conc-wrap');
  wrap.innerHTML = '<div class="empty"><div class="spin"></div></div>';
  document.getElementById('btn-conciliar').style.display='none';

  const url = '/api/compras/conciliacion/stock' + (alm?`?idalmacen=${alm}`:'');
  const data = await apiFetch(url).catch(()=>[]);
  const rows = Array.isArray(data)?data:[];

  if(!rows.length){
    wrap.innerHTML='<div class="empty">Sin registros de stock para este almacén</div>';
    return;
  }

  document.getElementById('conc-resumen').textContent = rows.length+' insumos';
  document.getElementById('btn-conciliar').style.display='';

  wrap.innerHTML = `
    <table class="data-tbl">
      <thead><tr>
        <th>Insumo</th><th>Presentación</th><th>Unidad</th><th>Almacén</th>
        <th class="r">Stock SR</th>
        <th class="r">Conteo físico</th>
        <th class="r">Diferencia</th>
      </tr></thead>
      <tbody>
        ${rows.map((r,i)=>{
          const almId = r.idalmacen||alm||'1';
          return `<tr>
            <td class="bold">${r.insumo}</td>
            <td>${r.presentacion}</td>
            <td>${r.unidad}</td>
            <td style="color:var(--text-3)">${r.almacen_nombre||almId}</td>
            <td class="r">${fmtN(r.stock_actual)}</td>
            <td class="td-r" style="padding:4px 8px;">
              <input type="number" class="conc-input conc-conteo" data-ipid="${r.idinsumospresentaciones}" data-alm="${almId}" data-stock="${r.stock_actual}"
                value="${Number(r.stock_actual).toFixed(4)}" min="0" step="0.0001"
                oninput="actualizarDiff(this)" style="width:100px;text-align:right;"/>
            </td>
            <td class="r conc-diff-cell" id="diff-${i}"><span class="conc-diff-zero">0.0000</span></td>
          </tr>`;
        }).join('')}
      </tbody>
    </table>
  `;
}

function actualizarDiff(inp) {
  const stock  = parseFloat(inp.dataset.stock||0);
  const conteo = parseFloat(inp.value||0);
  const diff   = Math.round((conteo-stock)*10000)/10000;
  // Encontrar celda diff de la misma fila
  const td = inp.closest('tr').querySelector('.conc-diff-cell');
  if(!td) return;
  const cls = diff>0?'conc-diff-pos':diff<0?'conc-diff-neg':'conc-diff-zero';
  const signo = diff>0?'+':'';
  td.innerHTML = `<span class="${cls}">${signo}${diff.toFixed(4)}</span>`;
}

async function guardarConciliacion() {
  const ajustes = [];
  document.querySelectorAll('.conc-conteo').forEach(inp=>{
    const conteo = parseFloat(inp.value||0);
    const stock  = parseFloat(inp.dataset.stock||0);
    if(conteo !== stock) {
      ajustes.push({
        idinsumospresentaciones: inp.dataset.ipid,
        idalmacen:               inp.dataset.alm,
        conteo_fisico:           conteo,
      });
    }
  });

  if(!ajustes.length){
    alert('No hay diferencias que aplicar. Todos los conteos coinciden con el stock de SR.');
    return;
  }

  if(!confirm(`¿Aplicar ${ajustes.length} ajuste(s) de inventario en SoftRestaurant?\nEsta acción registrará movimientos EDA en movtosalmacen.`)) return;

  const btn = document.getElementById('btn-conciliar');
  btn.disabled=true;
  btn.textContent='Aplicando...';

  const r = await apiFetch('/api/compras/conciliacion', {
    method:'POST',
    body: JSON.stringify({ ajustes })
  });

  btn.disabled=false;
  btn.innerHTML='Aplicar ajustes a SR';

  if(r.ok){
    alert(`Conciliación aplicada:\n• ${r.insertados} ajuste(s) registrados en SR\n• ${r.sin_cambio} sin diferencia (omitidos)`);
    cargarStock();
  } else {
    alert('Error: '+r.error);
  }
}

// ─── Proveedores ─────────────────────────────────────────────────────────────
async function cargarProveedores() {
  const wrap = document.getElementById('prov-wrap');
  wrap.innerHTML='<div class="empty"><div class="spin"></div></div>';
  const data = await apiFetch('/api/compras/proveedores').catch(()=>[]);
  proveedores = Array.isArray(data)?data:[];

  if(!proveedores.length){
    wrap.innerHTML='<div class="empty">Sin proveedores registrados</div>';
    return;
  }

  wrap.innerHTML = `
    <table class="data-tbl">
      <thead><tr><th>Clave</th><th>Nombre</th><th>Razón social</th><th>RFC</th><th>Teléfono</th><th>Email</th><th class="r">Crédito (días)</th></tr></thead>
      <tbody>
        ${proveedores.map(p=>`<tr>
          <td class="bold" style="font-family:monospace">${p.idproveedor}</td>
          <td class="bold">${p.nombre}</td>
          <td style="color:var(--text-3)">${p.razonsocial||'—'}</td>
          <td style="font-family:monospace">${p.rfc||'—'}</td>
          <td>${p.telefono||'—'}</td>
          <td>${p.email||'—'}</td>
          <td class="r">${p.credito||0}</td>
        </tr>`).join('')}
      </tbody>
    </table>
  `;
}

function abrirModalProveedor() {
  ['mp-id','mp-nombre','mp-rs','mp-rfc','mp-tel','mp-email'].forEach(id=>{
    document.getElementById(id).value='';
  });
  document.getElementById('mp-error').style.display='none';
  document.getElementById('modal-proveedor').classList.add('open');
}

function cerrarModalProveedor() {
  document.getElementById('modal-proveedor').classList.remove('open');
}

async function guardarProveedor() {
  const idproveedor  = document.getElementById('mp-id').value.trim().toUpperCase();
  const nombre       = document.getElementById('mp-nombre').value.trim();
  const razonsocial  = document.getElementById('mp-rs').value.trim();
  const rfc          = document.getElementById('mp-rfc').value.trim().toUpperCase();
  const telefono     = document.getElementById('mp-tel').value.trim();
  const email        = document.getElementById('mp-email').value.trim();
  const errEl        = document.getElementById('mp-error');

  if(!idproveedor||!nombre){
    errEl.textContent='Clave y Nombre son requeridos';
    errEl.style.display='block';
    return;
  }

  errEl.style.display='none';
  try {
    await apiFetch('/api/compras/proveedores', {
      method:'POST',
      body: JSON.stringify({ idproveedor, nombre, razonsocial, rfc, telefono, email })
    });
    cerrarModalProveedor();
    cargarProveedores();
    // Actualizar selector de compras
    const sel = document.getElementById('inp-proveedor');
    const opt = document.createElement('option');
    opt.value = idproveedor;
    opt.textContent = `${nombre} (${idproveedor})`;
    sel.appendChild(opt);
  } catch(e) {
    errEl.textContent = e.message || 'Error al guardar';
    errEl.style.display='block';
  }
}

// ─── Arrancar ─────────────────────────────────────────────────────────────────
init();
</script>
</body>
</html>
