<?php

/**
 * Example of using the class:
 * require_once 'AstroPayStreamline.class.php';
 * $aps = new AstroPayStreamline();
 * $banks = $apd->get_banks_by_country('BR', 'json');
 *
 * Available functions:
 * - newinvoice($invoice, $amount, $bank, $country, $iduser, $cpf, $name, $email, $currency, $description, $bdate, $address, $zip, $city, $state, $return_url, $confirmation_url)
 * - get_status($invoice)
 * - get_exchange($country = 'BR', $amount = 1) {befault: $country = BR | $amount = 1}
 * - y($country, $type) {befault: $country = BR | $type = 'json'}
 *
 */

/**
 * Class of AstroPay Streamline
 *
 * @author Santiago del Puerto (santiago@astropay.com)
 * @version 1.0
 *
 */

class AstroPay extends CFormModel{

    /**************************
     * Merchant configuration *
     **************************/
    private $x_login = 'dc2a1cb876';
    private $x_trans_key = 'bcb4673aab';

    private $x_login_for_webpaystatus = '7f8a755dca';
    private $x_trans_key_for_webpaystatus = '5d99d454f6';

    private $secret_key = '4de2dce61777e3bdc48b7c6486b3c6eec';

    private $sandbox = true;
    /*********************************
     * End of Merchant configuration *
     *********************************/

    public $x_invoice;
    public $x_amount;
    public $x_bank;
    public $x_country;
    public $x_iduser;
    public $x_cpf;
    public $x_name;
    public $x_email;
    public $x_currency;
    public $x_description;
    public $x_bdate;
    public $x_address;
    public $x_zip;
    public $x_city;
    public $x_state;
    public $x_return;
    public $x_confirmation;

    public $type = 'astropay';
    private $currencies = ['USD'];



    public function getAttribute($name){
        return $this->$name;
    }

    public function initData($data)
    {
        //var_dump($data);die();

        $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';

        $Registration = new Registration('Individual');
        $Registration->initIndv();
        $countries_code_two = $Registration->GetCountry('two');


        $this->x_invoice = uniqid();
        $this->x_amount = $data['amount'];
        $this->x_bank = 'TE';
        $this->x_country = $countries_code_two[$Registration->country];
        $this->x_iduser = (int)$data['transferTo'];
        $this->x_cpf = $data['x_cpf'];
        $this->x_name = $Registration->firstName.' '.$Registration->lastName;
        $this->x_email = $Registration->email;
        $this->x_currency = $data['currency'];
        $this->x_description = (int)$data['transferTo'];
        $this->x_bdate = '';
        $this->x_address = '';// rawurlencode($Registration->address);
        $this->x_zip = '';
        $this->x_city = '';//$Registration->city;
        $this->x_state = '';
        $this->x_return = $http.'//'.$_SERVER["SERVER_NAME"].'/payment/globePayTrans?isUser';
        $this->x_confirmation = $http.'//'.$_SERVER["SERVER_NAME"].'/payment/globePayTrans';


        $response = $this->newinvoice();
        $decoded_response = json_decode($response);

        //var_dump($decoded_response);die();

        $post_data = [];

        if($decoded_response->status == '0'){
            $post_data['data']['amount'] = $this->x_amount;
            $post_data['data']['currency'] = $this->x_currency;
            $post_data['data']['account'] = $this->x_iduser;
            $post_data['data']['transactionID'] = $this->x_invoice;


            $post_data['type'] = $this->type;
            $post_data['action'] = $decoded_response->link;
            $post_data['message'] = Yii::t("funds","446_you_will_redir_secure_payment");
        }

        return $post_data;
    }

    public function newTransaction($accountID, $value, $transactionID, $currency, $Id = ''){
        $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id='.$Id.'&accountID='.$accountID.'&trType=20');

        //var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id='.$Id.'&accountID='.$accountID.'&trType=20');die();


        /*$f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/globepay.txt',"a");
        fwrite($f, 'newGlobePayTransaction  '.Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id='.$Id.'&accountID='.$accountID.'&trType=19'.' ||||| '.json_encode($Info).'<br/>\n
		');*/

        return  $Info;
    }

    // ApplyAstroPayTransaction(string errorcode, string transactionid, double depValue, string currency)

    /*****************************************************
     * ---- PLEASE DON'T CHANGE ANYTHING BELOW HERE ---- *
     *****************************************************/



    private $url = array(
        'newinvoice' => '',
        'status' => '',
        'exchange' => '',
        'banks' => ''
    );
    private $errors = 0;

