<?php
// Helper mínimo para consumir APIs Node desde Cotizaciones (proxies PHP)

// Hacerlo idempotente: esta librería se incluye desde múltiples páginas/includes.
if (!function_exists('cpn_node_api_base')) {
    function cpn_node_api_base(): string
    {
        $base = getenv('COMPRANET_NODE_API_BASE');
        if (!$base) {
            $base = 'https://app.compranet.com.co';
        }
        return rtrim($base, '/');
    }
}

if (!function_exists('cpn_node_token_or_fail')) {
    function cpn_node_token_or_fail(): string
    {
        $token = $_SESSION['node_token'] ?? '';
        if (!is_string($token) || trim($token) === '') {
            http_response_code(401);
            echo json_encode(['error' => 'Token de sesión no disponible. Vuelva a iniciar sesión.']);
            exit;
        }
        return $token;
    }
}

if (!function_exists('cpn_node_request')) {
    function cpn_node_request(string $method, string $url, string $token, ?array $payload = null): array
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);

        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $token,
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);

        if ($payload !== null) {
            $json = json_encode($payload);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        }

        $resp = curl_exec($ch);
        $err = curl_error($ch);
        $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($resp === false) {
            return ['ok' => false, 'error' => ['message' => 'Error conectando a Node: ' . ($err ?: 'desconocido')], '_http' => $http];
        }

        $data = json_decode($resp, true);
        if (!is_array($data)) {
            $snippet = substr((string)$resp, 0, 500);
            return ['ok' => false, 'error' => ['message' => 'Respuesta inválida de Node', 'raw' => $snippet], '_http' => $http];
        }

        $data['_http'] = $http;
        return $data;
    }
}
