<?php

declare(strict_types=1);

namespace Bot\Infrastructure\Payment;

/**
 * سرویس برای مدیریت پرداخت‌های NextPay
 */
final class NextPayGateway
{
    public function __construct(
        private readonly string $apiKey,
    ) {
    }

    /**
     * ایجاد لینک پرداخت
     *
     * @param int $amount مبلغ به ریال
     * @param string $callbackUrl آدرس callback
     * @param string $orderId شناسه سفارش
     * @return array{success: bool, trans_id?: string, url?: string, error?: string}
     */
    public function createPayment(int $amount, string $callbackUrl, string $orderId): array
    {
        $data = [
            'api_key' => $this->apiKey,
            'amount' => $amount,
            'order_id' => $orderId,
            'callback_uri' => $callbackUrl,
        ];

        $ch = curl_init('https://nextpay.org/nx/gateway/token');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200 || $response === false) {
            return ['success' => false, 'error' => 'خطا در ارتباط با درگاه NextPay'];
        }

        $result = json_decode($response, true);

        if (!isset($result['code']) || $result['code'] !== -1) {
            return ['success' => false, 'error' => $result['message'] ?? 'خطا در ایجاد لینک پرداخت'];
        }

        return [
            'success' => true,
            'trans_id' => $result['trans_id'] ?? '',
            'url' => 'https://nextpay.org/nx/gateway/payment/' . ($result['trans_id'] ?? ''),
        ];
    }

    /**
     * بررسی و تأیید پرداخت
     *
     * @param string $transId شناسه تراکنش
     * @param int $amount مبلغ به ریال
     * @param string $orderId شناسه سفارش
     * @return array{success: bool, verified: bool, error?: string}
     */
    public function verifyPayment(string $transId, int $amount, string $orderId): array
    {
        $data = [
            'api_key' => $this->apiKey,
            'trans_id' => $transId,
            'amount' => $amount,
            'order_id' => $orderId,
        ];

        $ch = curl_init('https://nextpay.org/nx/gateway/verify');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200 || $response === false) {
            return ['success' => false, 'verified' => false, 'error' => 'خطا در ارتباط با درگاه NextPay'];
        }

        $result = json_decode($response, true);

        if (!isset($result['code']) || $result['code'] !== 0) {
            return ['success' => false, 'verified' => false, 'error' => $result['message'] ?? 'پرداخت تأیید نشد'];
        }

        return ['success' => true, 'verified' => true];
    }
}

