<?php
// index.php — Lavado express (PDS) con switch basado en tb_datadai.lavada
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"; // ajusta la ruta si aplica
?>
<?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="p-2">
        <div class="card shadow-sm">
          <div class="card-header py-2 d-flex align-items-center justify-content-between">
            <div>
              <i class="fa-solid fa-soap me-2"></i> Lavado express (PDS)
            </div>
          </div>

          <div class="card-body p-2">
            <div class="table-responsive">
              <table id="lava" class="table table-striped table-hover table-sm w-100">
                <thead class="table-info">
                  <tr>
                    <th>Régimen</th>
                    <th>Marca</th>
                    <th>Modelo</th>
                    <th>Nº de Chasis</th>
                    <th>Nº de Motor</th>
                    <th>Color</th>
                    <th>Lavado express</th>
                    <th>Acción</th>
                  </tr>
                </thead>
                <tbody><!-- AJAX --></tbody>
              </table>
            </div>
          </div>

        </div>
      </div>

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

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

<!-- ====== Librerías necesarias ====== -->
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- Bootstrap 5 Bundle -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- DataTables + Buttons + Responsive (BS5) -->
<link rel="stylesheet" href="https://cdn.datatables.net/v/bs5/jszip-3.10.1/dt-1.13.8/b-2.4.2/b-colvis-2.4.2/b-html5-2.4.2/b-print-2.4.2/r-2.5.0/datatables.min.css"/>
<script src="https://cdn.datatables.net/v/bs5/jszip-3.10.1/dt-1.13.8/b-2.4.2/b-colvis-2.4.2/b-html5-2.4.2/b-print-2.4.2/r-2.5.0/datatables.min.js"></script>

<script>
$(function() {
  /* ====== DataTable ====== */
  const dt = $('#lava').DataTable({
    ajax: {
      url: 'api/lavado_list.php',   // Debe devolver {data:[...]} y la columna 'lavada_switch'
      type: 'GET',
      dataSrc: 'data',
      error: function (xhr, status, err) {
        console.error('DT AJAX error:', status, err, xhr?.responseText);
        alert('No se pudo cargar la tabla (ver consola del navegador).');
      }
    },
    columns: [
      { data: 'regimen' },
      { data: 'marca' },
      { data: 'modelo' },
      { data: 'chasis' },
      { data: 'motor' },
      { data: 'color' },
      { data: 'lavada_switch', orderable: false, className: 'text-center' }, // ← switch según tb_datadai.lavada
      { data: 'accion',        orderable: false, className: 'text-center' }
    ],
    responsive: true,
    deferRender: true,
    pageLength: 25,
    language: { url: 'https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json' }
  });

  /* ====== Re-init tooltips cuando se dibuja ====== */
  $('#lava').on('draw.dt', function() {
    document.querySelectorAll('#lava [data-bs-toggle="tooltip"]').forEach(el => {
      new bootstrap.Tooltip(el);
    });
  });

  /* ====== Handler del switch (ON/OFF) ====== */
  $(document).on('change', '.toggle-express', async function () {
    const $chk = $(this);
    const id   = $chk.data('id');
    const on   = $chk.is(':checked') ? 1 : 0;

    if (!id) { alert('ID inválido'); return; }

    $chk.prop('disabled', true);
    try {
      const resp = await fetch('api/lavado_toggle.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json;charset=utf-8' },
        body: JSON.stringify({ iddatadai: id, express: on })
      });
      const data = await resp.json();
      if (!resp.ok || !data?.success) {
        throw new Error(data?.message || 'No se pudo actualizar el estado de lavado');
      }
      // Refresca la fila/tabla para mantener consistencia visual
      dt.ajax.reload(null, false);
    } catch (e) {
      // Revertir visualmente si falló
      $chk.prop('checked', !on);
      alert(e.message || 'Error al actualizar Lavado express');
    } finally {
      $chk.prop('disabled', false);
    }
  });
});
</script>

<style>
/* Opcional: afinar tamaño de la perilla del switch en tablas compactas */
.form-check.form-switch .form-check-input {
  cursor: pointer;
}
</style>
</body>
</html>
