<?php
// ⬇️ Anti-caché: debe ir ANTES de cualquier salida
header("Content-Type: text/html; charset=utf-8");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: 0");

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/navbar.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<div class="content-wrapper">
  <section class="content-header">
    <div class="container-fluid d-flex justify-content-between align-items-center">
      <h1>Gestión de Productos</h1>
      <button id="btnNuevo" class="btn btn-primary"><i class="fas fa-plus"></i> Nuevo Producto</button>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      <div class="card">
        <div class="card-body">
          <div class="table-responsive">
            <table id="tablaProductos" class="table table-bordered table-hover">
              <thead class="thead-dark">
                <tr>
                  <th>Imagen</th>
                  <th>Nombre</th>
                  <th>Código (QR general)</th>
                  <th>Tipo</th>
                  <th>Categoría</th>
                  <th>Medida</th>
                  <th>Stock</th>
                  <th>Fecha de Ingreso</th>
                  <th>Acciones</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>

<!-- Modal para agregar o editar productos -->
<div class="modal fade" id="modalProducto" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <form id="formProducto" enctype="multipart/form-data">
        <div class="modal-header bg-primary text-white">
          <h5 class="modal-title">Registrar Producto</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>

        <div class="modal-body">
          <input type="hidden" id="producto_id" name="producto_id">
          <input type="hidden" id="imagen_actual" name="imagen_actual">

          <div class="form-row">
            <div class="form-group col-md-6">
              <label for="codigo">Código (QR general)</label>
              <div class="input-group">
                <input type="text" class="form-control" id="codigo" name="codigo" placeholder="Escribe o escanea el QR" autocomplete="off" required>
                <div class="input-group-append">
                  <button class="btn btn-dark" type="button" id="btnEscanearQRGeneral" title="Escanear QR">
                    <i class="fas fa-qrcode"></i>
                  </button>
                </div>
              </div>
              <small class="text-muted">Este será el código único del producto.</small>
            </div>

            <div class="form-group col-md-6">
              <label for="nombre">Nombre</label>
              <input type="text" class="form-control" id="nombre" name="nombre" required>
            </div>

            <div class="form-group col-md-4">
              <label for="select_tipo">Tipo</label>
              <select class="form-control" id="select_tipo" name="tipo_id" required></select>
            </div>
            <div class="form-group col-md-4">
              <label for="select_categoria">Categoría</label>
              <select class="form-control" id="select_categoria" name="categoria_id" required></select>
            </div>
            <div class="form-group col-md-4">
              <label for="select_medida">Medida</label>
              <select class="form-control" id="select_medida" name="medida_id" required></select>
            </div>

            <div class="form-group col-md-6">
              <label for="stock">Stock</label>
              <input type="number" class="form-control" id="stock" name="stock" required>
            </div>
            <div class="form-group col-md-6">
              <label for="stock_minimo">Stock mínimo</label>
              <input type="number" class="form-control" id="stock_minimo" name="stock_minimo">
            </div>

            <div class="form-group col-md-6">
              <label for="imagen">Imagen referencial</label>
              <input type="file" class="form-control-file" id="imagen" name="imagen" accept="image/*">
              <small class="text-muted d-block">Formatos: JPG/PNG/WebP. Máx. 2MB.</small>
              <div class="mt-2">
                <img id="preview_imagen" src="" class="img-thumbnail d-none" style="max-height:120px;object-fit:cover;">
              </div>
            </div>

            <div class="form-group col-md-6">
              <label for="fecha_ingreso">Fecha de Ingreso</label>
              <input type="date" class="form-control" id="fecha_ingreso" name="fecha_ingreso">
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-success">Guardar</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Modal: Ingreso rápido de stock (para el botón verde) -->
<div class="modal fade" id="modalIngresoProducto" tabindex="-1" role="dialog" aria-labelledby="ingresoLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <form id="formIngresoRapido" class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title" id="ingresoLabel">Ingreso de stock: <span id="ingreso_producto_label"></span></h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Cerrar">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="ingreso_producto_id" name="producto_id">
        <div class="form-group">
          <label for="ingreso_cantidad">Cantidad</label>
          <input type="number" class="form-control" id="ingreso_cantidad" name="cantidad" min="1" required>
        </div>
        <div class="form-group">
          <label for="ingreso_motivo">Motivo (opcional)</label>
          <input type="text" class="form-control" id="ingreso_motivo" name="motivo" placeholder="Compra, ajuste, etc.">
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success" type="submit">Registrar ingreso</button>
        <button class="btn btn-secondary" type="button" data-dismiss="modal">Cerrar</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal escáner QR -->
<div class="modal fade" id="modalEscanerQR" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h5 class="modal-title">Escaneo QR</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body text-center">
        <div style="max-width:100%; aspect-ratio:1/1; overflow:hidden; border-radius:10px; box-shadow:0 0 10px #000">
          <video id="video" class="w-100 border d-none" style="object-fit:cover;"></video>
        </div>
      </div>
    </div>
  </div>
</div>

<?php include "../templates/footer.php"; ?>

<script>window.BASE_URL = "<?= BASE_URL ?>";</script>

<!-- ✅ Carga UMD del lector QR (sin type="module" y SIN WORKER_PATH) -->
<script src="<?= BASE_URL ?>assets/js/qr/qr-scanner.umd.min.js?v=1"></script>

<!-- ✅ Tu JS con fixes (versión nueva para romper caché) -->
<script src="<?= BASE_URL ?>assets/js/productos.js?v=2.0"></script>

<script>
  // Vista previa de imagen
  (function () {
    const inputImagen = document.getElementById('imagen');
    const preview = document.getElementById('preview_imagen');
    if (!inputImagen || !preview) return;

    inputImagen.addEventListener('change', (e) => {
      const f = e.target.files && e.target.files[0];
      if (!f) { preview.classList.add('d-none'); preview.src=''; return; }
      if (f.size > 2 * 1024 * 1024) {
        Swal.fire('Atención', 'La imagen supera 2MB.', 'warning');
        inputImagen.value = ''; preview.classList.add('d-none'); preview.src=''; return;
      }
      const url = URL.createObjectURL(f);
      preview.src = url; preview.classList.remove('d-none');
    });
  })();

  // ⬇️ Fix bfcache + auto-refresh al volver el foco
  window.addEventListener('pageshow', function (e) {
    if (e.persisted) location.reload();
  });
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden && typeof cargarProductos === 'function') {
      try { cargarProductos(); } catch(e) {}
    }
  });
</script>
