<?php
// /cotizaciones/api/agregar_a_ventas.php

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('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Expires: 0');

if (!isset($_SESSION['user'])) {
    http_response_code(401);
    echo json_encode(['error' => 'No autenticado']);
    exit;
}

$idCotizacion = intval($_POST['idCotizacion'] ?? 0);
if (!$idCotizacion) {
    http_response_code(400);
    echo json_encode(['error' => 'Falta parámetro idCotizacion']);
    exit;
}

require __DIR__ . '/_node.php';
require_once __DIR__ . '/../../includes/user_activity_log.php';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();
$url = $base . '/api/cotizaciones/' . $idCotizacion . '/agregar-a-venta';

// Importante: el endpoint Node espera un objeto JSON (o body vacío).
// Si enviamos [] (array) como JSON, Zod marca "Validation error".
$r = cpn_node_request('POST', $url, $token, null);
if (!isset($r['ok']) || $r['ok'] !== true) {
    http_response_code($r['_http'] ?? 500);
    $msg = $r['error']['message'] ?? 'Error agregando a ventas.';
    $details = $r['error']['details'] ?? ($r['error']['raw'] ?? null);
    echo json_encode(['error' => $msg, 'details' => $details, 'http' => $r['_http'] ?? null]);
    exit;
}

$idVenta = $r['data']['idVenta'] ?? 0;
$alreadyLinked = $r['data']['alreadyLinked'] ?? false;

if (!$idVenta) {
    http_response_code(500);
    echo json_encode(['error' => 'Respuesta inválida: falta idVenta']);
    exit;
}

echo json_encode([
    'success' => true,
    'idVenta' => $idVenta,
    'alreadyLinked' => $alreadyLinked,
]);

if ((int)$idVenta > 0) {
    cpn_activity_log_event(
        'Cotizaciones',
        'cotizaciones.agregar_a_venta',
        'Agregó la cotización #' . (int)$idCotizacion . ' a la venta #' . (int)$idVenta,
        'cotizacion',
        (int)$idCotizacion,
        ['idVenta' => (int)$idVenta, 'alreadyLinked' => (bool)$alreadyLinked]
    );
}
