<?php
namespace App\Libraries;

class GatewayApi
{
    public function payment($data = [], $header = [])
    {
        $url = $header['url'];

        // ─── FIX for shared hosting SSL loopback error ──────────────────────
        // When main calls secent on the same server via HTTPS, Cloudflare/WAF
        // drops the SSL connection (unexpected EOF, INTERNAL_ERROR, etc.).
        // Converting to HTTP for the internal cURL call bypasses this entirely.
        // The response data itself is not sensitive (it's just a payment link ID).
        $url = preg_replace('/^https:\/\//i', 'http://', $url);
        // ────────────────────────────────────────────────────────────────────

        $headers = array(
            'Content-Type: application/json',
            'API-KEY: ' . $header['api'],
            'Accept: application/json',
            'Connection: close',
        );

        $curl = curl_init();
        $data = json_encode($data);

        curl_setopt_array($curl, array(
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS      => 5,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_FRESH_CONNECT  => true,
            CURLOPT_FORBID_REUSE   => true,
            CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
            CURLOPT_CUSTOMREQUEST  => 'POST',
            CURLOPT_POSTFIELDS     => $data,
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => 0,
        ));

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            $error_msg  = curl_error($curl);
            $error_no   = curl_errno($curl);
            $http_code  = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);
            log_message('error', "GatewayApi cURL Error [{$error_no}]: {$error_msg} | URL: {$url} | HTTP: {$http_code}");
            return json_encode(['status' => 'error', 'message' => 'Connection Error: ' . $error_msg]);
        }

        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if ($http_code !== 200) {
            log_message('error', "GatewayApi HTTP {$http_code} | URL: {$url} | Response: " . substr($response, 0, 500));
        }

        return $response;
    }
}
