<?php
class TotalPay extends CFormModel
{
	public $type = 'totalpay';
	public $trType = 40;

    private $action;
    private $merchant_key;
    private $password;

    private $operation = 'purchase';
    private $methods = "card";

    public $number;
    public $amount;
    public $currency;
    public $description;

    public $cancel_url;
    public $success_url;
    public $recurring_init = "true";

    private $hash;

    private $redirectUrl;
    private $currencies = array('USD', 'AED');

    // response
    public $res;
    public $resultMessage;

	public function rules(){
		return array(
            array('cancel_url, success_url, description, currency, amount, number', 'required', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),

            //array('receiver_email, receiver_name, amount, refrence_no, item_name, item_id, payer_email, custom, payer_name, date', 'required', 'on'=>'response', 'message'=> Yii::t("main","36_cannot_be_blank")),
            //array('refrence_no_real, status, additional_memo', 'safe', 'on'=>'response', 'message'=> Yii::t("main","36_cannot_be_blank")),

            array('amount, account, currency, description, res', 'safe', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}
	
	public function init()
	{
        $this->action = Yii::app()->params['totalpay_action'];
        $this->merchant_key = Yii::app()->params['totalpay_merchant_key'];
        $this->password = Yii::app()->params['totalpay_password'];
        $this->redirectUrl = Yii::app()->params['totalpay_alt_url'].'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode');
	}

    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();
        $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
        $Registration = new Registration('Individual');
        $Registration->initIndv();
        $countries_code_two = $Registration->GetCountry('two');

        $this->number = $data2['data']["number"] = uniqid();
        $this->amount = $data2['data']["amount"] = (float)$data["amount"];
        $this->description = $data2['data']["description"] = ((int)$data["transferTo"]).'';

        $data2['data']['transaction_currency'] = 'USD';
        $data2['data']['currency'] = $this->currency = 'AED';

        if($data['currency'] === 'USD'){
            $data2['data']['transaction_amount'] = $data['amount'];
            $data2['data']['amount'] = $this->amount = round(stFunctions::currConv($data["currency"], 'AED', $this->amount), 2);
        }elseif($data['currency'] === 'AED') {
            $data2['data']['transaction_amount'] = round(stFunctions::currConv($data['currency'], 'USD', $this->amount), 2);
            $data2['data']['amount'] = $this->amount = $data['amount'];
        }

        // https://pay.bmfprofessional.com/payment/response/totalpay?d=i&code=86


        $amountFormated = number_format(ceil($this->amount), 2, '.', '');

        $main_json = [
            "merchant_key" => $this->merchant_key,
            "operation" => $this->operation,
            "methods" => $this->methods,
            "order"=> [
                "number" => $this->number,
                "amount" => $amountFormated,
                "currency" => $this->currency,
                "description" => $this->description
           ],
            "cancel_url" => Yii::app()->params['totalpay_alt_url'].'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode').'&res=error&ref',
            "success_url" => Yii::app()->params['totalpay_alt_url'].'/payment/userPaymentRedirect?type='.$this->type.'&code='.wlParams::get('officeCode').'&res=success&amount='.$data['amount'].'&description='.$this->description.'&currency='.$data['currency'].'&ref',
           "customer" => [
              "name" => $Registration->firstName." ".$Registration->lastName,
              "email" => stFunctions::randomizeEmail($Registration->email)
           ],
            "billing_address" => [
                "country"=> isset($countries_code_two[$Registration->country]) ? $countries_code_two[$Registration->country] : '',
                "city"=>$Registration->city,
                "address"=>substr($Registration->address,0,32),
                "phone"=>stFunctions::randomizePhone(str_replace('+', '', str_replace(" ","",$Registration->phone)))
            ],
           //"recurring_init"=> "true",
           "hash"=>sha1(md5(strtoupper($this->number.$amountFormated.$this->currency.$this->description.$this->password)))
        ];

        $json = json_encode($main_json);
        $checkoutUrl = Yii::app()->params['totalpay_action']."/api/v1/session";
        $getter = curl_init($checkoutUrl); //init curl
        curl_setopt($getter, CURLOPT_POST, 1); //post
        curl_setopt($getter, CURLOPT_POSTFIELDS, $json); //json
        curl_setopt($getter, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); //header
        curl_setopt($getter, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($getter, CURLOPT_SSL_VERIFYPEER, false);//todo this should be set to true in production
        $result = curl_exec($getter);
        $httpcode = curl_getinfo($getter, CURLINFO_HTTP_CODE);
        if(curl_errno($getter)) {
            return curl_error($getter);
        }

        $cRes = json_decode($result, true);
        #Check the Response and then redirect the user to Payment Widget

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            var_dump($checkoutUrl, $result);
            print_r($json);die();
        }*/


        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            //print_r( $json);die();
            var_dump($cRes, $main_json, $json, $checkoutUrl);die();
        }*/


        if(isset($cRes['errors'])){
            $errors = [];
            foreach ($cRes['errors'] as $error) {
               // var_dump($error['error_message']);die();
                $errors[] = $error['error_message'];
            }
            $_SESSION['message'][] = array("text" => 'TotalPay Errors '.implode(', ', $errors), "action" => Yii::app()->controller->id . "/" . Yii::app()->controller->action->id, "type" => "error");
            return null;
        }


        $data2['type'] = $this->type;
        //$data2['action'] = $this->action;
         $data2['action'] = $cRes['redirect_url'];

        $data2["message"] = Yii::t("funds","446_you_will_redir_secure_payment");

        return $data2;
    }
	
	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='.$this->trType);

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
            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='.$this->trType);die();
        }*/


        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/totalpay.txt',"a");
        fwrite($f, 'newTotalPayTransaction  '.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/ApplyTotalPayTransaction?errorcode='.(($this->status === 'SUCCESS') ? 'APPROVED' : 'CANCELED').'&transactionid='.$this->number.'&depValue='.$this->amount.'&currency='.$this->currency);

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/totalpay.txt',"a");
        fwrite($f, 'ApplyTotalPayTransaction  '.Yii::app()->params['json_server'].'/API/Transactions/ApplyTotalPayTransaction?errorcode='.(($this->status) ? 'APPROVED' : 'CANCELED').'&transactionid='.$this->number.'&depValue='.$this->amount.'&currency='.$this->currency.' ||||| '.json_encode($Info).'<br/>\n
		');

        return  $Info;
	}

    public function confirmOnReturn()
    {
        return true;
	}

    public function checkResponse()
    {
        return true;

	}

    public function isSuccess() {
        return $this->res === 'success';
    }

    public function getRedirectLink()
    {
        if($this->isSuccess()){
            return '/transaction.html?ammount='.$this->amount.'&currency='.$this->currency.'&account='.$this->description;
        }else{
            return '/transaction.html?errorText='.$this->resultMessage;
        }
    }

}