<?php

namespace App\Core\Payment\Payriff;

use App\Exceptions\ApiErrorException;
use Auth;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Log;
use Exception;

class Payriff
{

    private $requestUrl;
    private $secretKey;

    public function __construct($paymentInitializeParam)
    {
        $this->restClient = new Client();

        $this->requestUrl = 'https://api.payriff.com/api/v3';
        if ($paymentInitializeParam['env'] == 'test') {
            $this->requestUrl = 'https://api.payriff.com/api/v3';
        }


        $this->secretKey = $paymentInitializeParam['secretKey'];


    }

    private function makeRequest($method, $payloadData, $methodType = 'POST')
    {

        $response = ['status' => false, 'message' => ''];

        try {

            $requestParams['headers']['Content-Type'] = 'application/json';
            $requestParams['headers']['Authorization'] = $this->secretKey;
            $requestParams['body'] = json_encode($payloadData);


            $result = $this->restClient->request($methodType, $this->requestUrl . '/' . $method, $requestParams);

            $getResponseBody = $result->getBody()->getContents();
            $getResponseData = $getResponseBody ? json_decode($getResponseBody, 1) : [];


            if ($getResponseData['code'] == '00000') {
                $response = [
                    'status' => true,
                    'serviceResponse' => $getResponseData
                ];
            } else {
                $response['message'] = 'Redirect url not found.';
                $response['serviceResponse'] = $getResponseData;
            }


        } catch (ClientException $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::debug($message);
            $response['message'] = $e->getMessage();

        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::debug($message);
            $response['message'] = $e->getMessage();
        }

        if (!$response['status']) {
            Log::error($method);
            Log::error($payloadData);
            Log::error($response);
        }

        return $response;

    }

    public function paymentInitialize($param)
    {

        $response = ['status' => false, 'message' => ''];
        try {

            $paymentInitializeParam = [
                'amount' => $param['amount'],
                'language' => 'EN',
                'currency' => $param['currencyCode'],
                'description' => $param['orderId'],
                'callbackUrl' => $param['paymentCheckUrl'],
                'cardSave' => false,
                'operation' => 'PURCHASE',
                'metadata' => [
                    'orderId' => $param['orderId'],
                ]
            ];

            $paymentInitialize = $this->makeRequest('orders', $paymentInitializeParam);

            if (!$paymentInitialize['status']) {
                throw new ApiErrorException($paymentInitialize['message']);
            }

            $response = [
                'status' => true,
                'data' => $paymentInitialize['serviceResponse']
            ];

        } catch (ApiErrorException $e) {
            $response = ['status' => false, 'message' => $e->getMessage()];
        } catch (Exception $e) {
            $response = ['status' => false, 'message' => $e->getMessage()];
            Log::error($response);
        }

        return $response;

    }

    public function orderInformation($orderId)
    {

        $response = ['status' => false, 'message' => ''];
        try {

            $method = 'orders/' . $orderId;
            $payloadData = [];

            $orderInformationRequest = $this->makeRequest($method, $payloadData, 'GET');

            if (!$orderInformationRequest['status']) {
                throw new ApiErrorException($orderInformationRequest['message']);
            }

            $response = [
                'status' => true,
                'data' => $orderInformationRequest['serviceResponse']
            ];

        } catch (ApiErrorException $e) {
            $response = ['status' => false, 'message' => $e->getMessage()];
        } catch (Exception $e) {
            $response = ['status' => false, 'message' => $e->getMessage()];
            Log::error($response);
        }

        if (isset($orderInformationRequest['serviceResponse'])) {
            $response['serviceResponse'] = $orderInformationRequest['serviceResponse'];
        }

        return $response;

    }

}
