<?php

declare(strict_types=1);

require_once __DIR__ . '/config.php';

$crestPath = __DIR__ . '/../lib/crest/crest.php';
if (is_file($crestPath)) {
    require_once $crestPath;
}

function bitrixCallRaw(string $method, array $params = []): array
{
    $webhookUrl = rtrim((string) config('BITRIX_WEBHOOK_URL', ''), '/');
    if ($webhookUrl !== '') {
        return bitrixWebhookCall($webhookUrl, $method, $params);
    }

    if (!class_exists('CRest')) {
        throw new RuntimeException('CRest is not loaded and BITRIX_WEBHOOK_URL is empty.');
    }

    $response = CRest::call($method, $params);

    return is_array($response) ? $response : ['result' => $response];
}

function bitrixCall(string $method, array $params = []): array
{
    $response = bitrixCallRaw($method, $params);
    if (isset($response['error'])) {
        throw new RuntimeException(sprintf(
            'Bitrix REST error in %s: %s - %s',
            $method,
            (string) $response['error'],
            (string) ($response['error_description'] ?? $response['error_information'] ?? '')
        ));
    }

    return $response;
}

function bitrixWebhookCall(string $webhookUrl, string $method, array $params = []): array
{
    $url = $webhookUrl . '/' . $method . '.json';
    $ch = curl_init($url);
    if ($ch === false) {
        throw new RuntimeException('Cannot initialize cURL.');
    }

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 60,
    ]);

    $raw = curl_exec($ch);
    $error = curl_error($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($raw === false) {
        throw new RuntimeException('cURL error: ' . $error);
    }

    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        return [
            'error' => 'INVALID_JSON',
            'error_description' => 'HTTP ' . $status . ': ' . $raw,
        ];
    }

    return $decoded;
}

function cliPrintJson($data): void
{
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
}
