<?php
class Stripe extends CFormModel
{
	public $type = 'stripe';
	private $trType = 28; // todo change

    public $action;

    public $account;
    public $amount;
    public $currency;

    public $first_name;
    public $last_name;
    public $email;
    public $phone;
    public $transaction;

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

	public function rules(){
		return array(
            array('amount, currency, account', 'required', 'on'=>'deposit', 'message'=> Yii::t("main","36_cannot_be_blank")),
        );
	}
	
	public function init()
	{
        $this->action = Yii::app()->params['stripe_action'];
	}


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

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

    public function initData($data)
    {

        /*$ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
        if ($ip == '162.13.154.241') {
         var_dump('33333333');die();
        }*/
        $data2 = array();

        $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->amount = (int)$data["amount"];
        $this->account = (int)$data["transferTo"];

        $this->transaction = uniqid();
        $this->first_name = $Registration->firstName;
        $this->last_name = $Registration->lastName;
        $this->email = $Registration->email;
        $this->phone = $Registration->phone;

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

        return $data2;
    }

    public function parseCallback($json)
    {
        if($this->isSuccess()){
            $res = $this->ApplyTransaction();
        }
    }

    public function initRequest($data)
    {
        $res = $this->getRequest();

        $this->setScenario('return2');


        if(isset($res['status'])){
            $this->status = $res['status'];
        }
        if(isset($res['customer']['id']) && isset($res['reference'])){
            $this->customer_id = $res['customer']['id'];
        }
        if(isset($res['description'])){
            $this->description = $res['description'];
        }
        if(isset($res['transaction'])){
            $this->attributes = $res['transaction'];
        }
    }

    public function sendRequest($params)
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->action,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($params),
            CURLOPT_HTTPHEADER => array(
                "authorization: Bearer ".($this->currency === 'USD' ? $this->ivp_test_usd : $this->ivp_test),
                "content-type: application/json"
            ),
        ));

        $response = json_decode(curl_exec($curl), true);
        $err = curl_error($curl);
        curl_close($curl);

        if(isset($response['status'])){ // && $response['status'] == 'INITIATED'
            return $response;
        }

        return $err;
    }

    public function getRequest()
    {
        /*$curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->action.'/'.$this->tap_id,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            //CURLOPT_POSTFIELDS => json_encode($params),
            CURLOPT_HTTPHEADER => array(
                "authorization: Bearer ".($this->currency === 'USD' ? $this->ivp_test_usd : $this->ivp_test),
                "content-type: application/json"
            ),
        ));

        $response = json_decode(curl_exec($curl), true);
        $err = curl_error($curl);
        curl_close($curl);


        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/tap.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' return parse '.$_SERVER['REMOTE_ADDR'].' '.date('Y-m-d H:i:s').' | '.$this->action.'/'.$this->tap_id.' | '.json_encode($response).'
                ');

        if(isset($response['status'])){
            return $response;
        }

        return $err;*/
    }

    public function confirmOnReturn()
    {
        return true;
    }

	public function newTransaction($accountID, $value, $transactionID, $currency = 'AED', $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);

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/tap.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' newTapTransaction  '.$this->type .' '.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/ApplyTapTransaction?errorcode='.($this->status == 'CAPTURED' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->transaction.'&depValue=0&currency=');
	    //var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyTapTransaction?errorcode='.($this->status == 'CAPTURED' ? 'APPROVED' : 'ERROR').'&transactionid='.$this->transaction.'&depValue=0&currency=');die();

        $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/tap.txt',"a");
        fwrite($f, date('Y-m-d H:i:s').' ApplyTapTransaction  '.$this->type .' '.Yii::app()->params['json_server'].'/API/Transactions/ApplyTapTransaction?errorcode='.($this->status == 3 ? 'APPROVED' : 'ERROR').'&transactionid='.$this->transaction.'&depValue=0&currency= ||||| '.json_encode($Info).'<br/>\n
		');

        return  $Info;*/
	}

    public function checkResponse()
    {
        return true;
	}

    public function initResponse($data)
    {

    }

    public function isSuccess()
    {
        return true;
    }

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

}
