<?php

declare(strict_types=1);

namespace Bot\Infrastructure\Payment;

/**
 * سرویس برای مدیریت پرداخت‌های ZarinPal
 */
final class ZarinPalGateway
{
    public function __construct(
        private readonly string $merchantId,
        private readonly bool $sandbox = false,
    ) {
    }

    /**
     * ایجاد لینک پرداخت
     *
     * @param int $amount مبلغ به ریال
     * @param string $callbackUrl آدرس callback
     * @param string $description توضیحات
     * @return array{success: bool, authority?: string, url?: string, error?: string}
     */
    public function createPayment(int $amount, string $callbackUrl, string $description = ''): array
    {
        $url = $this->sandbox
            ? 'https://sandbox.zarinpal.com/pg/v4/payment/request.json'
            : 'https://api.zarinpal.com/pg/v4/payment/request.json';

        $data = [
            'merchant_id' => $this->merchantId,
            'amount' => $amount,
            'callback_url' => $callbackUrl,
            'description' => $description ?: 'پرداخت ربات آپلودر',
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        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' => 'خطا در ارتباط با درگاه ZarinPal'];
        }

        $result = json_decode($response, true);

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

        $authority = $result['data']['authority'] ?? '';
        $paymentUrl = $this->sandbox
            ? "https://sandbox.zarinpal.com/pg/StartPay/{$authority}"
            : "https://www.zarinpal.com/pg/StartPay/{$authority}";

        return [
            'success' => true,
            'authority' => $authority,
            'url' => $paymentUrl,
        ];
    }

    /**
     * بررسی و تأیید پرداخت
     *
     * @param string $authority شناسه پرداخت
     * @param int $amount مبلغ به ریال
     * @return array{success: bool, verified: bool, ref_id?: string, error?: string}
     */
    public function verifyPayment(string $authority, int $amount): array
    {
        $url = $this->sandbox
            ? 'https://sandbox.zarinpal.com/pg/v4/payment/verify.json'
            : 'https://api.zarinpal.com/pg/v4/payment/verify.json';

        $data = [
            'merchant_id' => $this->merchantId,
            'authority' => $authority,
            'amount' => $amount,
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        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' => 'خطا در ارتباط با درگاه ZarinPal'];
        }

        $result = json_decode($response, true);

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

        return [
            'success' => true,
            'verified' => true,
            'ref_id' => $result['data']['ref_id'] ?? '',
        ];
    }
}

