<?php
class AwePay extends CFormModel
{
	public $type = 'awepay';

    public $action;

    public $firstname;
    public $sid;
    public $rcode;
    public $lastname;
    public $email;
    public $phone;
    public $address;
    public $suburb_city;
    public $country;
    public $md;
    public $redirecturl;
    public $postbackurl;
    public $currency_code;
    public $amount_unit;
    public $account;

    public $card_name;
    public $card_no;
    public $card_ccv;
    public $card_exp_month;
    public $card_exp_year;

    //response
    public $amount_raw;
    public $ref1;
    public $ref2;
    public $ref3;
    public $ref4;
    public $currency;
    public $response;
    public $signature;
    public $wid;
    public $parent_txid;
    public $txid;
    public $tx_action;

    public $status;
    public $msg;


    private $currencies = array('USD');


	public function rules(){
		return array(
            /*array('sod, sinm1, siam1', 'required', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),
            array('result, sod, pid, account, md5, currency, amount, domain', 'required', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),
            */
            array('ref1, ref2, ref3, ref4, amount_raw, currency, response, signature, wid, parent_txid, txid, tx_action', 'required', 'on'=>'response', 'message'=> Yii::t("main","36_cannot_be_blank")),

            array('ref1, ref2, ref3, ref4, status, msg', 'required', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}
	
	public function init()
	{
        if($this->getScenario() == 'cc'){
            $this->action = 'https://admin.awepay.com/soap//tx3.php?wsdl';
        }else{
            $this->action = 'https://secure.awepay.com/index.php';
        }
        $this->sid = 2260;
        $this->rcode = 'c71006';

	}

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

    public function attributeLabels(){
        return array(
//            'sinm1' => Yii::t("main",'157_account'),
        );
    }

    public function initData($data)
    {
        $tr = uniqid();
        $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
        $redirecturl = $http.'//'.$_SERVER["SERVER_NAME"].'/awePayTrans.html?isUser';
        $postbackurl = $http.'//'.$_SERVER["SERVER_NAME"].'/awePayTrans.html';

        //var_dump($data);die();

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

        if($this->getScenario() == 'cc'){
            //var_dump($data);die();
            $data2 = array(
                "sid" => $this->sid,
                "rcode" => $this->rcode,
                "udetails" => array(
                    "username" => "",
                    "password" => "",
                    "firstname" => $data['firstName'],
                    "lastname" => $data['lastName'],
                    "email" => $data['email'],
                    "phone" => $data['phone'],
                    "mobile" => "",
                    "address" => $data['address'],
                    "suburb_city" => $data['city'],
                    "state" => "AU",
                    "postcode" => "4000",
                    "country" => "AU",
                    "ship_firstname" => "",
                    "ship_lastname" => "",
                    "ship_address" => "",
                    "ship_suburb_city"=> "",
                    "ship_state" => "",
                    "ship_postcode" => "",
                    "ship_country" => "",
                    "bank_name" => "",
                    "bank_phone" => "",
                    "ssn" => "",
                    "dl" => "",
                    "dob" => "",
                    "uip" => $_SERVER['REMOTE_ADDR']
                ),
                "paydetails" => array(
                    "payby" => "visa",
                    "card_name" => isset($data['userName']) ? $data['userName'] : $data['firstName'].' '.$data['lastName'],
                    "card_no" => $data['ccFullNumber'],
                    "card_ccv" => $data['cvc_code'],
                    "card_exp_month" => $data['exp_month'],
                    "card_exp_year" => $data['exp_year'],
                    "md" => $tr,
                    "redirecturl" => $redirecturl,
                    "useragent" => $_SERVER["HTTP_USER_AGENT"],
                    "browseragent" => $_SERVER["HTTP_ACCEPT"],
                    "routing_no" => "",
                    "account_no" => (int)$data['transferTo'],
                    "type" => "",
                    "regulation_e" => "",
                    "class" => "",
                    "receive_name" => ""
                ),
                "cart" => array(
                    "items" => array(
                        array(
                            "name"=>(int)$data['transferTo'],
                            "quantity"=> 1,
                            "amount_unit"=>$data['amount'],
                            "item_no"=>"",
                            "item_desc"=>""
                        )
                    ),
                    "summary" => array(
                        "quantity"=> 1,
                        "amount_purchase"=>$data['amount'],
                        "amount_shipping"=>"0",
                        "currency_code" => $data['currency']
                    )
                ),
                "txparams" => array(
                    "wid" => $tr,
                    "tid" => "",
                    "ref1" => (int)$data['transferTo'],
                    "ref2" => $this->getScenario(),
                    "ref3" => $data['amount'],
                    "ref4" => $data['currency'],
                    "addinfo" => (int)$data['transferTo'],
                    "cmd" => "",
                    "postbackurl" => $postbackurl
                )
            );
        }else{

            $tmp = array(
                'firstname' => isset($data['firstName']) ? $data['firstName'] : '',
                'lastname' => isset($data['lastName']) ? $data['lastName'] : '',
                'email' => isset($data['email']) ? $data['email'] : '',
                'phone' => isset($data['phone']) ? $data['phone'] : '',
                'address' => isset($data['address']) ? $data['address'] : '',
                'suburb_city' => isset($data['city']) ? $data['city'] : '',
                'country' => isset($countries_code_two[$data['country']]) ? $countries_code_two[$data['country']] : '',


                'sid' => $this->sid,
                'wid' => $tr,
                'ref1' => (int)$data['transferTo'],
                'ref2' => $this->getScenario(),
                'ref3' => $data['amount'],
                'ref4' => $data['currency'],
                'addinfo' => (int)$data['transferTo'],
                'shipping' => 0,

                'successurl' => $redirecturl.'&st=success',
                'failureurl' => $redirecturl.'&st=error',
                'postback_url' => $postbackurl,
                'item_quantity' => array(1),
                'item_name' => array((int)$data['transferTo']),
                'item_no' => array(""),
                'item_desc' => array($data['currency']),
                'item_amount_unit' => array($data['amount']),
            );

            //var_dump($tmp);die();
            $data2['data'] = $tmp;
            $data2['type'] = ($this->getScenario() == 'cc') ? 'awepay' : 'awepayshp';
            //var_dump($data2);die();
        }

        //var_dump($data2);die();

        return $data2;
    }

    public function sendData($params)
    {
        $client = new SoapClient($this->action);

        $response = $client->__soapCall("processPayment", $params);

        //var_dump($response);die();

        return $response;
    }
	
	public function newTransaction($accountID, $value, $transactionID, $currency = 'USD', $Id = ''){

	    $trType = ($this->getScenario() == 'cc') ? 16 : 17;

	    //var_dump(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='.$trType);die();

        $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='.$trType);

        //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=14');die();



        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/awepayResponse.txt',"a");
            fwrite($f, ' '.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='.$trType.' ||||| '.json_encode($Info).'<br/>\n
		');

        return  $Info;
	}

	public function ApplyAwepayTransaction(){

        $function = ($this->ref2 == 'cc') ? 'ApplyAwepayCCTransaction' : 'ApplyAwepaySHPTransaction';


        //var_dump(Yii::app()->params['json_server'].'/API/Transactions/'.$function.'?errorcode='.$this->response.'&transactionid='.$this->wid.'&depValue=0&currency=');die();
	    $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/'.$function.'?errorcode='.$this->response.'&transactionid='.$this->wid.'&depValue=0&currency=');

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/awepayResponse.txt',"a");
        fwrite($f, ' '.Yii::app()->params['json_server'].'/API/Transactions/'.$function.'?errorcode='.$this->response.'&transactionid='.$this->wid.'&depValue=0&currency= ||||| '.json_encode($Info).'<br/>\n
		');

        return  $Info;
	}

    public function checkResponse()
    {
        if($this->getScenario() == 'response'){
            return sha1($this->parent_txid.$this->txid.$this->tx_action.$this->response.$this->rcode) == $this->signature;
        }else{
            return true;
        }
	}

	public function decrypt($string)
	{
        $key = $this->rcode;
        $result = "";
        $string = base64_decode($string);

        for($i=0; $i<strlen($string); $i++) {
            $char = substr($string, $i, 1);
            $keychar = substr($key, ($i % strlen($key))-1, 1);
            $char = chr(ord($char)-ord($keychar));
            $result.=$char;
        }
        //var_dump($result);die();

        parse_str($result,$result);

        return $result;
    }




}