<?php

declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

$apiUrl   = 'https://sgxcenter.xyz/api';
$agentCode = 'rudal28';
$signature = '2036dc7347d1d3f1b799465a6a7b3d4e';

$payload = [
    'command'    => 'provider_list',
    'agent_code' => trim($agentCode),
    'signature'  => trim($signature),
];

$jsonPayload = json_encode(
    $payload,
    JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);

if ($jsonPayload === false) {
    http_response_code(500);

    echo json_encode([
        'success' => false,
        'message' => 'Gagal membuat payload JSON.',
    ]);

    exit;
}

/*
|--------------------------------------------------------------------------
| Cek IP publik outbound dari PHP yang sama
|--------------------------------------------------------------------------
*/

$ipCh = curl_init('https://api.ipify.org');

curl_setopt_array($ipCh, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT        => 15,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
    CURLOPT_USERAGENT      => 'SGX-Connection-Test/1.0',
]);

$publicIp = curl_exec($ipCh);
$ipError  = curl_error($ipCh);

curl_close($ipCh);

$publicIp = is_string($publicIp)
    ? trim($publicIp)
    : null;

/*
|--------------------------------------------------------------------------
| Request SGX
|--------------------------------------------------------------------------
*/

$ch = curl_init($apiUrl);

curl_setopt_array($ch, [
    CURLOPT_POST            => true,
    CURLOPT_POSTFIELDS      => $jsonPayload,
    CURLOPT_RETURNTRANSFER  => true,

    // Sertakan response header agar bisa diperiksa
    CURLOPT_HEADER          => true,

    CURLOPT_CONNECTTIMEOUT  => 10,
    CURLOPT_TIMEOUT         => 30,

    CURLOPT_SSL_VERIFYPEER  => true,
    CURLOPT_SSL_VERIFYHOST  => 2,

    // Paksa IPv4 untuk memastikan IP whitelist konsisten
    CURLOPT_IPRESOLVE       => CURL_IPRESOLVE_V4,

    // Coba HTTP/1.1 agar tidak bermasalah dengan WAF tertentu
    CURLOPT_HTTP_VERSION    => CURL_HTTP_VERSION_1_1,

    CURLOPT_FOLLOWLOCATION  => false,
    CURLOPT_MAXREDIRS       => 0,

    CURLOPT_USERAGENT       => 'SGX-PHP-Client/1.0',

    CURLOPT_HTTPHEADER => [
        'Accept: application/json',
        'Content-Type: application/json; charset=utf-8',
        'Connection: close',
    ],
]);

$rawResponse = curl_exec($ch);

$curlError  = curl_error($ch);
$curlErrno  = curl_errno($ch);
$curlInfo   = curl_getinfo($ch);

curl_close($ch);

if ($rawResponse === false) {
    http_response_code(502);

    echo json_encode([
        'success'          => false,
        'stage'            => 'curl_connection',
        'curl_errno'       => $curlErrno,
        'curl_error'       => $curlError,
        'server_public_ip' => $publicIp,
        'ip_check_error'   => $ipError ?: null,
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

    exit;
}

$headerSize = (int) ($curlInfo['header_size'] ?? 0);

$responseHeaders = substr($rawResponse, 0, $headerSize);
$responseBody    = substr($rawResponse, $headerSize);

$decodedBody = json_decode($responseBody, true);

$outputBody = is_array($decodedBody)
    ? $decodedBody
    : trim(preg_replace('/\s+/', ' ', strip_tags($responseBody)) ?? '');

echo json_encode([
    'success' => ((int) ($curlInfo['http_code'] ?? 0)) === 200,

    'request' => [
        'url'        => $apiUrl,
        'command'    => 'provider_list',
        'agent_code' => $agentCode,

        // Signature sengaja tidak ditampilkan
        'signature_length' => strlen($signature),
    ],

    'connection' => [
        'server_public_ip' => $publicIp,
        'ip_check_error'   => $ipError ?: null,

        // local_ip bisa berupa IP internal NAT
        'local_ip'  => $curlInfo['local_ip'] ?? null,
        'remote_ip' => $curlInfo['primary_ip'] ?? null,

        'http_code'   => $curlInfo['http_code'] ?? null,
        'content_type'=> $curlInfo['content_type'] ?? null,
        'total_time'  => $curlInfo['total_time'] ?? null,
    ],

    'response_headers' => trim($responseHeaders),
    'response_body'    => $outputBody,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);