<?php
// /cotizaciones/api/update_cot_gen.php -> proxy a Node: POST /api/cotizaciones/update

session_start();
include '../../includes/session_control.php';

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

if (!isset($_SESSION['user'])) {
    echo json_encode(['ok' => false, 'msg' => 'No autenticado']);
    exit;
}

require __DIR__ . '/_node.php';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();
$url = $base . '/api/cotizaciones/update';

$payload = [
    'id' => $_POST['id'] ?? 0,
    'field' => $_POST['field'] ?? '',
];

if (($payload['field'] ?? '') === 'benef_emp') {
    $payload['idEmpresa'] = $_POST['idEmpresa'] ?? 0;
    $payload['idUsuario'] = $_POST['idUsuario'] ?? 0;
} else {
    $payload['value'] = $_POST['value'] ?? '';
}

$r = cpn_node_request('POST', $url, $token, $payload);
if (!isset($r['ok']) || $r['ok'] !== true) {
    $msg = $r['error']['message'] ?? 'No se pudo actualizar la cotización.';
    echo json_encode(['ok' => false, 'msg' => $msg]);
    exit;
}

echo json_encode(['ok' => true]);
