<?php
// views/pages/patio_inventario.php — Inventario de Vehículos en Patio (manteniendo tu diseño)
// Requiere: partials/header.php, partials/menu.php, partials/topbar.php, partials/footer.php
session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  header("Location: ../../views/index.php");
  exit();
}
$usuario = $_SESSION['usuario'] ?? 'Invitado';
$permiso = $_SESSION['permiso'] ?? 0;

include("conex.php");
?>

<?php include 'partials/header.php'; ?>

<body>
<div class="container-fluid">
  <div class="row">

    <!-- Sidebar -->
    <?php include 'partials/menu.php'; ?>

    <!-- Contenido principal -->
    <main class="col-md-9 ms-sm-auto col-lg-10 px-0">
      <!-- Topbar (fondo rojo + reloj) -->
      <?php include 'partials/topbar.php'; ?>

      <!-- ====== CONTENIDO: Inventario Patio ====== -->
      <div class="px-3 py-2">

        <div class="d-flex align-items-center justify-content-between mb-2">
          <h6 class="m-0">Inventario de Vehículos en Patio</h6>
          <small class="text-muted">Usuario: <strong><?php echo htmlspecialchars($usuario); ?></strong></small>
        </div>

        <!-- Card filtros -->
        <div class="card shadow-sm mb-3">
          <div class="card-body pb-2">
            <div class="row g-2 align-items-end">
              <div class="col-12 col-md-3">
                <label class="form-label mb-1">Buscar (marca/modelo/color/pedido/origen)</label>
                <input type="text" id="filtroQ" class="form-control" placeholder="Escribe para filtrar...">
              </div>

              <div class="col-12 col-md-4">
                <label class="form-label mb-1">Multibúsqueda de chasis</label>
                <input type="text" id="filtroChasis" class="form-control" placeholder="Pega varios chasis separados por coma, espacio o salto de línea">
              </div>

              <div class="col-6 col-md-2">
                <label class="form-label mb-1">Bodega</label>
                <select id="filtroBodega" class="form-select">
                  <option value="">Todas</option>
                </select>
              </div>

              <div class="col-6 col-md-2">
                <label class="form-label mb-1">Estado</label>
                <select id="filtroEstado" class="form-select">
                  <option value="2" selected>En patio (2)</option>
                  <option value="">Todos</option>
                  <option value="1">1</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                </select>
              </div>

              <div class="col-12 col-md-1">
                <div class="form-check mt-4">
                  <input class="form-check-input" type="checkbox" id="autoRefresh" checked>
                  <label class="form-check-label small" for="autoRefresh">Auto</label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Card tabla -->
        <div class="card shadow-sm">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <div id="dtButtons" class="toolbar"></div>
              <div class="small text-muted" id="lastUpdate"></div>
            </div>

            <div class="table-responsive">
              <table id="tablaInventario" class="table table-striped table-bordered align-middle w-100">
                <thead class="table-light">
                  <tr>
                    <th>Ingreso</th>
                    <th>Días</th>
                    <th>Bodega</th>
                    <th>Andén</th>
                    <th>Zona</th>
                    <th>Sección</th>
                    <th>Marca</th>
                    <th>Modelo</th>
                    <th>Color</th>
                    <th>Chasis</th>
                    <th>Pedido</th>
                    <th>Estado</th>
                  </tr>
                </thead>
                <tbody></tbody>
                <tfoot class="table-light">
                  <tr>
                    <th>Ingreso</th>
                    <th>Días</th>
                    <th>Bodega</th>
                    <th>Andén</th>
                    <th>Zona</th>
                    <th>Sección</th>
                    <th>Marca</th>
                    <th>Modelo</th>
                    <th>Color</th>
                    <th>Chasis</th>
                    <th>Pedido</th>
                    <th>Estado</th>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </div>

      </div>
      <!-- ====== /CONTENIDO ====== -->

    </main>
  </div>
</div>

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