    public function __construct(){
        $this->errors = 0;

        $this->url['newinvoice'] = 'https://astropaycard.com/api_curl/streamline/newinvoice/';
        $this->url['status'] = 'https://astropaycard.com/apd/webpaystatus';
        $this->url['exchange'] = 'https://astropaycard.com/apd/webcurrencyexchange';
        $this->url['banks'] = 'https://astropaycard.com/api_curl/apd/get_banks_by_country';

        if ($this->sandbox){
            $this->url['newinvoice'] = 'https://sandbox.astropaycard.com/api_curl/streamline/newinvoice';
            $this->url['status'] = 'https://sandbox.astropaycard.com/apd/webpaystatus';
            $this->url['exchange'] = 'https://sandbox.astropaycard.com/apd/webcurrencyexchange';
            $this->url['banks'] = 'https://sandbox.astropaycard.com/api_curl/apd/get_banks_by_country';
        }
    }

    public function newinvoice(){

        $params_array = array(
            //Mandatory
            'x_login' => $this->x_login,
            'x_trans_key' => $this->x_trans_key,
            'x_invoice' => $this->x_invoice,
            'x_amount' => $this->x_amount,
            'x_bank' => $this->x_bank,
            'type'=>'json',
            'x_country' => $this->x_country,
            'x_iduser' => $this->x_iduser,
            'x_cpf' => $this->x_cpf,
            'x_name' => $this->x_name,
            'x_email' => $this->x_email,
        );

        //Optional
        if(!empty($currency)){
            $params_array['x_currency']=$this->x_currency;
        }
        if(!empty($description)){
            $params_array['x_description']=$this->x_description;
        }
        if(!empty($bdate)){
            $params_array['x_bdate']=$this->x_bdate;
        }
        if(!empty($address)){
            $params_array['x_address']=$this->x_address;
        }
        if(!empty($zip)){
            $params_array['x_zip']=$this->x_zip;
        }
        if(!empty($city)){
            $params_array['x_city']=$this->x_city;
        }
        if(!empty($state)){
            $params_array['x_state']=$this->x_state;
        }
        if(!empty($return_url)){
            $params_array['x_return']=$this->x_return;
        }
        if(!empty($confirmation_url)){
            $params_array['x_confirmation']=$this->x_confirmation;
        }


        $message = $this->x_invoice .'V' . $this->x_amount .'I' . $this->x_iduser .'2' . $this->x_bank .'1' . $this->x_cpf .'H' . $this->x_bdate .'G' . $this->x_email .'Y' . $this->x_zip .'A' . $this->x_address .'P' . $this->x_city .'S' . $this->x_state . 'P';


        $control = strtoupper(hash_hmac('sha256', pack('A*', $message), pack('A*', $this->secret_key)));
        $params_array['control'] = $control;

        //var_dump($params_array);

        $response = $this->curl($this->url['newinvoice'], $params_array);
        return $response;
    }

    public function get_status($invoice){
        $params_array = array(
            //Mandatory
            'x_login' => $this->x_login_for_webpaystatus,
            'x_trans_key' => $this->x_trans_key_for_webpaystatus,
            'x_invoice' => $invoice
        );

        $response = $this->curl($this->url['status'], $params_array);
        return $response;
    }

    public function get_exchange($country = 'BR', $amount = 1){
        $params_array = array(
            //Mandatory
            'x_login' => $this->x_login_for_webpaystatus,
            'x_trans_key' => $this->x_trans_key_for_webpaystatus,
            'x_country' => $country,
            'x_amount' => $amount
        );

        $response = $this->curl($this->url['exchange'], $params_array);
        return $response;
    }

    public function get_banks_by_country($country = 'BR', $type = 'json'){
        $params_array = array(
            //Mandatory
            'x_login' => $this->x_login,
            'x_trans_key' => $this->x_trans_key,
            'country_code' => $country,
            'type' => $type
        );

        $response = $this->curl($this->url['banks'], $params_array);
        return $response;
    }


    /**
     * END OF PUBLIC INTERFACE
     */
    private function curl($url, $params_array) {
        $params = array();
        foreach ($params_array as $key => $value){
            $params[] = "{$key}={$value}";
        }
        $params = join('&', $params);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $response = curl_exec($ch);
        if (($error = curl_error($ch)) != false) {
            $this->errors++;

            if ($this->errors >= 5){
                die("Error in curl: $error");
            }

            sleep(1);
            $this->curl($url, $params_array);
        }
        curl_close($ch);

        $this->errors = 0;
        return $response;
    }

}
