<?php
// api/dai_programar.php — Fuente DataTables basada en tu SELECT
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors','0');

set_error_handler(function($n,$s,$f,$l){
  http_response_code(500);
  echo json_encode(['data'=>[], 'success'=>false, 'message'=>"PHP:$n $s @ $f:$l"]); exit;
});
set_exception_handler(function($e){
  http_response_code(500);
  echo json_encode(['data'=>[], 'success'=>false, 'message'=>$e->getMessage()]); exit;
});

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

require_once __DIR__ . '/../conex.php';
if (!isset($conn) || !($conn instanceof mysqli)) { throw new RuntimeException('Sin conexión a BD'); }
mysqli_set_charset($conn,'utf8mb4');
@$conn->query("SET time_zone='-05:00'");

// === TU CONSULTA (con pequeños formateos/alias) ===
$sql = "
  SELECT 
    d.iddatadai,
    dt.nombre            AS destino,
    t.nombre             AS transportista,
    p.`status`,
    d.marca, d.modelo, d.chasis, d.color, d.pedido, d.origen_localidad,
    e.descripcion        AS estado,
    d.origen,
    p.id                 AS id_asignar,
    p.tipo, p.grupo, p.placa, p.numero_doc, p.conductor,
    DATE_FORMAT(p.fecha_carga,    '%Y-%m-%d %H:%i') AS fecha_carga,
    DATE_FORMAT(p.fecha_descarga, '%Y-%m-%d %H:%i') AS fecha_descarga,
    p.guia, p.enlace_rastreo
  FROM tb_datadai            AS d
  INNER JOIN tb_estado       AS e  ON e.idestado = d.id_estado
  INNER JOIN tb_asignar_datadai AS a ON a.id_datadai = d.iddatadai
  INNER JOIN tb_asignar      AS p  ON p.id = a.id_asignar
  INNER JOIN tb_destino      AS dt ON dt.id = p.destino
  INNER JOIN tb_transporte   AS t  ON t.id = p.transportista
  WHERE d.dai = 'Simple'
    AND d.condicion = 1
    AND d.id_estado <= 2
  ORDER BY p.id DESC, d.iddatadai DESC
  LIMIT 1000
";
$res = $conn->query($sql);

$data = [];
while ($row = $res->fetch_assoc()) {
  $idAsignar = (int)$row['id_asignar'];

  // checkbox por fila (valor = id de tb_asignar)
  $check = '<input type="checkbox" class="form-check-input check-row" '.
           'value="'.$idAsignar.'" '.
           'data-gestion="'.$idAsignar.'" '.
           'data-chasis="'.htmlspecialchars($row['chasis']??'',ENT_QUOTES).'" '.
           'data-color="'.htmlspecialchars($row['color']??'',ENT_QUOTES).'" '.
           'data-modelo="'.htmlspecialchars($row['modelo']??'',ENT_QUOTES).'" '.
           'data-marca="'.htmlspecialchars($row['marca']??'',ENT_QUOTES).'" '.
           '/>';

  $accion = '<div class="btn-group btn-group-sm">'.
              '<button class="btn btn-outline-primary btn-rastreo" data-id="'.$idAsignar.'"><i class="fa fa-link"></i></button>'.
            '</div>';

  $data[] = [
    'check'         => $check,
    'tipo'          => $row['tipo'] ?? '',
    'grupo'         => $row['grupo'] ?? '',
    'chasis'        => $row['chasis'] ?? '',
    'color'         => $row['color'] ?? '',
    'modelo'        => $row['modelo'] ?? '',
    'marca'         => $row['marca'] ?? '',
    'pedido'        => $row['pedido'] ?? '',
    'localidad'     => $row['origen_localidad'] ?? '',
    'destino'       => $row['destino'] ?? '',
    'transportista' => $row['transportista'] ?? '',
    'placa'         => $row['placa'] ?? '',
    'conductor'     => $row['conductor'] ?? '',
    'cedula'        => $row['numero_doc'] ?? '',
    'carga'         => $row['fecha_carga'] ?? '',
    'descarga'      => $row['fecha_descarga'] ?? '',
    'status'        => $row['status'] ?? '',
    'guia'          => $row['guia'] ?? '',
    'link'          => !empty($row['enlace_rastreo']) ? '<a href="'.htmlspecialchars($row['enlace_rastreo'],ENT_QUOTES).'" target="_blank">Abrir</a>' : '',
    'accion'        => $accion
  ];
}

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