<?php

namespace Sipago\WooCommerce\SipagoCheckout\ClientSipago;
use Sipago\WooCommerce\SipagoCheckout\Helpers\LogHandler;

class SipagoCheckoutRest{

    const GET_JWT = 'https://auth.prd.geopagos.io/oauth/token';
    const GET_LINK = 'https://api.sipago.coop/api/v2/orders';

    public $clientId;
    public $clientSecrect;


    /**
     * @var LogHandler
     */
    protected $log;



    public function __construct($clientId,$clientSecrect){

        $this->clientId = $clientId;
        $this->clientSecrect = $clientSecrect;

    }

    public function getJwt(){
        $this->log = new LogHandler();
        $this->log->logInfo('getJwt ');

        $postData = [
            'grant_type' => 'client_credentials',
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecrect,
            'scope' => '*'
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, static::GET_JWT);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            $this->log->logInfo('error: ' . $error);
            $result = [
                'error' => true,
                'status' => null
            ];
            return $result;
        }

        if($httpCode == 200){
            $responseData = json_decode($response, true);

            $result = [
                'error' => false,
                'status' => $httpCode,
                'access_token' => $responseData['access_token']
            ];

            return $result;
        }

        $result = [
            'error' => true,
            'status' => $httpCode
        ];
        return $result;
    }




    public function flowLink($urlReturn,$urlWebhook,$orderId,$stackItems,$coupons,$shipping_Items,$amount_totals_details){
        $this->log = new LogHandler();
        $this->log->logInfo('urlWebhook'.$urlWebhook);
        try {



            $resultJwt=$this->getJwt();
            if($resultJwt['error']==false){
                $resultLink=$this->getOrder($resultJwt['access_token']
                                    ,$urlReturn
                                    ,$urlWebhook
                                    ,$orderId
                                    ,$stackItems
                                    ,$coupons
                                    ,$shipping_Items
                                    ,$amount_totals_details
                                );

                return $resultLink;
            }
            $result = [
                'error' => true,
                'status' => null
            ];
            return $result;

        }
        catch(Exception $e) {
            $this->log->logInfo('error'.$e->getMessage());
            $result = [
                'error' => true,
                'status' => null
            ];
            return $result;
          }

    }




    public function getOrder($jwt,$urlReturn,$urlWebhook,$orderId,$stackItems,$coupons,$shipping_Items, $amount_totals_details){
        $this->log = new LogHandler();

        $produtItems=[];
        //Newfeature
        if ($amount_totals_details==-1){
            foreach ( $stackItems as $item_id => $item ) {
                array_push($produtItems,[
                    'id'=>$item['productId']
                    ,'name'=>$item['productName']
                    ,'unitPrice'=>[
                        'currency'=>'032'
                        ,'amount'=>$item['total']
                    ]
                    ,'quantity'=>$item['quantity']
                ]);
            }
        }else{


                array_push($produtItems,[
                    'id'=>"1"
                    ,'unitPrice'=>[
                        'currency'=>'032'
                        ,'amount'=>$amount_totals_details
                    ]
                    ,'quantity'=>1
                ]);

        }



        try{

            $jsonPre = [

                'data' => [
                    'attributes' => [
                        'redirect_urls' => [
                            'success' => $urlReturn ,
                            'failed' =>  $urlReturn
                        ],
                        'webhookUrl' =>  $urlWebhook ,
                        'currency'=>'032'
                        ]
                    ]

                ];

            if (count($coupons)>0 && $amount_totals_details==-1){
                $index = 0;
                foreach ( $coupons as $item_id => $item ) {
                    array_push($produtItems,[
                        'id'=>"icp".$index
                        ,'name'=>$item['discount_type']
                        ,'unitPrice'=>[
                            'currency'=>'032'
                            ,'amount'=>$item['coupon_amount']
                        ]
                        ,'quantity'=>1
                    ]);
                }
                $index =$index +1;

            }


            if (count($shipping_Items)>0 && $amount_totals_details==-1){
                $shipping = [
                    'name'=>$shipping_Items[0]['method']
                    ,'price'=>[
                        'currency'=>'032'
                        ,'amount'=>$shipping_Items[0]['total']
                    ]
                ];

                $jsonPre['data']['attributes']['shipping'] =$shipping;
            }


            $jsonPre['data']['attributes']['items'] =$produtItems;


            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, static::GET_LINK);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($jsonPre));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/vnd.api+json',
                'Accept: application/vnd.api+json',
                'Authorization: Bearer ' . $jwt
            ]);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);

            if ($error) {
                $this->log->logInfo('error: ' . $error);
                $result = [
                    'error' => true,
                    'status' => null
                ];
                return $result;
            }

            if($httpCode == 201){

                $responseData = json_decode($response, true);

                $jsonRaw = [
                    'ref_id' => $responseData['data']['attributes']['uuid'],
                    'dataRes' => $responseData
                ];

                $result = [
                    'error' => false,
                    'status' => $httpCode,
                    'link' => $responseData['data']['attributes']['links']['checkout'],
                    'uuid' => $responseData['data']['attributes']['uuid'],
                    'orderNumber' => $responseData['data']['attributes']['orderNumber'],
                    'voucherNumber' => $responseData['data']['attributes']['voucherNumber'],
                    'statusSipago' => $responseData['data']['attributes']['status'],
                    'subsidiaryId' => $responseData['data']['attributes']['subsidiaryId']
                ];

                return $result;
            }

            $result = [
                'error' => true,
                'status' => $httpCode
            ];
            return $result;

        }
        catch(Exception $e) {
            $this->log->logInfo('error'.$e->getMessage());
            $result = [
                'error' => true,
                'status' => null
            ];
            return $result;
        }
    }

}
