<?php
// api/modelo_list.php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

session_start();
require_once __DIR__ . '/../conex.php';
mysqli_set_charset($conn,'utf8mb4');

$search = trim((string)($_GET['search'] ?? ''));
$id_marca = (int)($_GET['id_marca'] ?? 0);

$sql = "SELECT mo.id_modelo, mo.id_marca, ma.nombre AS marca_nombre,
               mo.nombre, mo.anio, IFNULL(mo.condicion,1) AS condicion
        FROM tb_inv_modelo mo
        JOIN tb_inv_marca ma ON ma.id_marca = mo.id_marca
        WHERE 1=1";
$params = []; $types = '';

if ($id_marca > 0) {
  $sql .= " AND mo.id_marca = ?";
  $params[] = $id_marca; $types .= 'i';
}
if ($search !== '') {
  $sql .= " AND (ma.nombre LIKE CONCAT('%',?,'%') OR mo.nombre LIKE CONCAT('%',?,'%') OR CAST(mo.anio AS CHAR) LIKE CONCAT('%',?,'%'))";
  $params[] = $search; $params[] = $search; $params[] = $search; $types .= 'sss';
}
$sql .= " ORDER BY ma.nombre ASC, mo.nombre ASC, mo.anio DESC";

$stmt = mysqli_prepare($conn, $sql);
if ($params) mysqli_stmt_bind_param($stmt, $types, ...$params);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);

$data = [];
while ($row = mysqli_fetch_assoc($res)) $data[] = $row;
echo json_encode(['success'=>true,'data'=>$data]);
