<?php
namespace Trustpay;

class PaymentSkipPayThree extends Payment {
    
    protected $redirect;
    
    protected $wcOrder;
    
    public function setWCOrder($wcOrder)
    {
        $this->wcOrder = $wcOrder;
    }
    
    public function getUrl($paymentType) {
        
        /********** PaymentSkipPay PAYMENT *************/
        
        // token
        
        $url = self::URL_TOKEN;
        
        $data = array('grant_type' => 'client_credentials');

        $username = $this->account_id;
        $password = $this->secret_key;
        $auth = base64_encode("$username:$password");

        $options = array(
           'http' => array(
              'header'  => array(
                 "Authorization:Basic $auth",
                 "Content-type:application/x-www-form-urlencoded",
              ),
              'method'  => 'POST',
              'content' => http_build_query($data)
           ),
        );
        /*
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $options['http']['header']);

        $response = curl_exec($ch);
        curl_close($ch);
        */
        
        $context  = stream_context_create($options);
        $response = file_get_contents($url, false, $context);
        
        $response = json_decode($response, true);
        
        if(isset($response['access_token'])) {
            return $this->paySkipPay($response['access_token']);
        }
        
        return '';
    }
    
    protected function paySkipPay($token)
    {
        $url = self::URL_PAYMENT;
        
        $items = array();
        $itemTaxes = $this->wcOrder->get_items('tax');
        foreach ( $this->wcOrder->get_items() as $item_id => $item ) {
            $items[] = array(
                        'Code' => $item->get_product_id(),
                        'Name' => mb_substr($item->get_name(), 0, 255),
                        'Price' => number_format($item->get_total() + $item->get_total_tax(), 2, '.', ''), // tu sa nenasobi kvantitou ako v magente
                        'Vat' => number_format($item->get_total_tax(), 2, '.', ''),
                        //'VatRate' => \WC_Tax::get_rate_percent( $itemTaxes[$item_id]->get_rate_id() )
                        'VatRate' => round(($item->get_total_tax() / $item->get_total()) * 100, 2)
                      );
        }
        
        
        $shippingAmount = $this->wcOrder->get_shipping_total();
        if($shippingAmount > 0) {
            $items[] = array(
                        'Code' => '0',
                        'Name' => 'Shipping',
                        'Price' => number_format($shippingAmount + $this->wcOrder->get_shipping_tax(), 2, '.', ''),
                        'Vat' => number_format($this->wcOrder->get_shipping_tax(), 2, '.', ''),
                        'VatRate' => round(($this->wcOrder->get_shipping_tax() / $shippingAmount) * 100, 2)
                      );
        }
        
        $data = array(
            'PaymentMethod' => 'SkipPay',
            'MerchantIdentification' => array(
                'ProjectId' => $this->account_id
            ),
            'PaymentInformation' => array(
                'Amount' => array(
                   'Amount' => (string) number_format($this->order->getTotal(), 2, '.', ''),
                   'Currency' => (string)$this->order->getCurrency()
                ),
                'Localization' => (string)$this->localization,
                'References' => array(
                   'MerchantReference' => (string)$this->order->getId()
                ),
                'Debtor' => array(
                    'FirstName' => $this->wcOrder->get_shipping_first_name(),
                    'LastName' => $this->wcOrder->get_shipping_last_name(),
                    'Email' => $this->order->getEmail(),
                    'Phone' => $this->wcOrder->get_billing_phone(), // get_shipping_phone vracia null
                ),
                'OrderedItems' => $items,
                'FinancingType' => 'PAY_IN_THREE'
            ),
            'CallbackUrls' => array(
                
                'Success' => (string)$this->returnUrl,
                'Cancel' => (string)$this->cancelUrl,
                'Error' => (string)$this->errorUrl,
                'Notification' => (string)$this->notificationUrl
            ),
        );
        
        if($this->redirect === 'true') {
            $data['PaymentInformation']['IsRedirect'] = 'true';
        }
        
        $options = array(
          'http' => array(
             'header'  => array(
                "Authorization:bearer $token",
                'Content-type: text/json',
                'Cache-Control: no-store, no-cache, must-revalidate, max-age=0',
                 'Cache-Control: post-check=0, pre-check=0',
                 'Pragma: no-cache'
             ),
             'method'  => 'POST',            
             'content' => json_encode($data)
          ),
        );
        /*
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $options['http']['header']);

        $response = curl_exec($ch);
        curl_close($ch);
        */
        
        $context  = stream_context_create($options);
        $response = file_get_contents($url, false, $context);
        
        $response = json_decode($response, true);
        //var_dump($response,json_encode($data), $token); die;
        //var_dump(json_encode($data)); die;
        if(isset($response['GatewayUrl'])) {
            return $response['GatewayUrl'];
        }
        
        return '';
    }
    
    protected function getSigData($paymentType) {
        return array(
            $this->account_id,
            number_format($this->order->getTotal(), 2, '.', ''),
            $this->order->getCurrency(),
            $this->order->getId(),
            $paymentType
        );
    }
}