<!-- Si ya cargas Bootstrap/DataTables en header.php, puedes omitir estas líneas -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css">
<style>
  .table{ font-size:12px; }
  .form-control,.form-select,.btn{ font-size:12px; padding:.375rem .5rem; }
  .dt-buttons .btn{ margin-right:.25rem; }
  tr.dias-bajo{ background:#f3fff6; }   /* <=15 */
  tr.dias-medio{ background:#fffdf2; }  /* 16..30 */
  tr.dias-alto{ background:#fff5f5; }   /* >30 */
</style>

<script src="https://code.jquery.com/jquery-3.7.1.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.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>

<script>
const API = 'api/patio_inventario_data.php'; // ruta relativa a este archivo

function parseChasisList(txt){
  if(!txt) return [];
  return txt.split(/[\s,;]+/).map(s => s.trim()).filter(Boolean);
}

async function cargarBodegas(){
  try{
    const url = new URL(API, location.href);
    url.searchParams.set('only_bodegas','1');
    const r = await fetch(url);
    const j = await r.json();
    const sel = document.getElementById('filtroBodega');
    if (j.success && Array.isArray(j.bodegas)){
      for(const b of j.bodegas){
        const o = document.createElement('option');
        o.value = b.id;
        o.textContent = b.nombre;
        sel.appendChild(o);
      }
    }
  }catch(_e){}
}

let tabla=null, timer=null;

function pintarFilaPorDias(row, dias){
  row.classList.remove('dias-bajo','dias-medio','dias-alto');
  if (dias <= 15) row.classList.add('dias-bajo');
  else if (dias <= 30) row.classList.add('dias-medio');
  else row.classList.add('dias-alto');
}

function initTabla(){
  tabla = new DataTable('#tablaInventario', {
    deferRender:true,
    processing:true,
    serverSide:false,
    searching:false, // usamos filtros propios
    pageLength:25,
    lengthMenu:[25,50,100,200],
    order:[[0,'asc']],
    dom:"<'row'<'col-sm-12 col-md-6'B><'col-sm-12 col-md-6'f>>" +
        "<'row'<'col-sm-12'tr>>" +
        "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
    buttons:[
      {extend:'copyHtml5', text:'Copiar'},
      {extend:'excelHtml5', text:'Excel'},
      {extend:'csvHtml5', text:'CSV'},
      {extend:'print', text:'Imprimir'}
    ],
    columns:[
      { data:'fecha_ingreso' },
      { data:'dias' },
      { data:'bodega' },
      { data:'anden' },
      { data:'zona' },
      { data:'seccion' },
      { data:'marca' },
      { data:'modelo' },
      { data:'color' },
      { data:'chasis' },
      { data:'pedido' },
      { data:'estado' }
    ],
    createdRow: function(row, data){
      pintarFilaPorDias(row, Number(data.dias||0));
    },
    language:{ url:"https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json" }
  });
  tabla.buttons().container().appendTo('#dtButtons');
}

async function cargarTabla(){
  const q = document.getElementById('filtroQ').value.trim();
  const estado = document.getElementById('filtroEstado').value.trim();
  const bodega = document.getElementById('filtroBodega').value.trim();
  const multi = parseChasisList(document.getElementById('filtroChasis').value);

  const url = new URL(API, location.href);
  if (q) url.searchParams.set('q', q);
  if (estado) url.searchParams.set('estado', estado);
  if (bodega) url.searchParams.set('bodega_id', bodega);
  if (multi.length) url.searchParams.set('multi', multi.join(','));

  document.getElementById('lastUpdate').textContent = 'Cargando...';
  const r = await fetch(url);
  const j = await r.json();

  if (!j.success) { alert(j.message || 'Error al cargar'); return; }

  tabla.clear();
  tabla.rows.add(j.data || []).draw();
  document.getElementById('lastUpdate').textContent =
    'Actualizado: ' + (new Date()).toLocaleString();
}

function programarAuto(){
  const chk = document.getElementById('autoRefresh');
  if (timer){ clearInterval(timer); timer=null; }
  if (chk.checked){ timer = setInterval(cargarTabla, 60000); }
}

document.addEventListener('DOMContentLoaded', async () => {
  await cargarBodegas();
  initTabla();
  await cargarTabla();
  programarAuto();

  document.getElementById('filtroQ').addEventListener('input', cargarTabla);
  document.getElementById('filtroChasis').addEventListener('change', cargarTabla);
  document.getElementById('filtroBodega').addEventListener('change', cargarTabla);
  document.getElementById('filtroEstado').addEventListener('change', cargarTabla);
  document.getElementById('autoRefresh').addEventListener('change', programarAuto);
});
</script>

</body>
</html>
