<?php
// modelos.php — SGO · Inventario · Modelos
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 · Modelos</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 flex-wrap align-items-center gap-2 px-3 py-2 border-bottom">
          <h6 class="mb-0"><i class="fa-solid fa-car-side me-2"></i> Modelos</h6>
          <select id="fMarca" class="form-select form-select-sm" style="width:220px">
            <option value="">— Todas las marcas —</option>
          </select>
          <input id="txtBuscar" class="form-control form-control-sm" placeholder="Buscar...">
          <div class="ms-auto d-flex gap-2">
            <button id="btnSync" class="btn btn-outline-secondary btn-sm">
              <i class="fa-solid fa-rotate"></i> Sincronizar
            </button>
            <button id="btnNueva" class="btn btn-primary btn-sm">
              <i class="fa-solid fa-plus"></i> Nuevo
            </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>Marca</th>
                  <th>Modelo</th>
                  <th style="width:90px" class="dt-center">Año</th>
                  <th style="width:120px" class="dt-center">Estado</th>
                  <th style="width:200px" class="dt-center">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="formModelo">
      <div class="modal-header py-2">
        <h6 class="modal-title"><span id="ttlForm">Nuevo Modelo</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_modelo" name="id_modelo" value="0">
        <div class="mb-2">
          <label class="form-label">Marca *</label>
          <select class="form-select" id="id_marca" name="id_marca" required></select>
        </div>
        <div class="mb-2">
          <label class="form-label">Modelo *</label>
          <input type="text" class="form-control" id="nombre" name="nombre" maxlength="150" required>
        </div>
        <div class="mb-2">
          <label class="form-label">Año</label>
          <input type="number" class="form-control" id="anio" name="anio" min="1900" max="2100" step="1" placeholder="Opcional">
        </div>
        <div class="form-check">
          <input class="form-check-input" type="checkbox" id="condicion" name="condicion" checked>
          <label class="form-check-label" for="condicion">Activo</label>
        </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('formModelo');

  cargarMarcasFiltro();      // combo del toolbar
  initTable();
  window.addEventListener('resize', debounce(resizeTableHeight, 150));

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

/* ===== DataTable sin ajax (recarga manual) ===== */
function initTable(){
  if (dt) return;
  const h = computeScrollY();
  dt = new DataTable('#tabla', {
    data: [],
    columns: [
      { data: 'marca_nombre' },
      { data: 'nombre' },
      { data: 'anio', className:'dt-center', render: v => v ? v : '' },
      {
        data: 'condicion', className:'dt-center',
        render: v => v==1 ? '<span class="badge bg-success">Activo</span>' : '<span class="badge bg-secondary">Inactivo</span>'
      },
      { data: null, className:'dt-center', orderable:false, render: row => accionesHTML(row) },
    ],
    order: [[0,'asc'], [1,'asc'], [2,'desc']],
    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 || '');
  const idMarca = encodeURIComponent(document.getElementById('fMarca').value || '');
  fetch(`${apiBase}modelo_list.php?_=${Date.now()}&search=${q}&id_marca=${idMarca}`)
    .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);
}

/* ===== Cargar combos ===== */
function cargarMarcasFiltro(){
  fetch(`${apiBase}marca_options.php`)
    .then(r=>r.json())
    .then(j=>{
      const sel = document.getElementById('fMarca');
      (j.data||[]).forEach(o=>{
        const opt = document.createElement('option');
        opt.value = o.id_marca; opt.textContent = o.nombre;
        sel.appendChild(opt);
      });
    });
}
function cargarMarcasModal(selectedId=0){
  fetch(`${apiBase}marca_options.php`)
    .then(r=>r.json())
    .then(j=>{
      const sel = document.getElementById('id_marca');
      sel.innerHTML = '';
      (j.data||[]).forEach(o=>{
        const opt = document.createElement('option');
        opt.value = o.id_marca; opt.textContent = o.nombre;
        sel.appendChild(opt);
      });
      if (selectedId) sel.value = String(selectedId);
    });
}

/* ===== UI acciones ===== */
function nueva(){
  form.reset();
  document.getElementById('id_modelo').value = 0;
  document.getElementById('condicion').checked = true;
  document.getElementById('ttlForm').textContent = 'Nuevo Modelo';
  cargarMarcasModal();
  modal.show();
}
function accionesHTML(row){
  const id = row.id_modelo;
  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="Activar/Desactivar"><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}modelo_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_modelo').value = d.id_modelo;
      document.getElementById('nombre').value = d.nombre;
      document.getElementById('anio').value = d.anio ?? '';
      document.getElementById('condicion').checked = (parseInt(d.condicion)===1);
      document.getElementById('ttlForm').textContent = 'Editar Modelo';
      cargarMarcasModal(d.id_marca);
      modal.show();
    })
    .catch(()=> Swal.fire('Error','No se pudo obtener el registro','error'));
}
function onGuardar(e){
  e.preventDefault();
  const payload = {
    id_modelo: parseInt(document.getElementById('id_modelo').value || '0'),
    id_marca: parseInt(document.getElementById('id_marca').value || '0'),
    nombre: (document.getElementById('nombre').value || '').trim(),
    anio: document.getElementById('anio').value ? parseInt(document.getElementById('anio').value) : null,
    condicion: document.getElementById('condicion').checked ? 1 : 0
  };
  if (!payload.id_marca) return Swal.fire('Validación','Selecciona una marca','info');
  if (!payload.nombre) { document.getElementById('nombre').focus(); return Swal.fire('Validación','El modelo es obligatorio','info'); }
  if (payload.anio && (payload.anio < 1900 || payload.anio > 2100)) {
    document.getElementById('anio').focus(); return Swal.fire('Validación','Año fuera de rango','info');
  }

  fetch(`${apiBase}modelo_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}modelo_toggle.php`, {
    method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id_modelo: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 inactivarlo en lugar de eliminar.',
    icon:'warning', showCancelButton:true, confirmButtonText:'Eliminar', cancelButtonText:'Cancelar'
  }).then(res=>{
    if(!res.isConfirmed) return;
    fetch(`${apiBase}modelo_delete.php`, {
      method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id_modelo: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'));
  });
}
function sincronizar(){
  Swal.fire({
    title:'Sincronizar modelos',
    text:'Copiará nuevas combinaciones Marca/Modelo (y año si existe) desde tb_datadai.',
    icon:'question', showCancelButton:true, confirmButtonText:'Sincronizar', cancelButtonText:'Cancelar'
  }).then(res=>{
    if(!res.isConfirmed) return;
    fetch(`${apiBase}modelo_sync.php`, { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({}) })
      .then(r=>r.json())
      .then(j=>{
        if(!j.success) return Swal.fire('Atención', j.message||'No se pudo sincronizar', 'warning');
        Swal.fire('Listo', `Marcas nuevas: ${j.inserted_brands ?? 0}\nModelos nuevos: ${j.inserted_models ?? 0}`, 'success');
        recargarTabla();
        cargarMarcasFiltro(); // por si aparecieron marcas nuevas
      })
      .catch(()=> Swal.fire('Error','No se pudo sincronizar','error'));
  });
}

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