<?php

namespace Devsaadat\ShopGostardeh\Helpers;

use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;

class Payment4
{
    private string $api_key;
    private bool $sandbox = false;
    private string $url = 'service.payment4.com';
    private Client $httpClient;

    /**
     * @param string $api_key
     * @param bool $sandbox
     * @throws Exception
     */
    function __construct(string $api_key, bool $sandbox = false) {
        if($api_key) {
            $this->api_key = $api_key;
            $this->sandbox = $sandbox;
            $this->httpClient = new Client([
                'base_uri' => 'https://' . $this->url,
                'timeout' => 10.0,
            ]);
        } else {
            throw new Exception("کلید سرویس معتبر نیست");
        }
    }

    /**
     * @param $method
     * @param $endpoint
     * @param array $data
     * @return array|mixed
     * @throws Exception
     */
    private function sendRequest($method, $endpoint, array $data = []): mixed
    {
        try {
            $data['sandBox'] = $this->sandbox;
            $headers = [
                'x-api-key' => $this->api_key,
                'Content-Type' => 'application/json',
            ];

            $response = $this->httpClient->request($method, $endpoint, [
                'headers' => $headers,
                'json' => $data,
            ]);

            return json_decode($response->getBody()->getContents(), true);
        } catch (RequestException  $e) {
            if ($e->hasResponse()) {
                $responseBody = $e->getResponse()->getBody()->getContents();
                return json_decode($responseBody, true);
            } else {
                throw new Exception('Request failed with no response!');
            }
        } catch (GuzzleException $e) {
            $error = $e->getMessage();
            //SendLog("خطای اتصال به payment4: ". $error);
            //error("خطای اتصال به payment4: ". $error);
            throw new Exception($error);
        }
    }


    /**
     * @param $amount
     * @param $callbackUrl
     * @param string $currency
     * @param object|null $callbackParams
     * @param null $webhookUrl
     * @param object|null $webhookParams
     * @param string $language
     * @return mixed
     * @throws Exception
     */
    public function createPayment($amount, $callbackUrl, string $currency = 'USD', object $callbackParams = null, $webhookUrl = null, object $webhookParams = null, string $language = 'EN'): mixed
    {
        $post_fields = [
            'amount' => $amount,
            'callbackUrl' => $callbackUrl,
            'currency' => $currency, // Optional Default USD
            'webhookParams' => $webhookParams, // Optional
            'language' => $language, // Optional Default EN
        ];
        if($callbackParams) $post_fields['callbackParams'] = $callbackParams;
        if($webhookUrl) $post_fields['webhookUrl'] = $webhookUrl;
        if($webhookParams) $post_fields['webhookParams'] = $webhookParams;


        return $this->sendRequest('POST', '/api/v1/payment', $post_fields);
    }
    /*
     * Example
     * { "id": 0,  "paymentUid": "string",  "paymentUrl": "string" }
     *
     * paymentStatus و paymentUid به ادرس CallbackUrl به صورت GET ارسال می شود (کاربر)
     */


    /**
     * @param $paymentUid
     * @param $amount
     * @param string $currency
     * @return mixed
     * @throws Exception
     */
    public function verifyPayment($paymentUid, $amount, string $currency = 'USD'): mixed
    {
        $post_fields = [
            'paymentUid' => $paymentUid,
            'amount' => $amount,
            'currency' => $currency,

        ];

        return $this->sendRequest('PUT', '/api/v1/payment/verify', $post_fields);
    }
    /*
     * Example
     * { "paymentStatus": "PENDING",  "amountDifference": "-1.1",  "verified": true }
     */


}