<?php

namespace App\Core\Payment\BankOfGeorgia;

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 BankOfGeorgia
{

    private $requestUrl;
    private $clientId;
    private $secretKey;
    private $accessToken;

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

        $this->requestUrl = 'https://ipay.ge/opay/api/v1';
        if ($paymentInitializeParam['env'] == 'test') {
            $this->requestUrl = 'https://dev.ipay.ge/opay/api/v1/';
        }


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

        $getAccessToken = $this->getAccessToken();
        $this->accessToken = $getAccessToken['status'] ? $getAccessToken['token'] : null;

    }

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

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

        try {

            $requestParams['headers']['Content-Type'] = 'application/json';
            $requestParams['headers']['Authorization'] = 'Bearer ' . $this->accessToken;
            $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 (isset($getResponseData['error_code'])) {
                $response['message'] = $getResponseData['status_description'];
                $response['serviceResponse'] = $getResponseData;
            } else {
                $response = [
                    'status' => true,
                    '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;

    }

    private function getAccessToken()
    {

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

        try {

            $requestParams['headers']['Authorization'] = 'Basic ' . base64_encode($this->clientId . ':' . $this->secretKey);
            $requestParams['headers']['Content-Type'] = 'application/x-www-form-urlencoded';
            $requestParams['form_params']['grant_type'] = 'client_credentials';

            $result = $this->restClient->request('POST', $this->requestUrl . '/oauth2/token', $requestParams);

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

            if (isset($getResponseData['error_code'])) {
                throw new ApiErrorException($getResponseData['error_message']);
            }

            $response['status'] = true;
            $response['token'] = $getResponseData['access_token'];

        } catch (ApiErrorException $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();
        }

        return $response;

    }


    public function paymentInitialize($param)
    {

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

            $paymentInitializeParam = [
                'intent' => 'CAPTURE',
                'items' => [
                    [
                        'amount' => $param['amount'],
                        'description' => $param['orderCode'],
                        'quantity' => 1,
                        'product_id' => $param['orderCode'],
                    ]
                ],
                'locale' => 'en-US',
                'shop_order_id' => $param['orderId'],
                'redirect_url' => $param['paymentCheckUrl'],
                'capture_method' => 'AUTOMATIC',
                'purchase_units' => [
                    [
                        'amount' => [
                            'currency_code' => $param['currencyCode'],
                            'value' => $param['amount'],
                        ]
                    ]
                ]
            ];

            $paymentInitialize = $this->makeRequest('checkout/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 checkoutOrderInfo($orderId)
    {

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

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

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

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

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

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

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

        return $response;

    }

}
