<?php
// api/dai_simple.php — DataSource para DataTable del módulo SIMPLE
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');

session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  echo json_encode(['data'=>[], 'success'=>false, 'message'=>'No autorizado']); exit;
}

/* Conexión */
$pathConex = realpath(__DIR__ . '/../conex.php') ?: realpath(__DIR__ . '/../../conex.php');
if (!$pathConex) { echo json_encode(['data'=>[], 'success'=>false, 'message'=>'No se encontró conex.php']); exit; }
require_once $pathConex;

$db = $conn ?? ($conex ?? null);
if (!$db instanceof mysqli) { echo json_encode(['data'=>[], 'success'=>false, 'message'=>'Sin conexión BD']); exit; }
mysqli_set_charset($db, 'utf8mb4');

/*
  Tabla esperada: tb_datadai
  Campos usados (ajusta si tus nombres difieren):
    iddatadai (PK), origen, pedido, naviera, regimen, marca, modelo, chasis, color, impronta,
    id_estado (FK a tb_estado.idestado), condicion (1 activo), dai ('Simple')
*/
$sql = "SELECT 
          d.iddatadai      AS id,
          d.origen,
          d.pedido,
          d.naviera,
          d.dai            AS regimen,   -- <<<<<<<<<<<<<< AQUI el cambio (antes: d.regimen)
          d.marca,
          d.modelo,
          d.chasis,
          d.color,
          d.impronta,
          e.descripcion    AS estado
        FROM tb_datadai d
        LEFT JOIN tb_estado e ON e.idestado = d.id_estado
        WHERE d.condicion = 1 AND d.dai = 'Simple'
        ORDER BY d.iddatadai DESC
        LIMIT 5000";


$res = $db->query($sql);
$data = [];

if ($res) {
  while ($r = $res->fetch_assoc()) {
    $id      = (int)$r['id'];
    $chasis  = htmlspecialchars($r['chasis'] ?? '', ENT_QUOTES,'UTF-8');
    $marca   = htmlspecialchars($r['marca'] ?? '', ENT_QUOTES,'UTF-8');
    $modelo  = htmlspecialchars($r['modelo'] ?? '', ENT_QUOTES,'UTF-8');
    $color   = htmlspecialchars($r['color'] ?? '', ENT_QUOTES,'UTF-8');

    $check = '<input type="checkbox" class="form-check-input check-row"'
           . ' value="'.$id.'"'
           . ' data-chasis="'.$chasis.'"'
           . ' data-marca="'.$marca.'"'
           . ' data-modelo="'.$modelo.'"'
           . ' data-color="'.$color.'"'
           . ' />';

    $improntaBadge = '';
    $imp = trim((string)($r['impronta'] ?? ''));
    if ($imp !== '') {
      $improntaBadge = '<span class="badge text-bg-'.(($imp==='SI'||$imp==='1')?'success':'secondary').'">'
                     . htmlspecialchars($imp, ENT_QUOTES,'UTF-8')
                     . '</span>';
    }

    $btnEliminar = '<button class="btn btn-sm btn-danger btn-eliminar"'
                 . ' data-id="'.$id.'"'
                 . ' data-chasis="'.$chasis.'"'
                 . ' title="Eliminar">'
                 . '<i class="fa fa-trash"></i></button>';

    $data[] = [
      'check'    => '<div class="d-flex justify-content-center">'.$check.'</div>',
      'origen'   => htmlspecialchars($r['origen'] ?? '', ENT_QUOTES,'UTF-8'),
      'pedido'   => htmlspecialchars($r['pedido'] ?? '', ENT_QUOTES,'UTF-8'),
      'naviera'  => htmlspecialchars($r['naviera'] ?? '', ENT_QUOTES,'UTF-8'),
      'regimen'  => htmlspecialchars($r['regimen'] ?? '', ENT_QUOTES,'UTF-8'),
      'marca'    => $marca,
      'modelo'   => $modelo,
      'chasis'   => $chasis,
      'color'    => $color,
      'impronta' => $improntaBadge,
      'estado'   => htmlspecialchars($r['estado'] ?? '', ENT_QUOTES,'UTF-8'),
      'accion'   => '<div class="d-flex justify-content-center gap-1">'.$btnEliminar.'</div>',
    ];
  }
}

echo json_encode(['data'=>$data, 'success'=>true]);
