<?php

/**
 * iTzAYDiN-BOT — TetraPay API v1 adapter
 *
 * Contract implemented from the gateway owner's sample:
 * POST {API_URL}/api/v1/payment-link
 * Headers: X-API-Key + application/json
 * Body: {"amount": <toman>}
 * Success: {ok,total_amount,link,token}
 *
 * Important: no verification/status/webhook contract was supplied in that sample,
 * therefore this adapter only creates payment links and never marks a payment paid.
 */

if (!function_exists('itz_tetrapay_setting')) {
    function itz_tetrapay_setting(string $key, string $default = ''): string
    {
        try {
            $row = select('PaySetting', 'ValuePay', 'NamePay', $key, 'select');
            if (is_array($row) && array_key_exists('ValuePay', $row)) {
                return trim((string) $row['ValuePay']);
            }
        } catch (Throwable $e) {
            @error_log('[TetraPay config] ' . $e->getMessage());
        }
        return $default;
    }
}

if (!function_exists('itz_tetrapay_mask')) {
    function itz_tetrapay_mask(string $value): string
    {
        $value = trim($value);
        $len = strlen($value);
        if ($len === 0) return '— تنظیم نشده';
        if ($len <= 8) return str_repeat('•', max(4, $len));
        return substr($value, 0, 4) . str_repeat('•', max(4, $len - 8)) . substr($value, -4);
    }
}

if (!function_exists('itz_tetrapay_base_url')) {
    function itz_tetrapay_base_url(?string $raw = null): string
    {
        $url = trim((string) ($raw ?? itz_tetrapay_setting('tetrapay_api_url')));
        if ($url === '') return '';
        $url = rtrim($url, '/');
        if (!filter_var($url, FILTER_VALIDATE_URL)) return '';
        $parts = parse_url($url);
        $scheme = strtolower((string)($parts['scheme'] ?? ''));
        if (!in_array($scheme, ['http', 'https'], true)) return '';
        if (empty($parts['host'])) return '';
        return $url;
    }
}

if (!function_exists('itz_tetrapay_config')) {
    function itz_tetrapay_config(): array
    {
        return [
            'api_url' => itz_tetrapay_base_url(),
            'api_key' => itz_tetrapay_setting('tetrapay_api_key'),
        ];
    }
}

if (!function_exists('itz_tetrapay_transport_message')) {
    function itz_tetrapay_transport_message(int $errno, string $error = ''): string
    {
        $messages = [
            5  => 'Proxy در دسترس نیست یا نام آن Resolve نشد.',
            6  => 'نام میزبان API از سمت سرور هاست Resolve نشد (DNS).',
            7  => 'اتصال TCP به سرور/پورت API برقرار نشد.',
            28 => 'اتصال به API بیش از زمان مجاز طول کشید (Timeout).',
            35 => 'Handshake امن SSL/TLS ناموفق بود.',
            47 => 'تعداد Redirectهای API بیش از حد مجاز بود.',
            52 => 'سرور API بدون ارسال پاسخ اتصال را بست.',
            56 => 'دریافت پاسخ از سرور API با خطای شبکه قطع شد.',
            60 => 'گواهی SSL سرور API قابل اعتبارسنجی نیست.',
        ];
        $base = $messages[$errno] ?? 'ارتباط شبکه با API تتراپی برقرار نشد.';
        $error = trim($error);
        return $error !== '' ? $base . ' (' . $error . ')' : $base;
    }
}

