<?php
/**
 * Created by PhpStorm.
 * User: merdan
 * Date: 9/22/2021
 * Time: 15:40
 */

namespace TPS\Payment\Methods;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use TPS\Payment\Http\Resoures\Payment\Order;
use Webkul\Checkout\Facades\Cart;
use Webkul\Checkout\Models\CartPayment;
use Webkul\Payment\Payment\Payment;

class TFEB extends Payment
{

    protected $code = 'tfeb';

    private function getApiClient():Client{
        return new Client([
            'base_uri' => $this->getConfigData('api_url'),
            'connect_timeout' => 55,//sec
            'timeout' => 55,//sec
            'verify' => false,
            'headers' =>[
                'ClientId' => $this->getConfigData('client_id'),
                'ClientSecret' => $this->getConfigData('client_secret'),
                'Accept' => "application/hal+json",
                "Content-Type" => 'application/json'
            ],
        ]);
    }

    public function registerOrder()
    {
        $client = $this->getApiClient();

        $cart_order = Order::make($this->getCart());

        $body = $cart_order->toJson();

        $params =[
            'body' => $body
        ];

        try {
            $result = json_decode($client->post('',$params)->getBody(),true);

            if($result['response']['operationResult'] == 'OPG-00100'){
                return [
                    "success" =>  $this->registerOrderId($result['response']['orderId']),
                    "url" => $result['_links']['redirectToCheckout']['href'],
                    "message" => "unable to save order id"
                ];
            }
            else{//if already registered or otkazana w dostupe
                return [
                    "success" => false,
                    "message" => $result['response']['operationResultDescription']
                ];
            }

        }catch(Exception $e){
            Log::info($result);
            Log::error($e);
            return [
                "success" => false,
                "message" => $e->getMessage()
            ];

        }
    }

    public function getRedirectUrl()
    {
        return route('paymentmethod.tfeb.redirect');
    }

    public function isRegistered(){
        $payment = $this->getCart()->payment;
        return (!empty($payment) && !empty($payment->orderId));
    }

    public function getOrderStatus(){
        try {
            $client = $this->getApiClient();
            $payment = $this->getCart()->payment;

            if ($payment) {

                $result = json_decode($client->get($payment->order_id)->getBody());

                if ($result['response']['operationResult'] == 'GEN-00000') {
                    return [
                        "success" =>  true,
                    ];

                } else {
                    return [
                        "success" =>  false,
                        "message" => trans('payment.unsuccessfull')
                    ];
                }
            }

        }catch(Exception $e){
            return [
                "success" =>  false,
                "message" => $e->getMessage()
            ];
        }

    }

    public function registerOrderId($orderId){
        $payment = $this->getCart()->payment;
        $payment->order_id = $orderId;
//        dd($payment);
//        $payment->paymentFormUrl = $formUrl;
        return $payment->save();
    }
}