<?php
// api/tipo_reparacion_list.php — Lista de tipos de reparación con clasificación por Taller
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  http_response_code(401);
  echo json_encode(['success'=>false,'data'=>[], 'message'=>'No autorizado']); exit;
}

$pathConex = realpath(__DIR__ . '/../conex.php')
         ?: realpath(__DIR__ . '/../../conex.php')
         ?: realpath(__DIR__ . '/conex.php');
if (!$pathConex) { http_response_code(500); echo json_encode(['success'=>false,'data'=>[], 'message'=>'No se encontró conex.php']); exit; }
require_once $pathConex;

$db = $conn ?? ($conex ?? null);
if (!$db instanceof mysqli) { http_response_code(500); echo json_encode(['success'=>false,'data'=>[], 'message'=>'Sin conexión BD']); exit; }
mysqli_set_charset($db, 'utf8mb4');

$id_taller = isset($_GET['id_taller']) ? (int)$_GET['id_taller'] : 0;

$sql = "SELECT tr.id, tr.tipo, tr.id_taller, t.taller
        FROM tb_tipo_reparacion tr
        LEFT JOIN tb_taller t ON t.idtaller = tr.id_taller
        WHERE tr.condicion = 1 " . ($id_taller > 0 ? " AND tr.id_taller = ?" : "") . "
        ORDER BY t.taller, tr.tipo";

$data = [];
if ($id_taller > 0) {
  if ($stmt = $db->prepare($sql)) {
    $stmt->bind_param('i', $id_taller);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($r = $res->fetch_assoc()) {
      $data[] = [
        'id'        => (int)$r['id'],
        'tipo'      => $r['tipo'],
        'id_taller' => (int)($r['id_taller'] ?? 0),
        'taller'    => $r['taller'] ?? null,
      ];
    }
    $stmt->close();
  }
} else {
  $res = $db->query($sql);
  if ($res) {
    while ($r = $res->fetch_assoc()) {
      $data[] = [
        'id'        => (int)$r['id'],
        'tipo'      => $r['tipo'],
        'id_taller' => (int)($r['id_taller'] ?? 0),
        'taller'    => $r['taller'] ?? null,
      ];
    }
  }
}

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