<?php
// views/pages/index.php — SGO · Novedades por Chasis (Vista + Layout)
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);

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 rojo con reloj -->
      <?php include 'partials/topbar.php'; ?>

      <!-- === Novedades por Chasis (Vista) === -->
      <section class="p-2 p-md-3">
        <div class="d-flex justify-content-between align-items-center mb-2">
          <h5 class="mb-0"><i class="fa-solid fa-clipboard-list"></i> Novedades por Chasis</h5>
        </div>

        <!-- Filtros -->
        <div class="card mb-2">
          <div class="card-body py-2">
            <div class="row g-2 align-items-end">
              <div class="col-lg-5">
                <label class="form-label mb-1">Chasis (múltiples: coma o espacio)</label>
                <input id="f-chasis" type="text" class="form-control form-control-sm" placeholder="Ej: 8A1BCD... 9ZZ... , ABC123">
                <div id="chips" class="mt-1"></div>
              </div>
              <div class="col-lg-3">
                <label class="form-label mb-1">Búsqueda general</label>
                <input id="f-search" type="text" class="form-control form-control-sm" placeholder="Marca, modelo, parte, zona…">
              </div>
              <div class="col-lg-4">
                <div class="row g-2">
                  <div class="col-4">
                    <div class="form-check form-switch mt-4">
                      <input class="form-check-input" type="checkbox" id="f-grave">
                      <label class="form-check-label small" for="f-grave">Solo graves</label>
                    </div>
                  </div>
                  <div class="col-4">
                    <div class="form-check form-switch mt-4">
                      <input class="form-check-input" type="checkbox" id="f-validar">
                      <label class="form-check-label small" for="f-validar">Solo validados</label>
                    </div>
                  </div>
                  <div class="col-4">
                    <div class="form-check form-switch mt-4">
                      <input class="form-check-input" type="checkbox" id="f-condicion">
                      <label class="form-check-label small" for="f-condicion">Solo activos</label>
                    </div>
                  </div>
                </div>
              </div>

              <div class="col-12 text-end">
                <button id="btn-limpiar" class="btn btn-outline-secondary btn-sm">
                  <i class="fa-solid fa-eraser"></i> Limpiar
                </button>
                <button id="btn-buscar" class="btn btn-danger btn-sm">
                  <i class="fa-solid fa-magnifying-glass"></i> Buscar
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Tabla -->
        <div class="card">
          <div class="card-body p-2">
            <div class="table-responsive">
              <table id="tabla-nov" class="table table-striped table-bordered table-sm w-100">
                <thead class="table-light">
                  <tr>
                    <th>Chasis</th>
                    <th>Marca/Modelo/Color</th>
                    <th>Zona</th>
                    <th>Parte</th>
                    <th>Novedad</th>
                    <th>Medida</th>
                    <th>Observación</th>
                    <th>Tarja</th>
                    <th>Resp.</th>
                    <th>Validado</th>
                    <th>Grave</th>
                    <th>Foto</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
            <small class="text-muted">Tip: escribe varios chasis separados por espacios o comas.</small>
          </div>
        </div>
      </section>

      <!-- Modal Foto -->
      <div class="modal fade" id="fotoModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
          <div class="modal-content">
            <div class="modal-header py-2">
              <h6 class="modal-title mb-0"><i class="fa-regular fa-image"></i> Foto del incidente</h6>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body text-center">
              <img id="fotoFull" src="" alt="Foto" style="max-width:100%;max-height:70vh;border-radius:8px;border:1px solid #ddd;">
            </div>
          </div>
        </div>
      </div>

      <!-- Estilos mínimos -->
      <style>
        #tabla-nov thead th{ white-space:nowrap; }
        #tabla-nov img.thumb{ width:40px; height:40px; object-fit:cover; border-radius:6px; border:1px solid #ddd; }
        #chips .chip{ display:inline-block; background:#e9ecef; border-radius:999px; padding:.15rem .5rem; font-size:.8rem; margin:.05rem; }
        body, table{ font-size: 0.97rem; }
      </style>

      <!-- Dependencias (si ya están en header.php, puedes quitar estas líneas) -->
      <link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css">
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.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(){
        // Ruta al API (relativa a views/pages/index.php)
        const API_URL = '/api/novedades_chasis_api.php';

        const $tabla   = $('#tabla-nov');
        const $fChasis = $('#f-chasis');
        const $fSearch = $('#f-search');
        const $fGrave  = $('#f-grave');
        const $fValidar= $('#f-validar');
        const $fCond   = $('#f-condicion');
        const $chips   = $('#chips');

        function parseChasisList(){
          const raw = $fChasis.val().trim();
          if(!raw) return [];
          return [...new Set(raw.split(/[,\s]+/).map(s=>s.trim()).filter(Boolean))];
        }
        function renderChips(){
          const arr = parseChasisList();
          $chips.empty();
          arr.forEach(c=>{
            const el = $('<span class="chip"></span>').text(c).attr('data-c', c);
            el.append(' ');
            const x = $('<i class="fa-solid fa-xmark" style="cursor:pointer;"></i>');
            x.on('click', ()=>{
              const left = parseChasisList().filter(v=>v!==c);
              $fChasis.val(left.join(' '));
              renderChips();
            });
            el.append(x);
            $chips.append(el);
          });
        }
        $fChasis.on('input', renderChips); renderChips();

        const dt = $tabla.DataTable({
          processing: true,
          serverSide: false, // Cambia a true + d.mode='dt' si tienes muchísimos registros
          pageLength: 25,
          ajax: {
            url: API_URL,
            data: function(d){
              d.ajax = '1';
              // d.mode = 'dt'; // <- si activas serverSide arriba
              d.chasis_list = parseChasisList().join(' ');
              d.search      = $fSearch.val().trim();
              d.grave       = $fGrave.is(':checked')   ? '1' : '';
              d.validar     = $fValidar.is(':checked') ? '1' : '';
              d.condicion   = $fCond.is(':checked')    ? '1' : ''; // se filtra, pero ya no se muestra columna
            },
            dataSrc: function(json){
              if(!json || !json.success){ console.error(json); return []; }
              return json.data || [];
            }
          },
          columns: [
            { data: 'chasis', render: (d)=>`<strong>${d||''}</strong>` },
            { data: null, render: (row)=>`${row.marca||''} / ${row.modelo||''} / ${row.color||''}` },
            { data: 'zona', defaultContent: '' },
            { data: 'parte', defaultContent: '' },
            { data: 'novedad', defaultContent: '' },
            { data: 'medida', defaultContent: '' },
            { data: 'observacion', defaultContent: '' },
            { data: 'id_tarja', render: d => d? d : '' },
            { // Resp. (1 = Sí; 0 o null = No)
              data: 'reponsabilidad',
              render: d => (String(d) === '1')
                ? '<span class="badge bg-success">Sí</span>'
                : '<span class="badge bg-secondary">No</span>'
            },
            { // Validado
              data: 'validar',
              render: d => (String(d) === '1')
                ? '<span class="badge bg-success">Sí</span>'
                : '<span class="badge bg-secondary">No</span>'
            },
            { // Grave
              data: 'grave',
              render: d => (String(d) === '1')
                ? '<span class="badge bg-danger">Grave</span>'
                : '<span class="badge bg-secondary">No</span>'
            },
            { // Foto
              data: 'foto',
              orderable:false,
              render: (d)=>{
                if(!d) return '';
                const esc = String(d).replace(/"/g,'&quot;');
                return `<img src="${esc}" class="thumb" alt="foto" onerror="this.style.display='none';" data-foto="${esc}">`;
              }
            },
          ],
          order: [[0,'asc']],
          language: { url: 'https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json' }
        });

        $('#btn-buscar').on('click', ()=> dt.ajax.reload());
        $('#btn-limpiar').on('click', ()=>{
          $fChasis.val(''); $fSearch.val('');
          $fGrave.prop('checked',false); $fValidar.prop('checked',false); $fCond.prop('checked',false);
          renderChips(); dt.ajax.reload();
        });

        // Modal foto
        const fotoModal = new bootstrap.Modal(document.getElementById('fotoModal'));
        $tabla.on('click', 'img.thumb', function(){
          document.getElementById('fotoFull').src = this.getAttribute('data-foto') || this.src;
          fotoModal.show();
        });
      })();
      </script>
    </main>
  </div>
</div>

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