<?php

namespace modules\paypal\classes\payment;

use payment\PaymentAPI;
use System\Config;
use System\Exception;
use System\Tools;

class PayPalAPI extends PaymentAPI
{
    protected  $_form_action = 'https://api.sandbox.paypal.com/';

    public function __construct(array $shop)
    {
        parent::__construct($shop);
        if($shop['test_mode']){
            $this->_form_action = 'https://api.sandbox.paypal.com/';
        } else {
            $this->_form_action = 'https://api.paypal.com/';
        }
    }

    public function setFormAction(){

    }

    public function getFormValues()
    {}

    public function getFields()
    {}

    public function getSign($fields)
    {}

    final protected function _checkSignature(array $source)
    {}

    public function createPayment(array $options)
    {
        parent::createPayment($options); // TODO: Change the autogenerated stub


        $pconfig = Config::factory('payments');
        // echo $res2['access_token'];
        $token = $pconfig->paypal->token_data['token'];


        if($pconfig->paypal->token_data['expires_in'] <= time()) {


                $headers = array(
                    'Content-Type: application/x-www-form-urlencoded',
                    'Accept: application/json',
                    'Accept-Language: en_US',
                );

                $json = 'grant_type=client_credentials';

                $curl = curl_init($this->getFormAction() . 'v1/oauth2/token');
                // curl_setopt($curl, CURLOPT_URL, );
                curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

                // curl_setopt($curl, CURLOPT_POST,    1 );
                curl_setopt($curl, CURLOPT_POSTFIELDS, $json);

                curl_setopt($curl, CURLOPT_USERPWD, $this->_shop['client_id'] . ':' . $this->_shop['secret']);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                $res = curl_exec($curl);
                curl_close($curl);
                $res2 = json_decode($res, 1);
                // print_r($res2);
            if(isset($res2['access_token'])) {
                $token = $res2['access_token'];
                $pconfig->paypal->token_data['expires_in'] = time() + $res2['expires_in'];

                $pconfig->paypal->token_data['token'] = $token;
                $pconfig->save();
            }
        }

        $headers = array(
            'Content-Type: application/json',
            'Authorization: Bearer '.$token
        );

        $json = json_encode(array(
            'intent' => 'sale',
            'redirect_urls' => array(
                'return_url' => $this->getStatusUrl(),
                'cancel_url' => $this->getFailUrl()
            ),
            'payer'        => array('payment_method' => 'paypal'),
            'transactions' => array(array(
                'amount' => array(
                    'total'     => $this->getAmountAsString(),
                    'currency'  => 'USD'
                ),
                'invoice_number' => $this->getId(),
                'description' => $this->getDescription()
            ))

        ));

        $curl = curl_init($this->getFormAction().'v1/payments/payment');
       // curl_setopt($curl, CURLOPT_URL, );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        curl_setopt($curl, CURLOPT_POST,    1 );
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_POSTFIELDS, $json );
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
        $res = curl_exec($curl);
        curl_close($curl);
        $res2 = json_decode($res, 1);

        if(isset($res2['links'][1]['href'])) {
            $link = $res2['links'][1]['href'];
            // echo '<br>'.$link;
            Tools::redirect($link);
        }else{
            Tools::redirect('/');
        }
      // print_r($res2);

    }

    public function getPayment()
    {
        return $this;
    }

    public function approvePayment($array)
    {
        $pconfig = Config::factory('payments');
        // echo $res2['access_token'];
        $token = $pconfig->paypal->token_data['token'];

        $paymentId = $array['paymentId'];
        $payer_id = $array['PayerID'];

        $headers = array(
            'Content-Type: application/json',
            'Authorization: Bearer '.$token
        );

        $json = json_encode(array(
            'payer_id' => $payer_id

        ));

        $curl = curl_init($this->getFormAction().'v1/payments/payment/'.$paymentId.'/execute');

        // curl_setopt($curl, CURLOPT_URL, );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        curl_setopt($curl, CURLOPT_POST,    1 );
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_POSTFIELDS, $json );
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
        $res = curl_exec($curl);
        curl_close($curl);

        $res2 = json_decode($res, 1);
        $order_id      = ($res2['transactions'][0]['invoice_number']);


        $this->_id     = $order_id;
        $this->_amount = $res2['transactions'][0]['amount']['total'];
       

        if($res2['state'] == 'approved'){
            $this->verified = true;

        } else {
            $this->verified = false;
        }

        return $this->getPayment();
    }
}