<?php
// api/ingresos_list.php — Lista unidades para la tabla "DAI 70"
declare(strict_types=1);
session_start();
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../conex.php';

$db = $conn ?? ($conex ?? null);
if (!$db) { echo json_encode(['data'=>[]]); exit; }

mysqli_set_charset($db, 'utf8mb4');

$sql = "
  SELECT
    d.iddatadai,
    d.item,
    d.marca,
    d.modelo,
    d.chasis,
    d.color,
    d.id_estado,
    e.numerodai,
    MAX(t.numerotarja) AS numerotarja,
    MAX(t.numero_auto) AS numero_auto,
    COALESCE(b.sigla, b.detalle, '') AS sigla,
    es.descripcion AS estado
  FROM tb_datadai AS d
  INNER JOIN tb_daientrada   AS e  ON e.iddaientrada     = d.id_daientrada
  INNER JOIN tb_solicitudprevia AS sp ON sp.idsolicitudprevia = d.id_solicitudprevia
  INNER JOIN tb_estado       AS es ON es.idestado        = d.id_estado
  LEFT  JOIN tb_tarja        AS t  ON t.id_datadai       = d.iddatadai
  LEFT  JOIN tb_bodega       AS b  ON b.idbodega         = d.id_bodega
  WHERE d.condicion = 1
  GROUP BY
    d.iddatadai, d.item, d.marca, d.modelo, d.chasis, d.color, d.id_estado,
    e.numerodai, es.descripcion, b.sigla, b.detalle
  ORDER BY d.iddatadai DESC
";

$res = mysqli_query($db, $sql);
$data = [];
if ($res) {
  while ($r = mysqli_fetch_assoc($res)) {
    $iddatadai   = (int)$r['iddatadai'];
    $chasis      = htmlspecialchars((string)$r['chasis'] ?? '', ENT_QUOTES, 'UTF-8');

    // Botón Ver tarjas
    $btnVerTarjas =
      '<button type="button" class="btn btn-info btn-sm btn-ver-tarjas" '.
      'data-idd="'.$iddatadai.'" data-chasis="'.$chasis.'" title="Ver tarjas">'.
      '<i class="fa fa-eye"></i></button>';

    $data[] = [
      'dai70'       => htmlspecialchars((string)$r['numerodai'] ?? '', ENT_QUOTES, 'UTF-8'),
      'item'        => htmlspecialchars((string)$r['item'] ?? '', ENT_QUOTES, 'UTF-8'),
      'numerotarja' => htmlspecialchars((string)$r['numerotarja'] ?? '', ENT_QUOTES, 'UTF-8'),
      'descripcion' => htmlspecialchars((string)$r['marca'] ?? '', ENT_QUOTES, 'UTF-8'),
      'modelo'      => htmlspecialchars((string)$r['modelo'] ?? '', ENT_QUOTES, 'UTF-8'),
      'chasis'      => $chasis,
      'color'       => htmlspecialchars((string)$r['color'] ?? '', ENT_QUOTES, 'UTF-8'),
      'estado'      => htmlspecialchars((string)$r['estado'] ?? '', ENT_QUOTES, 'UTF-8'),
      'accion'      => $btnVerTarjas
    ];
  }
}
echo json_encode(['data'=>$data]);
