<?php
// api/categoria_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(); // opcional: valida si usas login
// if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') { http_response_code(401); echo json_encode(['success'=>false,'message'=>'No autorizado']); exit; }

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

$soloActivos = isset($_GET['soloActivos']) ? (int)$_GET['soloActivos'] : 0;
$search = trim((string)($_GET['search'] ?? ''));
$params = [];
$sql = "SELECT id_categoria, nombre, condicion FROM tb_inv_categoria WHERE 1=1";

if ($soloActivos === 1) {
  $sql .= " AND condicion = 1";
}
if ($search !== '') {
  $sql .= " AND nombre LIKE CONCAT('%',?,'%')";
  $params[] = $search;
}

$sql .= " ORDER BY nombre ASC";
$stmt = mysqli_prepare($conn, $sql);
if ($params) {
  $types = str_repeat('s', count($params));
  mysqli_stmt_bind_param($stmt, $types, ...$params);
}
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

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