<?php
namespace Trustpay;

class PaymentCard extends Payment {
    public function getUrl($paymentType) {
        
        /********** Card 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->payCard($response['access_token']);
        }
        
        return '';
    }
    
    protected function payCard($token)
    {
        $url = self::URL_PAYMENT;
                
        $data = array(
            'PaymentMethod' => 'Card',
            'MerchantIdentification' => array(
                'ProjectId' => $this->account_id,
                'Email' => (string)$this->order->getEmail()
            ),
            'PaymentInformation' => array(
                //'RemittanceInformation' => TRUSTPAY_VERSION,
                'Amount' => array(
                   'Amount' => (string) number_format($this->order->getTotal(), 2, '.', ''),
                   'Currency' => (string)$this->order->getCurrency()
                ),
                'Localization' => (string)$this->localization,
                /*
                'DebtorAgent' => array(
                    //'Bic' => 'TPAYSKBX'
                    'Bic' => ''
                ),
                 */
                'Debtor' => array(
                    'Name' =>  (string)$this->order->getCardHolder(),
                    'Address' => array(
                        'PostalCode' => (string)$this->order->getBillingPostcode(),
                        'City' => (string)$this->order->getBillingCity(),
                        'CountryCode' => (string)$this->order->getBillingCountry(),
                        'Lines' =>  (string)$this->order->getBillingStreet(),
                    )
                ),
                'References' => array(
                   'MerchantReference' => (string)$this->order->getId()
                ),
                'CardTransaction' => array(
                    'PaymentType' => 'Purchase'
                )
            ),
            'CallbackUrls' => array(
                
                'Success' => (string)$this->returnUrl,
                'Cancel' => (string)$this->cancelUrl,
                'Error' => (string)$this->errorUrl,
                'Notification' => (string)$this->notificationUrl
            ),
        );
        
        if($this->isRedirect == "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);
        //var_dump($data); die;
        //var_dump($response); die;
         * 
         */
        
        
        $context  = stream_context_create($options);
        $response = file_get_contents($url, false, $context);
        
        $response = json_decode($response, true);
        
        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
        );
    }
}