<?php
declare(strict_types=1);
namespace PpPhp\Generated\SocialAuth;

final class HttpClient
{
    public static function get(string $url, array $headers = []): array { return self::request('GET', $url, [], $headers); }
    public static function post(string $url, array $data, array $headers = []): array { return self::request('POST', $url, $data, $headers); }
    private static function request(string $method, string $url, array $data, array $headers): array
    {
        $headers[] = 'Accept: application/json';
        $body = '';
        $status = 0;
        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false, CURLOPT_CONNECTTIMEOUT => 8, CURLOPT_TIMEOUT => 20, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_HTTPHEADER => $headers]);
            if ($method === 'POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&', PHP_QUERY_RFC3986)); curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($headers, ['Content-Type: application/x-www-form-urlencoded'])); }
            $body = (string)curl_exec($ch); $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $error = curl_error($ch); curl_close($ch);
            if ($body === '' && $error !== '') throw new \RuntimeException('Provider request failed: ' . $error);
        } else {
            $context = ['http' => ['method' => $method, 'timeout' => 20, 'ignore_errors' => true, 'header' => implode("\r\n", $headers)]];
            if ($method === 'POST') { $context['http']['header'] .= "\r\nContent-Type: application/x-www-form-urlencoded"; $context['http']['content'] = http_build_query($data, '', '&', PHP_QUERY_RFC3986); }
            $body = (string)@file_get_contents($url, false, stream_context_create($context));
            foreach (($http_response_header ?? []) as $line) if (preg_match('#^HTTP/\S+\s+(\d+)#', $line, $m)) $status = (int)$m[1];
        }
        $json = json_decode($body, true);
        if ($status < 200 || $status >= 300 || !is_array($json)) {
            $message = is_array($json) ? (string)($json['error_description'] ?? $json['error']['message'] ?? $json['error'] ?? 'Provider rejected the request.') : 'Invalid provider response.';
            throw new \RuntimeException($message);
        }
        return $json;
    }
}
