<?php
// api/ingreso_refdata.php — Catálogos para ingreso de accesorio
declare(strict_types=1);
ini_set('display_errors','0'); ini_set('log_errors','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');

function column_exists(mysqli $c, string $t, string $col): bool {
  $sql="SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1";
  $st=mysqli_prepare($c,$sql); mysqli_stmt_bind_param($st,'ss',$t,$col); mysqli_stmt_execute($st); mysqli_stmt_store_result($st);
  $ok = mysqli_stmt_num_rows($st)>0; mysqli_stmt_close($st); return $ok;
}

try{
  // si piden modelos por marca
  if (isset($_GET['modelos'])) {
    $id_marca = (int)($_GET['id_marca'] ?? 0);
    $mods = [];
    if ($id_marca>0){
      $q = mysqli_query($conn,"SELECT id_modelo, nombre FROM tb_inv_modelo WHERE id_marca={$id_marca} AND IFNULL(condicion,1)=1 ORDER BY nombre");
      while($r=mysqli_fetch_assoc($q)){ $mods[]=['id_modelo'=>(int)$r['id_modelo'],'nombre'=>$r['nombre']]; }
    }
    echo json_encode(['success'=>true,'modelos'=>$mods]); exit;
  }

  // categorías
  $categorias=[];
  $qc=mysqli_query($conn,"SELECT id_categoria, nombre FROM tb_inv_categoria WHERE IFNULL(condicion,1)=1 ORDER BY nombre");
  while($r=mysqli_fetch_assoc($qc)){ $categorias[]=['id_categoria'=>(int)$r['id_categoria'],'nombre'=>$r['nombre']]; }

  // partes
  $partes=[];
  $qp=mysqli_query($conn,"SELECT id_parte, nombre FROM tb_inv_parte WHERE IFNULL(condicion,1)=1 ORDER BY nombre");
  while($r=mysqli_fetch_assoc($qp)){ $partes[]=['id_parte'=>(int)$r['id_parte'],'nombre'=>$r['nombre']]; }

  // marcas
  $marcas=[];
  $qm=mysqli_query($conn,"SELECT id_marca, nombre FROM tb_inv_marca WHERE IFNULL(condicion,1)=1 ORDER BY nombre");
  while($r=mysqli_fetch_assoc($qm)){ $marcas[]=['id_marca'=>(int)$r['id_marca'],'nombre'=>$r['nombre']]; }

  // bodegas
  $bodegas=[];
  $qb=mysqli_query($conn,"SELECT id_bodega, nombre FROM tb_inv_bodega WHERE IFNULL(activo,1)=1 ORDER BY nombre");
  while($r=mysqli_fetch_assoc($qb)){ $bodegas[]=['id_bodega'=>(int)$r['id_bodega'],'nombre'=>$r['nombre']]; }

  echo json_encode(['success'=>true,'categorias'=>$categorias,'partes'=>$partes,'marcas'=>$marcas,'bodegas'=>$bodegas]);
}catch(Throwable $e){
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
