<?php
session_start();
header('Content-Type: application/json');
include("../conex.php");

$id_usuario = $_SESSION['idusuario'] ?? 0;

if (!$conn) {
    echo json_encode(['error' => 'Error de conexión a la base de datos']);
    exit;
}

$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
            FROM tb_datadai as d
            INNER JOIN tb_estado as e ON e.idestado = d.id_estado
            LEFT JOIN tb_asignar_datadai AS a ON a.id_datadai = d.iddatadai
            LEFT JOIN tb_asignar AS p ON p.id= a.id_asignar
            LEFT JOIN tb_destino AS dt ON dt.id = p.destino
            LEFT JOIN tb_transporte AS t ON t.id = p.transportista
            WHERE d.dai = 'Simple' AND d.condicion = 1 AND d.id_estado <= 2
            ";

$result = mysqli_query($conn, $sql);
if (!$result) {
    echo json_encode(['error' => 'Error en la consulta: ' . mysqli_error($conn)]);
    exit;
}

$data = [];
while ($row = mysqli_fetch_assoc($result)) {
    

   $eliminar = '<button 
                    class="btn btn-danger btn-sm btn-eliminar" 
                    data-id="' . $row['iddatadai'] . '" 
                    data-chasis="' . htmlspecialchars($row['chasis']) . '">
                    <i class="fa fa-trash"></i>
                </button>';


   $check = '<label class="d-flex align-items-center gap-2">
              <input type="checkbox" class="check-row" style="width: 20px; height: 20px;"
                value="' . $row['iddatadai'] . '" 
                data-chasis="' . htmlspecialchars($row['chasis']) . '" 
                data-color="' . htmlspecialchars($row['color']) . '" 
                data-modelo="' . htmlspecialchars($row['modelo']) . '" 
                data-marca="' . htmlspecialchars($row['marca']) . '">
              
            </label>';


    $data[] = [
        'check'             => $check,        
        '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'],
        'status'            => $row['status'],
        'accion'            => ''
    ];
}

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