<?php
session_start();
include '../includes/session_control.php';
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../cotizaciones/api/_node.php';
require_once __DIR__ . '/../includes/user_activity_log.php';

$idG = intval($_POST['idGasto'] ?? 0);

$token = cpn_node_token_or_fail();
$url = cpn_node_api_base() . '/api/gastos/items/add';
$resp = cpn_node_request('POST', $url, $token, ['idGasto' => $idG]);

if (!($resp['ok'] ?? false)) {
  http_response_code(intval($resp['_http'] ?? 500));
  echo json_encode(['success' => false, 'msg' => $resp['error']['message'] ?? 'Error en API']);
  exit;
}

cpn_activity_log_event(
  'Gastos',
  'gastos.item_add',
  'Agregó ítem al gasto #' . $idG,
  'gasto',
  $idG
);

echo json_encode($resp['data'] ?? ['success' => false]);