if (!function_exists('itz_tetrapay_http_request')) {
    function itz_tetrapay_http_request(string $endpoint, string $apiKey, string $payload, bool $forceIpv4 = false): array
    {
        $ch = curl_init();
        $options = [
            CURLOPT_URL => $endpoint,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => 20,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 3,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_USERAGENT => 'iTzAYDiN-BOT/3.0.0 TetraPay',
            CURLOPT_HTTPHEADER => [
                'X-API-Key: ' . $apiKey,
                'Content-Type: application/json',
                'Accept: application/json',
            ],
        ];
        if (defined('CURLOPT_TCP_KEEPALIVE')) {
            $options[CURLOPT_TCP_KEEPALIVE] = 1;
        }
        if ($forceIpv4 && defined('CURL_IPRESOLVE_V4')) {
            $options[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
        }
        curl_setopt_array($ch, $options);

        $raw = curl_exec($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        return [
            'raw' => $raw,
            'errno' => $errno,
            'error' => $error,
            'http_status' => (int)($info['http_code'] ?? 0),
            'effective_url' => (string)($info['url'] ?? $endpoint),
            'primary_ip' => (string)($info['primary_ip'] ?? ''),
            'primary_port' => (int)($info['primary_port'] ?? 0),
            'namelookup_time' => (float)($info['namelookup_time'] ?? 0),
            'connect_time' => (float)($info['connect_time'] ?? 0),
            'total_time' => (float)($info['total_time'] ?? 0),
            'forced_ipv4' => $forceIpv4,
        ];
    }
}

if (!function_exists('itz_tetrapay_create_payment_link')) {
    function itz_tetrapay_create_payment_link($amount): array
    {
        $amount = (int) round((float) $amount);
        if ($amount <= 0) {
            return ['ok' => false, 'status' => '0', 'message' => 'مبلغ پرداخت معتبر نیست.'];
        }

        $config = itz_tetrapay_config();
        if ($config['api_url'] === '') {
            return ['ok' => false, 'status' => '0', 'message' => 'API URL تتراپی تنظیم نشده یا آدرس http/https معتبر نیست.'];
        }
        if ($config['api_key'] === '') {
            return ['ok' => false, 'status' => '0', 'message' => 'API Key تتراپی تنظیم نشده است.'];
        }
        if (!function_exists('curl_init')) {
            return ['ok' => false, 'status' => '0', 'message' => 'افزونه cURL روی سرور فعال نیست.'];
        }

        $endpoint = $config['api_url'] . '/api/v1/payment-link';
        $payload = json_encode(['amount' => $amount], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        if ($payload === false) {
            return ['ok' => false, 'status' => '0', 'message' => 'ساخت درخواست JSON ناموفق بود.'];
        }

        // First attempt uses the host's normal network stack. Some shared hosts
        // advertise broken IPv6 routes; on transport failure we retry via IPv4.
        $attempt = itz_tetrapay_http_request($endpoint, $config['api_key'], $payload, false);
        if (($attempt['raw'] === false || $attempt['errno'] !== 0) && defined('CURL_IPRESOLVE_V4')) {
            $retry = itz_tetrapay_http_request($endpoint, $config['api_key'], $payload, true);
            if (!($retry['raw'] === false || $retry['errno'] !== 0) || $retry['http_status'] > 0) {
                $attempt = $retry;
            } else {
                // Keep the retry diagnostics because they are usually more actionable
                // on cPanel/shared-host environments.
                $attempt = $retry;
            }
        }

        $raw = $attempt['raw'];
        $errno = (int)$attempt['errno'];
        $error = (string)$attempt['error'];
        $http = (int)$attempt['http_status'];

        $diag = [
            'curl_errno' => $errno,
            'curl_error' => $error,
            'http_status' => $http,
            'effective_url' => (string)$attempt['effective_url'],
            'primary_ip' => (string)$attempt['primary_ip'],
            'primary_port' => (int)$attempt['primary_port'],
            'namelookup_time' => (float)$attempt['namelookup_time'],
            'connect_time' => (float)$attempt['connect_time'],
            'total_time' => (float)$attempt['total_time'],
            'forced_ipv4' => !empty($attempt['forced_ipv4']),
        ];

        if ($raw === false || $errno !== 0) {
            $message = itz_tetrapay_transport_message($errno, $error);
            @error_log('[TetraPay] transport error ' . json_encode($diag, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            return array_merge([
                'ok' => false,
                'status' => '0',
                'message' => $message,
                'diagnostic_code' => 'transport_error',
            ], $diag);
        }

        $data = json_decode((string)$raw, true);
        if (!is_array($data)) {
            $preview = trim(preg_replace('/\s+/', ' ', strip_tags((string)$raw)) ?? '');
            if (strlen($preview) > 300) $preview = substr($preview, 0, 300) . '…';
            @error_log('[TetraPay] invalid JSON response; HTTP=' . $http . '; preview=' . $preview);
            return array_merge([
                'ok' => false,
                'status' => '0',
                'message' => 'پاسخ API تتراپی JSON معتبر نبود.',
                'diagnostic_code' => 'invalid_json',
                'response_preview' => $preview,
            ], $diag);
        }

        $providerOk = ($http >= 200 && $http < 300 && !empty($data['ok']));
        $link = trim((string)($data['link'] ?? ''));
        $token = trim((string)($data['token'] ?? ''));
        if ($providerOk && filter_var($link, FILTER_VALIDATE_URL) && $token !== '') {
            return array_merge([
                'ok' => true,
                'status' => '100',
                'total_amount' => $data['total_amount'] ?? $amount,
                'link' => $link,
                'token' => $token,
                'payment_url_bot' => $link,
                'Authority' => $token,
                'message' => 'لینک پرداخت تتراپی ساخته شد.',
                'provider' => 'tetrapay_api_v1',
            ], $diag);
        }

        $providerError = trim((string)($data['error'] ?? $data['message'] ?? ''));
        if ($providerError === '') $providerError = 'درگاه درخواست ساخت لینک را نپذیرفت.';
        @error_log('[TetraPay] API rejected request; HTTP=' . $http . '; message=' . $providerError);
        return array_merge([
            'ok' => false,
            'status' => '0',
            'message' => $providerError,
            'diagnostic_code' => 'provider_rejected',
        ], $diag);
    }
}

