<?php

namespace modules\bepaid\classes\payment;
use payment\PaymentAPI;
use System\Exception;
use System\Logger;

class BePaidAPI extends PaymentAPI
{

    public function setFormAction(){
        $this->_form_action = '';
    }

    public function getFormValues()
    {
        $fields            = array();


        // $fields['s']       = $this->getSign($fields);

        return $fields;
    }

    public function getFormAction()
    {
        $data = array(
            'checkout' => array(
                'transaction_type' => 'payment',
                'settings' => array(
                    'success_url'   => $this->getSuccessUrl(),
                    'decline_url'   => $this->getFailUrl(),
                    'fail_url'      => $this->getFailUrl(),
                    'cancel_url'    => $this->getFailUrl(),
                    'notification_url' => $this->getStatusUrl(),
                    'language' => $this->getLocale()
                ),
                'order' => array(
                    'currency'      => $this->getCurrency(),
                    'amount'        => $this->getAmount() * 100,
                    'description'   => $this->getDescription(),
                    'tracking_id'   => $this->getId()
                )

            )
        );

        //print_r($data);
        // print_r($this->_shop);

        $data_string = json_encode($data);

        $ch = curl_init('https://checkout.bepaid.by/ctp/api/checkouts');
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Accept: application/json',
                'Authorization: Basic '. base64_encode($this->_shop['shop_id'].":".$this->_shop['key']),
                'Content-Length: ' . strlen($data_string))
        );

        $result = curl_exec($ch);

        //print_r($result);
        //exit;
        $data = json_decode($result,1);

        $this->_form_action = $data['checkout']['redirect_url'];

        return parent::getFormAction(); // TODO: Change the autogenerated stub
    }

    public function getSign($fields)
    {
        // TODO: Implement getSign() method.
    }

    public function getFields()
    {

    }


    final protected function _checkSignature(array $source)
    {

        Logger::log('bePaid: '.json_encode($source));

        if($source['transaction']['payment']['status'] == 'successful'){
            return true;
        }

        return false;
    }

    public function getPayment()
    {


        $source = json_decode(file_get_contents('php://input'), 1);


        if (!$source || empty($source)) {
            throw new Exception('Source not exist');
        }

        if($_SERVER['PHP_AUTH_USER']  !=  $this->_shop['shop_id']){
            throw new Exception('Auth user not valid');
        }


        if($_SERVER['PHP_AUTH_PW']  !=  $this->_shop['key']){
            throw new Exception('Auth pw not valid');
        }

        if ($this->_checkSignature($source))
            $this->verified = true;
        else
            throw new Exception('Signature does not match the data');

        Logger::log('bePaid _id: '.$source['transaction']['tracking_id']);
        Logger::log('bePaid _amount: '.$source['transaction']['amount']);
        $this->_id          = $source['transaction']['tracking_id'];
        $this->_amount      = $source['transaction']['amount'] / 100;


        return $this;

    }
}