<?php
declare(strict_types=1);

class PaymentService
{
    public function requestPayment(float $amount, string $description, string $mobile, int $orderId): array
    {
        if (PAYMENT_GATEWAY_MODE === 'mock') {
            return [
                'success' => true,
                'gateway_url' => appPath('/public/payment-callback.php') . '?Authority=MOCK-' . $orderId . '&Status=OK',
                'authority' => 'MOCK-' . $orderId,
            ];
        }

        if (ZARINPAL_MERCHANT_ID === '') {
            return [
                'success' => false,
                'message' => 'شناسه مرچنت زرین‌پال تنظیم نشده است.',
            ];
        }

        $base = PAYMENT_GATEWAY_MODE === 'production'
            ? 'https://api.zarinpal.com/pg/v4/payment'
            : 'https://sandbox.zarinpal.com/pg/v4/payment';

        $payload = [
            'merchant_id' => ZARINPAL_MERCHANT_ID,
            'amount' => (int)round($amount),
            'description' => $description,
            'callback_url' => rtrim(APP_URL, '/') . ZARINPAL_CALLBACK_PATH,
            'metadata' => [
                'mobile' => $mobile,
                'order_id' => (string)$orderId,
            ],
        ];

        $response = $this->postJson($base . '/request.json', $payload);
        if (!$response['ok']) {
            return ['success' => false, 'message' => 'خطا در ارتباط با زرین‌پال'];
        }

        $authority = $response['data']['data']['authority'] ?? null;
        if (!$authority) {
            return ['success' => false, 'message' => 'authority دریافت نشد'];
        }

        return [
            'success' => true,
            'authority' => $authority,
            'gateway_url' => 'https://www.zarinpal.com/pg/StartPay/' . $authority,
        ];
    }

    public function verify(string $authority, float $amount): array
    {
        if (PAYMENT_GATEWAY_MODE === 'mock') {
            return [
                'success' => true,
                'ref_id' => 'MOCK-REF-' . strtoupper(bin2hex(random_bytes(3))),
            ];
        }

        $base = PAYMENT_GATEWAY_MODE === 'production'
            ? 'https://api.zarinpal.com/pg/v4/payment'
            : 'https://sandbox.zarinpal.com/pg/v4/payment';

        $payload = [
            'merchant_id' => ZARINPAL_MERCHANT_ID,
            'amount' => (int)round($amount),
            'authority' => $authority,
        ];
        $response = $this->postJson($base . '/verify.json', $payload);
        if (!$response['ok']) {
            return ['success' => false, 'message' => 'خطا در تایید تراکنش'];
        }

        $refId = $response['data']['data']['ref_id'] ?? null;
        if (!$refId) {
            return ['success' => false, 'message' => 'ref_id دریافت نشد'];
        }

        return [
            'success' => true,
            'ref_id' => (string)$refId,
        ];
    }

    private function postJson(string $url, array $payload): array
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
            CURLOPT_TIMEOUT => 15,
        ]);
        $body = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if (!is_string($body) || $body === '' || $error !== '') {
            return ['ok' => false, 'data' => null];
        }

        $decoded = json_decode($body, true);
        return ['ok' => is_array($decoded), 'data' => $decoded];
    }
}
