<?php 
declare(strict_types=1);
session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  header("Location: ../../views/index.php"); exit();
}
$usuario   = $_SESSION['usuario'] ?? 'Invitado';
$permiso   = $_SESSION['permiso'] ?? 0;

require_once __DIR__ . '/conex.php';

/* =========================
   API INTERNA (AJAX)
   ========================= */
if (isset($_GET['action']) || isset($_POST['action'])) {
  header('Content-Type: application/json; charset=utf-8');
  $action = $_GET['action'] ?? $_POST['action'];

  // Listar vehículos en id_estado = 2 + última impronta válida (si existe)
  if ($action === 'list_estado2') {
    $sql = "
      SELECT 
        d.iddatadai,
        d.marca,
        d.modelo,
        d.chasis,
        d.color,
        imp.fecha  AS impronta_fecha,
        imp.foto   AS impronta_foto
      FROM tb_datadai AS d
      LEFT JOIN (
        SELECT i1.id_datadai, i1.fecha, i1.foto
        FROM tb_impronta i1
        INNER JOIN (
          SELECT id_datadai, MAX(fecha) AS max_fecha
          FROM tb_impronta
          WHERE condicion = 1
          GROUP BY id_datadai
        ) ult ON ult.id_datadai = i1.id_datadai AND ult.max_fecha = i1.fecha
        WHERE i1.condicion = 1
      ) AS imp
        ON imp.id_datadai = d.iddatadai
      WHERE d.id_estado >= 2
      ORDER BY d.iddatadai DESC
      LIMIT 2000
    ";
    $rs = $conn->query($sql);
    if (!$rs) { echo json_encode(['success'=>false, 'message'=>'Error: '.$conn->error]); exit; }
    $rows = [];
    while ($r = $rs->fetch_assoc()) { $rows[] = $r; }
    echo json_encode(['success'=>true,'data'=>$rows]); exit;
  }

  echo json_encode(['success'=>false,'message'=>'Acción no reconocida']); exit;
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>SGO · Vehículos Impronta</title>

  <!-- CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
  <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">
  <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

  <style>
    body{ font-size:.95rem; }
    #estado2 { font-size: 12px; }
    #estado2 thead th { font-size: 12px; }
    #estado2 tbody td { font-size: 11px; vertical-align: middle; }
    .thumb-impronta { width:44px; height:44px; object-fit:cover; border-radius:6px; cursor:zoom-in; }
    .hint { font-size:.85rem; opacity:.85; }
  </style>

  <?php
    // URL absoluta de esta misma página para evitar 404 en AJAX
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $uri    = $_SERVER['REQUEST_URI'] ?? '';
    $selfAbs = htmlspecialchars($scheme.'://'.$host.$uri, ENT_QUOTES, 'UTF-8');
  ?>
</head>
<body>
<div class="container-fluid">
  <div class="row">
    <?php include 'partials/menu.php'; ?>
    <main class="col-md-9 ms-sm-auto col-lg-10 px-0">
      <?php include 'partials/topbar.php'; ?>

      <div class="row g-0">
        <div class="col-12 p-3">
          <div class="table-responsive">
            <table id="estado2" class="table table-hover table-sm w-100">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Marca</th>
                  <th>Modelo</th>
                  <th>Chasis</th>
                  <th>Color</th>
                  <th class="text-center">Impronta</th>
                  <th class="text-center">Fecha impronta</th>
                  <th class="text-center">Foto</th>
                </tr>
              </thead>
              <tbody><!-- dinámico --></tbody>
            </table>
          </div>

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

<!-- Modal Foto grande -->
<div class="modal fade" id="modalFoto" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content">
      <img id="imgModal" alt="Impronta" style="width:100%; height:auto;">
    </div>
  </div>
</div>

<!-- JS -->
<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 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://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.10/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.10/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
  const API_URL = '<?= $selfAbs ?>';

  let tabla, modalFoto;

  function verFoto(url){
    document.getElementById('imgModal').src = url;
    modalFoto.show();
  }
  window.verFoto = verFoto;

  function cargarEstado2() {
    $.get(API_URL, { action:'list_estado2' }, function(resp){
      if (!resp.success) {
        Swal.fire('Error', resp.message || 'No se pudo obtener la lista', 'error');
        return;
      }
      tabla.clear();
      resp.data.forEach(v => {
        const tieneImp = !!(v.impronta_foto && v.impronta_foto !== '');
        const badge = tieneImp
          ? '<span class="badge bg-success">Con impronta</span>'
          : '<span class="badge bg-danger">Sin impronta</span>';
        const fecha = v.impronta_fecha ?? '';
        const foto  = tieneImp
          ? `<img src="${v.impronta_foto}" class="thumb-impronta" alt="impronta" onclick="verFoto('${(v.impronta_foto||'').replace(/'/g,"\\'")}')">`
          : '<span class="text-muted">—</span>';

        tabla.row.add([
          v.iddatadai ?? '',
          v.marca ?? '',
          v.modelo ?? '',
          v.chasis ?? '',
          v.color ?? '',
          `<div class="text-center">${badge}</div>`,
          `<div class="text-center">${fecha || '—'}</div>`,
          `<div class="text-center">${foto}</div>`
        ]);
      });
      tabla.draw();
    }, 'json').fail(xhr => {
      Swal.fire('Error', xhr.responseText || 'Fallo de servidor', 'error');
    });
  }

  $(function(){
    modalFoto = new bootstrap.Modal(document.getElementById('modalFoto'));

    tabla = $('#estado2').DataTable({
      responsive: true,
      ordering: false,
      pageLength: 25,
      lengthChange: false,
      dom: 'Bfrtip',
      buttons: [
        { extend:'excelHtml5', className:'btn btn-sm btn-outline-success', title:'Vehiculos_Estado2_Impronta' },
        { extend:'pdfHtml5',   className:'btn btn-sm btn-outline-danger',  title:'Vehiculos_Estado2_Impronta', orientation:'landscape', pageSize:'A4' }
      ],
      language: { url: 'https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json' }
    });

    cargarEstado2();
  });
</script>
</body>
</html>
