<?php
// /cotizaciones/api/add_cot_detalle.php -> proxy a Node: POST /api/cotizaciones/items

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(['success' => false, 'error' => 'No autenticado']);
    exit;
}

require __DIR__ . '/_node.php';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();
$url = $base . '/api/cotizaciones/items';

$payload = [
    'idCot' => $_POST['idCot'] ?? ($_POST['idCotizacion'] ?? 0),
    'idCotizacion' => $_POST['idCotizacion'] ?? ($_POST['idCot'] ?? 0),
    'idVar' => $_POST['idVar'] ?? ($_POST['idVariacion'] ?? 0),
    'idVariacion' => $_POST['idVariacion'] ?? ($_POST['idVar'] ?? 0),
    'cantidad' => $_POST['cantidad'] ?? 1,
    'idServicio' => $_POST['idServicio'] ?? null,
    'precioProd' => $_POST['precioProd'] ?? 0,
    'precioServ' => $_POST['precioServ'] ?? 0,
    'observaciones' => $_POST['observaciones'] ?? '',
];

$r = cpn_node_request('POST', $url, $token, $payload);
if (!isset($r['ok']) || $r['ok'] !== true) {
    $msg = $r['error']['message'] ?? 'No se pudo agregar el producto.';
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}

echo json_encode(['success' => true]);
