<?php
// views/pages/repor_novedad.php — Reporte de Novedades (server-side, filtros en encabezado, SIN Tarja)
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">

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

    <main class="col-md-9 ms-sm-auto col-lg-10 px-0">
      <?php include 'partials/topbar.php'; ?>

      <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> Reporte de Novedades</h5>
        </div>

        <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>

        <div class="card">
          <div class="card-body p-2">
            <div class="table-responsive">
              <table id="tabla-reporte" 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>Resp.</th>
                    <th>Validado</th>
                    <th>Grave</th>
                    <th>Foto</th>
                  </tr>
                  <tr id="filters-row">
                    <th><input type="text" class="form-control form-control-sm" placeholder="Filtrar chasis"></th>
                    <th><input type="text" class="form-control form-control-sm" placeholder="Marca/Modelo/Color"></th>
                    <th><input type="text" class="form-control form-control-sm" placeholder="Zona"></th>
                    <th><input type="text" class="form-control form-control-sm" placeholder="Parte"></th>
                    <th><input type="text" class="form-control form-control-sm" placeholder="Novedad"></th>
                    <th><input type="text" class="form-control form-control-sm" placeholder="Medida"></th>
                    <th><input type="text" class="form-control form-control-sm" placeholder="Observación"></th>
                    <th>
                      <select class="form-select form-select-sm">
                        <option value="">Todos</option>
                        <option value="1">Sí</option>
                        <option value="0">No</option>
                      </select>
                    </th>
                    <th>
                      <select class="form-select form-select-sm">
                        <option value="">Todos</option>
                        <option value="1">Sí</option>
                        <option value="0">No</option>
                      </select>
                    </th>
                    <th>
                      <select class="form-select form-select-sm">
                        <option value="">Todos</option>
                        <option value="1">Grave</option>
                        <option value="0">Normal</option>
                      </select>
                    </th>
                    <th></th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
            <small class="text-muted">Tip: combina filtros del encabezado con los globales.</small>
          </div>
        </div>
      </section>

      <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>

      <style>
        #tabla-reporte thead th{ white-space:nowrap; vertical-align:middle; }
        #tabla-reporte #filters-row th { background:#f8f9fa; }
        #chips .chip{ display:inline-block; background:#e9ecef; border-radius:999px; padding:.15rem .5rem; font-size:.8rem; margin:.05rem; }
        #tabla-reporte .badge{ font-weight:500; }
        body, table{ font-size: 0.97rem; }
      </style>

      <!-- Dependencias (si ya están en header.php, elimina 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(){
        "use strict";

        var API_URL = 'api/novedades_chasis_api.php';

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

        function parseChasisList(){
          var raw = $fChasis.val().trim();
          if(!raw) return [];
          return Array.from(new Set(raw.split(/[,\s]+/).map(function(s){ return s.trim(); }).filter(Boolean)));
        }

        function renderChips(){
          var arr = parseChasisList();
          $chips.empty();
          arr.forEach(function(c){
            var el = $('<span class="chip"></span>').text(c).attr('data-c', c);
            el.append(' ');
            var x = $('<i class="fa-solid fa-xmark" style="cursor:pointer;"></i>');
            x.on('click', function(){
              var left = parseChasisList().filter(function(v){ return v !== c; });
              $fChasis.val(left.join(' '));
              renderChips();
            });
            el.append(x);
            $chips.append(el);
          });
        }
        $fChasis.on('input', renderChips);
        renderChips();

        var dt = $tabla.DataTable({
          processing: true,
          serverSide: true,
          orderCellsTop: true,
          pageLength: 25,
          ajax: {
            url: API_URL,
            data: function(d){
              d.ajax = '1';
              d.mode = 'dt';
              d.chasis_list = parseChasisList().join(' ');
              d.search      = $fSearch.val() ? $fSearch.val().trim() : '';
              d.grave       = $fGrave.is(':checked')   ? '1' : '';
              d.validar     = $fValidar.is(':checked') ? '1' : '';
              d.condicion   = $fCond.is(':checked')    ? '1' : '';
            },
            dataSrc: 'data'
          },
          columns: [
            { data: 'chasis', render: function(d){ return '<strong>'+(d||'')+'</strong>'; } }, // 0
            { data: null, render: function(row){ return (row.marca||'')+' / '+(row.modelo||'')+' / '+(row.color||''); } }, // 1
            { data: 'zona', defaultContent: '' },        // 2
            { data: 'parte', defaultContent: '' },       // 3
            { data: 'novedad', defaultContent: '' },     // 4
            { data: 'medida', defaultContent: '' },      // 5
            { data: 'observacion', defaultContent: '' }, // 6
            { // 7 reponsabilidad
              data: 'reponsabilidad',
              render: function(d){
                return (String(d) === '1')
                  ? '<span class="badge bg-success">Sí</span>'
                  : '<span class="badge bg-secondary">No</span>';
              }
            },
            { // 8 validar
              data: 'validar',
              render: function(d){
                return (String(d) === '1')
                  ? '<span class="badge bg-success">Sí</span>'
                  : '<span class="badge bg-secondary">No</span>';
              }
            },
            { // 9 grave
              data: 'grave',
              render: function(d){
                return (String(d) === '1')
                  ? '<span class="badge bg-danger">Grave</span>'
                  : '<span class="badge bg-secondary">Normal</span>';
              }
            },
            { // 10 foto
              data: 'foto',
              orderable: false,
              render: function(d){
                if (!d) return '';
                var esc = String(d).replace(/"/g,'&quot;');
                return '<button type="button" class="btn btn-sm btn-outline-primary ver-foto" data-foto="'+esc+'">'+
                         '<i class="fa-regular fa-image"></i> Ver'+
                       '</button>';
              }
            }
          ],
          order: [[0,'asc']],
          language: { url: 'https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json' },
          initComplete: function(){
            var api = this.api();
            api.columns().every(function(colIdx){
              var th = $('#filters-row th').eq(colIdx);
              var $input = th.find('input');
              var $select = th.find('select');

              if ($input.length) {
                $input.on('keyup change', function(){
                  api.column(colIdx).search(this.value || '').draw();
                });
              }
              if ($select.length) {
                $select.on('change', function(){
                  var v = this.value;
                  if (v === '') {
                    api.column(colIdx).search('').draw();
                  } else {
                    api.column(colIdx).search('^'+v+'$', true, false).draw(); // igualdad exacta 0/1
                  }
                });
              }
            });
          }
        });

        $('#btn-buscar').on('click', function(){ dt.ajax.reload(); });

        $('#btn-limpiar').on('click', function(){
          $fChasis.val(''); $fSearch.val('');
          $fGrave.prop('checked', false);
          $fValidar.prop('checked', false);
          $fCond.prop('checked', false);
          renderChips();
          $('#filters-row input').val('');
          $('#filters-row select').prop('selectedIndex', 0);
          dt.columns().search('');
          dt.search('');
          dt.ajax.reload();
        });

        var fotoModalEl = document.getElementById('fotoModal');
        var fotoModal = new bootstrap.Modal(fotoModalEl);
        var fotoImg = document.getElementById('fotoFull');

        $tabla.on('click', 'button.ver-foto', function(){
          var src = this.getAttribute('data-foto') || '';
          fotoImg.src = src;
          fotoModal.show();
        });

        fotoModalEl.addEventListener('hidden.bs.modal', function(){
          fotoImg.src = '';
        });

      })();
      </script>
    </main>

  </div>
</div>

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