<?php
// bodegas.php — SGO · Inventario · Bodegas
declare(strict_types=1);
session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  header("Location: ../../views/index.php"); exit();
}
$usuario = $_SESSION['usuario'] ?? '';
$permiso = (int)($_SESSION['permiso'] ?? 0);
?>
<?php include __DIR__ . '/partials/header.php'; ?>
<!doctype html>
<html lang="es" data-theme="light">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>SGO · Inventario · Bodegas</title>

  <!-- CSS (quita si ya se cargan en header.php) -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" referrerpolicy="no-referrer" />
  <link href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bootstrap-4@5/bootstrap-4.min.css" rel="stylesheet">

  <style>
    :root { font-size: 15.5px; }
    .dt-center { text-align:center; }
    html, body, .container-fluid, .row { height: 100%; }
    .flex-fill { min-height: 0; }
    #workArea, #tableWrap { min-height: 0; padding: 0; }
    .dataTables_wrapper { padding: 0; }
    html[data-theme="dark"] body { background:#0f1115; color:#e7e7e7; }
    html[data-theme="dark"] .table { color:#e7e7e7; }
    html[data-theme="dark"] .table thead th { color:#f0f0f0; }
  </style>
</head>
<body>
<div class="container-fluid">
  <div class="row">
    <?php include __DIR__ . '/partials/menu.php'; ?>

    <main class="col-md-9 ms-sm-auto col-lg-10 px-0 d-flex flex-column">
      <?php include __DIR__ . '/partials/topbar.php'; ?>

      <section id="workArea" class="flex-fill d-flex flex-column">
        <div id="toolbar" class="d-flex align-items-center gap-2 px-3 py-2 border-bottom">
          <h6 class="mb-0"><i class="fa-solid fa-warehouse me-2"></i> Bodegas</h6>
          <input id="txtBuscar" class="form-control form-control-sm" placeholder="Buscar...">
          <div class="ms-auto d-flex gap-2">
            <button id="btnNueva" class="btn btn-primary btn-sm">
              <i class="fa-solid fa-plus"></i> Nueva
            </button>
          </div>
        </div>

        <div id="tableWrap" class="flex-fill d-flex flex-column">
          <div class="flex-fill overflow-hidden">
            <table id="tabla" class="table table-striped table-hover w-100 m-0">
              <thead>
                <tr>
                  <th>Nombre</th>
                  <th>Ciudad</th>
                  <th>Dirección</th>
                  <th class="dt-center" style="width:90px">Activo</th>
                  <th class="dt-center" style="width:110px">Estado</th>
                  <th class="dt-center" style="width:200px">Acciones</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
        </div>
      </section>
    </main>
  </div>
</div>

<!-- Modal CRUD -->
<div class="modal fade" id="modalForm" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" id="formBodega">
      <div class="modal-header py-2">
        <h6 class="modal-title"><span id="ttlForm">Nueva Bodega</span></h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="id_bodega" name="id_bodega" value="0">
        <div class="mb-2">
          <label class="form-label">Nombre *</label>
          <input type="text" class="form-control" id="nombre" name="nombre" maxlength="150" required>
        </div>
        <div class="mb-2">
          <label class="form-label">Ciudad *</label>
          <input type="text" class="form-control" id="ciudad" name="ciudad" maxlength="120" required>
        </div>
        <div class="mb-2">
          <label class="form-label">Dirección *</label>
          <input type="text" class="form-control" id="direccion" name="direccion" maxlength="200" required>
        </div>
        <div class="row">
          <div class="col-6">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" id="activo" name="activo" checked>
              <label class="form-check-label" for="activo">Activo (operativo)</label>
            </div>
          </div>
          <div class="col-6">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" id="condicion" name="condicion" checked>
              <label class="form-check-label" for="condicion">Habilitada</label>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer py-2">
        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancelar</button>
        <button type="submit" class="btn btn-primary btn-sm">Guardar</button>
      </div>
    </form>
  </div>
</div>

<?php include __DIR__ . '/partials/footer.php'; ?>

<!-- JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
const apiBase = (window.SGO_API_BASE ?? 'api/');
let dt=null, modal, form;

document.addEventListener('DOMContentLoaded', () => {
  modal = new bootstrap.Modal(document.getElementById('modalForm'));
  form  = document.getElementById('formBodega');

  initTable();
  window.addEventListener('resize', debounce(resizeTableHeight, 150));

  document.getElementById('txtBuscar').addEventListener('input', () => recargarTabla());
  document.getElementById('btnNueva').addEventListener('click', nueva);
  form.addEventListener('submit', onGuardar);
});

/* ===== DataTable sin ajax (recarga manual) ===== */
function initTable(){
  if (dt) return;
  const h = computeScrollY();
  dt = new DataTable('#tabla', {
    data: [],
    columns: [
      { data: 'nombre' },
      { data: 'ciudad' },
      { data: 'direccion' },
      { data: 'activo', className:'dt-center', render: v => v==1 ? '<span class="badge bg-info">Sí</span>' : '<span class="badge bg-secondary">No</span>' },
      { data: 'condicion', className:'dt-center', render: v => v==1 ? '<span class="badge bg-success">Habilitada</span>' : '<span class="badge bg-dark">Inactiva</span>' },
      { data: null, className:'dt-center', orderable:false, render: row => accionesHTML(row) },
    ],
    order: [[0,'asc'], [1,'asc']],
    scrollY: h + 'px',
    scrollCollapse: true,
    paging: true,
    language: { url: 'https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json' }
  });
  recargarTabla();
}

function recargarTabla(){
  const q = encodeURIComponent(document.getElementById('txtBuscar').value || '');
  fetch(`${apiBase}bodegas_list.php?_=${Date.now()}&search=${q}`)
    .then(r=>r.json())
    .then(j=>{
      if(!j.success) throw new Error(j.message||'Error');
      const pagina = dt.page();
      dt.clear();
      dt.rows.add(j.data || []);
      dt.draw(false);
      dt.page(pagina).draw(false);
      resizeTableHeight();
    })
    .catch(err=>{
      console.error(err);
      Swal.fire('Error','No se pudo cargar la lista','error');
    });
}

function resizeTableHeight(){
  if (!dt) return;
  const h = computeScrollY();
  const wrapper = document.querySelector('#tabla')?.closest('.dataTables_wrapper');
  const scroller = wrapper?.querySelector('.dataTables_scrollBody');
  if (scroller) {
    scroller.style.height = h + 'px';
    scroller.style.maxHeight = h + 'px';
  }
  dt.columns.adjust();
}
function computeScrollY(){
  const tableWrap = document.getElementById('tableWrap');
  const wrapper   = document.querySelector('#tabla')?.closest('.dataTables_wrapper');
  const headH = wrapper?.querySelector('.dataTables_scrollHead')?.offsetHeight || 0;
  const infoH = wrapper?.querySelector('.dataTables_info')?.offsetHeight || 0;
  const pagH  = wrapper?.querySelector('.dataTables_paginate')?.offsetHeight || 0;
  const gap   = 16;
  const wrapH = tableWrap?.clientHeight || 400;
  return Math.max(160, wrapH - headH - infoH - pagH - gap);
}

/* ===== UI acciones ===== */
function nueva(){
  form.reset();
  document.getElementById('id_bodega').value = 0;
  document.getElementById('activo').checked = true;
  document.getElementById('condicion').checked = true;
  document.getElementById('ttlForm').textContent = 'Nueva Bodega';
  modal.show();
}
function accionesHTML(row){
  const id = row.id_bodega;
  return `
    <button class="btn btn-sm btn-outline-primary me-1" onclick="editar(${id})" title="Editar"><i class="fa-solid fa-pen"></i></button>
    <button class="btn btn-sm btn-outline-warning me-1" onclick="toggleEstado(${id})" title="Habilitar/Inhabilitar"><i class="fa-solid fa-power-off"></i></button>
    <button class="btn btn-sm btn-outline-danger" onclick="eliminar(${id})" title="Eliminar/Inactivar"><i class="fa-solid fa-trash"></i></button>
  `;
}
function editar(id){
  fetch(`${apiBase}bodega_get.php?id=${id}`)
    .then(r=>r.json())
    .then(j=>{
      if(!j.success) return Swal.fire('Atención', j.message||'No encontrado', 'warning');
      const d = j.data;
      document.getElementById('id_bodega').value = d.id_bodega;
      document.getElementById('nombre').value = d.nombre;
      document.getElementById('ciudad').value = d.ciudad;
      document.getElementById('direccion').value = d.direccion;
      document.getElementById('activo').checked = (parseInt(d.activo)===1);
      document.getElementById('condicion').checked = (parseInt(d.condicion)===1);
      document.getElementById('ttlForm').textContent = 'Editar Bodega';
      modal.show();
    })
    .catch(()=> Swal.fire('Error','No se pudo obtener el registro','error'));
}
function onGuardar(e){
  e.preventDefault();
  const payload = {
    id_bodega: parseInt(document.getElementById('id_bodega').value || '0'),
    nombre: (document.getElementById('nombre').value || '').trim(),
    ciudad: (document.getElementById('ciudad').value || '').trim(),
    direccion: (document.getElementById('direccion').value || '').trim(),
    activo: document.getElementById('activo').checked ? 1 : 0,
    condicion: document.getElementById('condicion').checked ? 1 : 0
  };
  if (!payload.nombre || !payload.ciudad || !payload.direccion) {
    return Swal.fire('Validación','Nombre, ciudad y dirección son obligatorios','info');
  }
  fetch(`${apiBase}bodega_save.php`, {
    method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload)
  })
  .then(r=>r.json())
  .then(j=>{
    if(!j.success) return Swal.fire('Atención', j.message||'No se pudo guardar', 'warning');
    Swal.fire('Éxito', j.message||'Guardado', 'success');
    modal.hide();
    recargarTabla();
  })
  .catch(()=> Swal.fire('Error','No se pudo guardar','error'));
}
function toggleEstado(id){
  fetch(`${apiBase}bodega_toggle.php`, {
    method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id_bodega:id})
  })
  .then(r=>r.json())
  .then(j=>{
    if(!j.success) return Swal.fire('Atención', j.message||'No se pudo actualizar', 'warning');
    recargarTabla();
  })
  .catch(()=> Swal.fire('Error','No se pudo actualizar','error'));
}
function eliminar(id){
  Swal.fire({
    title: '¿Eliminar?', text: 'Puedes inactivarla en lugar de eliminar.',
    icon:'warning', showCancelButton:true, confirmButtonText:'Eliminar', cancelButtonText:'Cancelar'
  }).then(res=>{
    if(!res.isConfirmed) return;
    fetch(`${apiBase}bodega_delete.php`, {
      method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id_bodega:id, hard:0})
    })
    .then(r=>r.json())
    .then(j=>{
      if(!j.success) return Swal.fire('Atención', j.message||'No se pudo eliminar', 'warning');
      Swal.fire('Listo', j.message||'Eliminado', 'success');
      recargarTabla();
    })
    .catch(()=> Swal.fire('Error','No se pudo eliminar','error'));
  });
}

/* Utils */
function debounce(fn, wait=200){ let t; return (...a)=>{ clearTimeout(t); t=setTimeout(()=>fn.apply(this,a), wait); }; }
</script>
</body>
</html>
