<?php
session_start();
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../cotizaciones/api/_node.php';
require_once __DIR__ . '/../includes/user_activity_log.php';

$act    = $_REQUEST['action'] ?? '';
$idG    = intval($_REQUEST['idGasto']  ?? 0);
$idReg  = intval($_REQUEST['idRegistro'] ?? 0);

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

if ($act === 'list' || $act === 'listsel') {
  $url = $base . '/api/gastos/deducciones?action=' . urlencode($act) . '&idGasto=' . urlencode((string)$idG) . '&idRegistro=' . urlencode((string)$idReg);
  $resp = cpn_node_request('GET', $url, $token, null);
} else {
  $payload = $_POST;
  $payload['action'] = $act;
  if (!isset($payload['idGasto'])) $payload['idGasto'] = $idG;
  if (!isset($payload['idRegistro'])) $payload['idRegistro'] = $idReg;

  $resp = cpn_node_request('POST', $base . '/api/gastos/deducciones', $token, $payload);
}

if (!($resp['ok'] ?? false)) {
  http_response_code(intval($resp['_http'] ?? 500));

  // Mantener forma legacy cuando sea posible
  if ($act === 'list') {
    echo json_encode([]);
    exit;
  }
  if ($act === 'listsel') {
    echo json_encode(['lista' => []]);
    exit;
  }

  echo json_encode(['success' => false, 'error' => $resp['error']['message'] ?? 'Error en API']);
  exit;
}

if ($act !== 'list' && $act !== 'listsel') {
  cpn_activity_log_event(
    'Gastos',
    'gastos.deducciones_update',
    'Actualizó deducciones del gasto #' . $idG . ' (action: ' . (string)$act . ')',
    'gasto',
    $idG,
    ['action' => (string)$act, 'idRegistro' => $idReg]
  );
}

echo json_encode($resp['data'] ?? ($act === 'list' ? [] : []));
exit;
