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

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

$q          = trim((string)($_GET['q'] ?? ''));
$onlyActive = isset($_GET['onlyActive']) ? (int)$_GET['onlyActive'] : 1;
$limit      = max(1, (int)($_GET['limit'] ?? 200));

$sql = "SELECT a.id_accesorio,
               a.sku,
               a.nombre,
               IFNULL(a.condicion,1) AS condicion
        FROM tb_inv_accesorio a
        WHERE 1=1";

$params = []; $types = '';

if ($onlyActive === 1) {
  $sql .= " AND IFNULL(a.condicion,1)=1";
}

if ($q !== '') {
  $sql .= " AND (a.sku LIKE CONCAT('%',?,'%') OR a.nombre LIKE CONCAT('%',?,'%'))";
  $params[] = $q; $params[] = $q; $types .= 'ss';
}

$sql .= " ORDER BY a.sku ASC, a.nombre ASC LIMIT ?";
$params[] = $limit; $types .= 'i';

$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[] = [
    'id_accesorio' => (int)$row['id_accesorio'],
    'sku'          => $row['sku'],
    'nombre'       => $row['nombre'],
    'text'         => trim($row['sku'].' - '.$row['nombre']),
    'condicion'    => (int)$row['condicion'],
  ];
}

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