<?php
declare(strict_types=1);

require_once __DIR__ . '/../auth/guard.php';
require_once __DIR__ . '/../conexion.php';
require_once __DIR__ . '/../_helpers.php';

$u = require_login();
require_module_access($u, "instrumentos");

$id  = (int)($_GET['id'] ?? 0);
$cod = trim((string)($_GET['cod'] ?? $_GET['codigo_familia'] ?? ''));

try {
  if ($id > 0) {
    $st = $pdo->prepare("SELECT * FROM instrumentos_ciclo_vida WHERE id=:id LIMIT 1");
    $st->execute([':id'=>$id]);
  } else {
    if ($cod === '') json_response(['ok'=>false,'message'=>'cod o id requerido'], 400);
    $st = $pdo->prepare("SELECT * FROM instrumentos_ciclo_vida WHERE codigo_familia=:cod ORDER BY id DESC LIMIT 1");
    $st->execute([':cod'=>$cod]);
  }
  $row = $st->fetch(PDO::FETCH_ASSOC);
  if (!$row) json_response(['ok'=>false,'message'=>'No encontrado'], 404);
  json_response(['ok'=>true,'data'=>$row]);
} catch (Throwable $e) {
  error_log("CV GET ERROR: ".$e->getMessage());
  json_response(['ok'=>false,'message'=>'Error obteniendo Ciclo de vida.'], 500);
}
