<?php
// index.php — Vista de DAI 70 con modal de tarjas
session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  header("Location: ../../views/index.php");
  exit();
}
$usuario = $_SESSION['usuario'] ?? '';
$permiso = $_SESSION['permiso'] ?? '';
require_once __DIR__ . '/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 -->
      <?php include 'partials/topbar.php'; ?>

      <div class="row">
        <div class="col-lg-12 col-md-12">
          <div class="panel panel-WHITE">
            <div class="panel-heading">
              <div class="row">
                <div class="row">
                  <div class="col-md-12 col-md-offset-0">
                    <a id="btnngreso" data-toggle="modal" data-target="#guia_transporte" class="btn btn-warning">
                      <i class="fa fa-clone" aria-hidden="true"></i> Ingreso de Guía
                    </a>
                  </div>
                </div>
                <br>
                <div class="col-md-12 col-md-offset-0">
                  <table id="dai70" class="table table-hover" cellspacing="0" width="100%">
                    <thead>
                      <tr class="info">
                        <th>DAI 70</th>
                        <th>Nº Item</th>
                        <th>Nro. Tarja</th>
                        <th>Marca</th>
                        <th>Modelo</th>
                        <th>Nº de Chasis</th>
                        <th>Color</th>
                        <th>Estado</th>
                        <th>Acción</th>
                      </tr>
                    </thead>
                    <tbody></tbody>
                  </table>
                </div>
              </div><!-- row -->
            </div><!-- panel-heading -->
          </div><!-- panel -->
        </div>
      </div>
    </main>
  </div>
</div>

<!-- Modal: Tarjas de la Unidad -->
<div class="modal fade" id="modalTarjas" tabindex="-1" aria-labelledby="modalTarjasLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title" id="modalTarjasLabel">
          Tarjas de la unidad — Chasis: <span id="tarjasChasis"></span>
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <div class="modal-body">
        <div class="table-responsive" style="max-height:60vh; overflow:auto;">
          <table class="table table-striped table-bordered table-sm mb-0">
            <thead class="table-light">
              <tr>
                <th># Tarja</th>
                <th># Auto</th>
                <th>Fecha</th>
                <th>Bodega</th>
                <th>Observación</th>
              </tr>
            </thead>
            <tbody id="tbodyTarjas">
              <tr><td colspan="5" class="text-center text-muted">Sin datos</td></tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="modal-footer py-2">
        <button class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cerrar</button>
      </div>
    </div>
  </div>
</div>

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

<!-- DataTables (si tu header.php no ya los incluye, mantén estos CDN) -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<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>
$(function () {
  const tabla = $('#dai70').DataTable({
    ajax: { url: 'api/ingresos_list.php', dataSrc: 'data' },
    columns: [
      { data: 'dai70' },
      { data: 'item' },
      { data: 'numerotarja' },
      { data: 'descripcion' }, // Marca
      { data: 'modelo' },
      { data: 'chasis' },
      { data: 'color' },
      { data: 'estado' },
      { data: 'accion', orderable:false, searchable:false }
    ],
    order: [[0,'desc']],
    paging: false,           // sin paginado
    scrollY: '60vh',         // barra vertical (contenedor)
    scrollCollapse: true,
    language: {
      processing:"Procesando...", search:"Buscar:", lengthMenu:"Mostrar _MENU_",
      info:"_START_–_END_ de _TOTAL_", infoEmpty:"0–0 de 0", infoFiltered:"(filtrado de _MAX_)",
      loadingRecords:"Cargando...", zeroRecords:"No hay registros", emptyTable:"Sin datos",
      paginate:{ first:"Primero", previous:"Anterior", next:"Siguiente", last:"Último" },
      aria:{ sortAscending:": ordenar ascendente", sortDescending:": ordenar descendente" }
    }
  });

  // Ver tarjas
  $(document).on('click', '.btn-ver-tarjas', function () {
    const idd    = $(this).data('idd');     // id_datadai
    const chasis = $(this).data('chasis') || '';
    $('#tarjasChasis').text(chasis);

    const $tb = $('#tbodyTarjas');
    $tb.html('<tr><td colspan="5" class="text-center text-muted">Cargando…</td></tr>');

    fetch('api/tarjas_list.php?idd=' + encodeURIComponent(idd))
      .then(r => r.json())
      .then(j => {
        if (!j || j.success === false) {
          $tb.html('<tr><td colspan="5" class="text-center text-danger">No se pudo obtener la lista</td></tr>');
          return;
        }
        if (!Array.isArray(j.data) || j.data.length === 0) {
          $tb.html('<tr><td colspan="5" class="text-center text-muted">Sin tarjas registradas</td></tr>');
          return;
        }
        const rows = j.data.map(t => `
          <tr>
            <td>${t.numerotarja || ''}</td>
            <td>${t.numero_auto || ''}</td>
            <td>${t.fecha || ''}</td>
            <td>${t.bodega || ''}</td>
            <td>${t.observacion || ''}</td>
          </tr>
        `).join('');
        $tb.html(rows);
      })
      .catch(err => {
        console.error(err);
        $tb.html('<tr><td colspan="5" class="text-center text-danger">Error de conexión</td></tr>');
      });

    new bootstrap.Modal(document.getElementById('modalTarjas')).show();
  });
});
</script>
</body>
</html>
