<?php
class accentPay extends CFormModel
{
	public $type = 'accentpay';
	private $trType = 22;

    public $action;

    private $secret;
    private $projectId;

    /* - ----- - - - - -- - - - - - - -*/
    public $amount;
    public $currency;
    public $firstName;
    public $lastName;
    public $phone;
    public $email;
    public $country;
    public $city;
    public $description;
    public $transactionId;

    private $failUrl;
    private $successUrl;

    /* - ----- - - - - -- - - - - - - -*/

    //response
    public $status;


    // return
    public $account;
    /* - ----- - - - - -- - - - - - - -*/

    private $currencies = array('USD'=>'USD', 'EUR'=>'EUR');

    public $server;

    private $Callback;

	public function rules(){
		return array(
            array('amount, currency, description', 'required', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),
            array('firstName, lastName, phone, email, country, city', 'safe', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),

            array('amount, currency, account', 'required', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),
            array('transactionId, status, description, amount, currency', 'required', 'on'=>'response', 'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}
	
	public function init()
	{
        $this->action = 'https://paymentpage.ecommpay.com/payment';
        $this->secret = "c548f6f6cacdd467fca79e4453bb1dc52fe6476b24a5fba39f5b1395669b2c8e44a91b8af6922c4e2a67de0e168386b3fc559a84ba0ba92e1c5953c559c966d1";
        $this->projectId = "9921";

        if($this->getScenario() == 'response'){
            require_once $_SERVER['DOCUMENT_ROOT']."/protected/config/accent/Callback.php";
            require_once $_SERVER['DOCUMENT_ROOT']."/protected/config/accent/SignatureHandler.php";
        }
	}

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

    public function attributeLabels(){
        return array(
            'description' => Yii::t("main",'157_account'),
            'amount' => Yii::t("funds",'9_amount'),
        );
    }

    public function initData($data)
    {
        $data2 = array();
        require_once $_SERVER['DOCUMENT_ROOT']."/protected/config/accent/Gate.php";
        require_once $_SERVER['DOCUMENT_ROOT']."/protected/config/accent/Payment.php";

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

        $server = ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:').'//'.$_SERVER["SERVER_NAME"];
        $this->transactionId = uniqid();

        $this->currency = $data["currency"];
        $this->amount = (int)$data["amount"]*100;
        $this->description = (int)$data["transferTo"];

        $this->firstName = $Registration->firstName;
        $this->lastName = $Registration->lastName;
        $this->phone = $Registration->phone;
        $this->email = $Registration->email;
        $this->country = $countries_code_two[$Registration->country];
        $this->city = $Registration->city;
        $this->failUrl = $server.'/accentPayTrans?isUser&cancel';
        $this->successUrl = $server.'/accentPayTrans?isUser&success&account='.$this->description.'&amount='.$data["amount"].'&currency='.$this->currency;


        $gate = new Gate($this->secret);
        $payment = new Payment($this->projectId, $this->transactionId);
        $payment->setPaymentAmount($this->amount)
            ->setPaymentCurrency($this->currency)
            ->setCustomerFirstName($this->firstName)
            ->setCustomerLastName($this->lastName)
            ->setCustomerPhone($this->phone)
            ->setCustomerEmail($this->email)
            ->setCustomerCountry($this->country)
            ->setCustomerCity($this->city)
            ->setPaymentDescription($this->description)
            ->setRedirectFailUrl($this->failUrl)
            ->setRedirectSuccessUrl($this->successUrl);

        $data2['data']['link'] = $gate->getPurchasePaymentPageUrl($payment);
        $data2['data']['tr'] = $this->transactionId;
        $data2['data']['transferTo'] = $this->description;
        $data2['data']['currency'] = $this->currency;
        $data2['data']['amount'] = $data["amount"];



        /* ----------------------------------------------------------- */



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

        


        return $data2;
    }

    public function getSecret()
    {
        return $this->secret;
    }
	
	public function newTransaction($accountID, $value, $transactionID, $currency = 'KWD', $Id = ''){
        //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='.$this->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='.$this->trType);

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

        return  $Info;
	}

	public function ApplyTransaction(){
	    $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyAccentPayTransaction?errorcode='.($this->status == 'success' ? 'success' : 'error').'&transactionid='.$this->transactionId.'&depValue=0&currency=');

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

        //var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/ApplyAccentPayTransaction?errorcode='.($this->status == 'success' ? 'success' : 'error').'&transactionid='.$this->transactionId.'&depValue=0&currency=');die();

        return  $Info;
	}

    public function checkResponse()
    {
        if(isset($this->Callback) && !empty($this->Callback)){
            return $this->Callback->checkSignature();
        }else{
            return false;
        }

	}



    /*public function showRedirectLink()
    {
        $server = ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:').'//'.$_SERVER["SERVER_NAME"];

        if(strstr($this->udf5, '_')){
            $tmp = explode('_', $this->udf5);
            if(isset($tmp[1]) && $tmp[1] === 44){
                $server = 'https://my.swissfs.sa.com';
            }elseif(isset($tmp[1]) && $tmp[1] === '44sifx'){
                $server = 'https://my.sifx.sa.com';
            }
        }

        return 'REDIRECT='.$server."/transaction.html?PaymentID=" . $this->paymentid . "&Result=" . $this->result . "&PostDate=" . $this->postdate . "&TranID=" . $this->tranid . "&Auth=" . $this->auth . "&Ref=" . $this->ref . "&TrackID=" . $this->trackid . "&UDF1=" . $this->udf1 . "&UDF2=" .$this->udf2  . "&UDF3=" . $this->udf3  . "&UDF4=" . $this->udf4 . "&UDF5=" . $this->udf5  ;
	}*/

    public function initResponse($data)
    {
        if(!empty($data)){
            $SignatureHandler = new SignatureHandler($this->getSecret());
            $this->Callback = new Callback($data, $SignatureHandler);


            $details = $this->Callback->getPayment();

            $this->transactionId = $this->Callback->getPaymentId();
            $this->status = $this->Callback->getPaymentStatus();
            $this->description = $details['description'];
            $this->amount = $details['sum']['amount'];
            $this->currency = $details['sum']['currency'];

        }
    }

}
