<?php
// api/lavado_list.php — listado para DataTable Lavado express (PDS) — switch según tb_datadai.lavada
declare(strict_types=1);

ob_start();
header('Content-Type: application/json; charset=UTF-8');

try {
  session_start();
  if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
    http_response_code(401);
    echo json_encode(['data' => [], 'error' => 'No autorizado']);
    exit;
  }

  require_once __DIR__ . '/../conex.php';
  if (!isset($conn) || !($conn instanceof mysqli)) {
    throw new RuntimeException('Conexión $conn no disponible.');
  }
  mysqli_set_charset($conn, 'utf8mb4');

  /*
    Traemos datos del vehículo + el flag d.lavada.
    (Si quieres quitar los JOIN extra, puedes dejar solo tb_datadai + tb_estado)
  */
  $sql = "
    SELECT
      d.iddatadai,
      d.dai       AS regimen,
      d.marca,
      d.modelo,
      d.chasis,
      d.motor,
      d.color,
      d.lavada,         -- << flag (0/1/NULL)
      es.descripcion AS estado_desc
    FROM tb_datadai AS d
    INNER JOIN tb_estado AS es
            ON es.idestado = d.id_estado
    WHERE d.dai = 'Simple'
      AND d.id_estado >= 2
      AND d.id_estado < 22
      AND d.condicion = 1
    ORDER BY d.iddatadai DESC
  ";

  $data = [];
  $res = $conn->query($sql);
  if ($res === false) {
    throw new RuntimeException('Error en la consulta: ' . $conn->error);
  }

  while ($row = $res->fetch_assoc()) {
    $iddatadai = (int)($row['iddatadai'] ?? 0);
    $regimen   = $row['regimen'] ?? '';
    $marca     = $row['marca']   ?? '';
    $modelo    = $row['modelo']  ?? '';
    $chasis    = $row['chasis']  ?? '';
    $motor     = $row['motor']   ?? '';
    $color     = $row['color']   ?? '';
    $lavadaVal = isset($row['lavada']) ? (int)$row['lavada'] : 0; // null -> 0

    // ON si lavada = 1; OFF si 0 o NULL
    $isOn = ($lavadaVal === 1);

    // HTML del switch (Bootstrap 5)
    $switch = '<div class="form-check form-switch d-inline-block">'
            . '  <input class="form-check-input toggle-express" type="checkbox"'
            . '         data-id="' . $iddatadai . '"'
            . ($isOn ? ' checked' : '')
            . '         title="Activar/desactivar Lavado express">'
            . '</div>';

    // Botones extra (opcional)
    $btnGestion = '<a href="lavado_gestionar.php?id=' . $iddatadai . '" '
                . 'class="btn btn-sm btn-primary me-1" '
                . 'data-bs-toggle="tooltip" title="Registrar/Editar Lavado">'
                . '<i class="fa-solid fa-spray-can-sparkles"></i></a>';

    $btnHist = '<a href="lavado_historial.php?id=' . $iddatadai . '" '
             . 'class="btn btn-sm btn-outline-secondary" '
             . 'data-bs-toggle="tooltip" title="Ver historial de lavados">'
             . '<i class="fa-regular fa-clock"></i></a>';

    $data[] = [
      'regimen'       => htmlspecialchars($regimen, ENT_QUOTES, 'UTF-8'),
      'marca'         => htmlspecialchars($marca,   ENT_QUOTES, 'UTF-8'),
      'modelo'        => htmlspecialchars($modelo,  ENT_QUOTES, 'UTF-8'),
      'chasis'        => htmlspecialchars($chasis,  ENT_QUOTES, 'UTF-8'),
      'motor'         => htmlspecialchars($motor,   ENT_QUOTES, 'UTF-8'),
      'color'         => htmlspecialchars($color,   ENT_QUOTES, 'UTF-8'),
      'lavada_switch' => $switch,
      'accion'        => $btnHist
    ];
  }
  $res->free();

  ob_clean();
  echo json_encode(['data' => $data], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
  http_response_code(500);
  if (ob_get_length()) { ob_clean(); }
  echo json_encode(['data' => [], 'error' => 'Exception: ' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
