<?php
class nganLuong extends CFormModel
{
	public $type = 'nganluong';

    public $action;

    public $receiver;
    public $order_code;
    public $return_url;
    public $cancel_url;
    public $txh_name;
    public $txt_email;
    public $txt_phone;
    public $price;
    public $transaction_info;
    public $currency;
    public $quantity = 1;
    public $tax = 0;
    public $discount = 0;
    public $fee_cal = 0;
    public $fee_shipping = 0;
    public $order_description;
    public $buyer_info;
    public $affiliate_code;

    public $merchant_site_code;
    public $secure_pass;

    public $payment_id;
    public $payment_type;
    public $error_text;
    public $secure_code;
    public $token_nl;

    private $currencies = array('USD', 'VND');


	public function rules(){
		return array(
            array('transaction_info, order_code, price, payment_id, payment_type, secure_code, token_nl', 'required', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),
            array('error_text', 'safe', 'on'=>'return', 'message'=> Yii::t("main","36_cannot_be_blank")),
		);
	}
	
	public function init()
	{
        $this->action = Yii::app()->params['ngan_action'];
        $this->receiver = Yii::app()->params['ngan_receiver'];
        $this->merchant_site_code = Yii::app()->params['ngan_merchant_site_code'];
        $this->secure_pass = Yii::app()->params['ngan_secure_pass'];
	}

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

    public function attributeLabels(){

        return array(
            //'sinm1' => Yii::t("main",'157_account'),
            //'siam1' => Yii::t("funds",'9_amount'),
        );
    }

    public function initData($data)
    {
        if (!Yii::app()->user->isGuest) {
            $http = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') ? 'https:' : 'http:';
            $Registration = new Registration('Individual');
            $Registration->initIndv();

            $data2['receiver'] = $this->receiver;
            $data2['order_code'] = $this->order_code =uniqid();
            $data2['return_url'] = $this->return_url = $http.'//'.$_SERVER["SERVER_NAME"].'/nganluongtrans.html?isuser';
            $data2['cancel_url'] = $this->cancel_url = $http.'//'.$_SERVER["SERVER_NAME"].'/nganluongtrans.html?isuser&canceal';
            $data2['txh_name'] = $this->txh_name = $Registration->firstName.' '.$Registration->lastName;
            $data2['txt_email'] = $this->txt_email = $Registration->email;
            $data2['txt_phone'] = $this->txt_phone = $Registration->phone;
            $data2['price'] = $this->price = (float)$data['amount'];
            $data2['transaction_info'] = $this->transaction_info = (int)$data['transferTo'];
            $data2['currency'] = $this->currency = strtolower($data['currency']);
            $data2['quantity'] = $this->quantity;
            $data2['tax'] = $this->tax;
            $data2['discount'] = $this->discount;
            $data2['fee_cal'] = $this->fee_cal;
            $data2['fee_shipping']= $this->fee_shipping;
            $data2['order_description'] = $this->order_description = "Thong tin don hang: ".$data2['order_code'];
            $data2['buyer_info'] = $this->buyer_info = $this->txh_name."*|*".$this->txt_email."*|*".$this->txt_phone;
            $data2['affiliate_code'] = $this->affiliate_code = "";

            $data3['data']['transaction_info'] = $data2['transaction_info'];
            $data3['data']['order_code'] = $data2['order_code'];
            $data3['data']['price'] = $data2['price'];
            $data3['data']['currency'] = $data['currency'];
            $data3['action'] = $this->buildCheckoutUrlExpand();

            return $data3;
        }
    }
	
	public function newTransaction($accountID, $value, $transactionID, $currency){
        //var_dump(Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=14');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=&accountID='.$accountID.'&trType=15');
	    //var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/NewTransaction?guid='.Yii::app()->user->id.'&transactionID='.trim($transactionID).'&currency='.$currency.'&value='.$value.'&Id=&accountID='.$accountID.'&trType=14');die();

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

        return  $Info;
	}

	public function ApplyNganluongTransaction($errorCode, $transactionid, $netValue = '0', $currency = ''){
	    //var_dump(Yii::app()->params['json_server'].'/API/Transactions/ApplyNganluongTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency);

	    $Info = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/Transactions/ApplyNganluongTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency);

        //var_dump($Info, Yii::app()->params['json_server'].'/API/Transactions/ApplyNganluongTransaction?errorcode='.$errorCode.'&transactionid='.$transactionid.'&depValue='.$netValue.'&currency='.$currency);die();

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

        return  $Info;
	}

    public function checkResponse()
    {
        return true;
        /*if($this->getScenario() == 'return'){
            return (md5(strtolower($this->sod.($this->amount*100).$this->salt)) == $this->md5);
        }else{
            return (md5(strtolower($this->sod.$this->ta.$this->salt)) == $this->md5);
        }*/
	}




	/************  Payment functions  ************/

    public function buildCheckoutUrlExpand()
    {
        $arr_param = array(
            'merchant_site_code'=>	strval($this->merchant_site_code),
            'return_url'		=>	strval(strtolower($this->return_url)),
            'receiver'			=>	strval($this->receiver),
            'transaction_info'	=>	strval($this->transaction_info),
            'order_code'		=>	strval($this->order_code),
            'price'				=>	strval($this->price),
            'currency'			=>	strval(strtolower($this->currency)),
            'quantity'			=>	strval($this->quantity),
            'tax'				=>	strval($this->tax),
            'discount'			=>	strval($this->discount),
            'fee_cal'			=>	strval($this->fee_cal),
            'fee_shipping'		=>	strval($this->fee_shipping),
            'order_description'	=>	strval($this->order_description),
            'buyer_info'		=>	strval($this->buyer_info), //"Họ tên người mua *|* Địa chỉ Email *|* Điện thoại *|* Địa chỉ nhận hàng"
            'affiliate_code'	=>	strval($this->affiliate_code)
        );

        $secure_code ='';
        $secure_code = implode(' ', $arr_param) . ' ' . $this->secure_pass;
        $arr_param['secure_code'] = md5($secure_code);
        //echo $arr_param['secure_code'];
        /* */

        if ($_SERVER['REMOTE_ADDR'] == '46.98.173.72') {
            var_dump($arr_param);
        }
        $redirect_url = $this->action;
        if (strpos($redirect_url, '?') === false) {
            $redirect_url .= '?';
        } else if (substr($redirect_url, strlen($redirect_url)-1, 1) != '?' && strpos($redirect_url, '&') === false) {
            $redirect_url .= '&';
        }

        /* */
        $url = '';
        foreach ($arr_param as $key=>$value) {
            $value = urlencode($value);
            if ($url == '') {
                $url .= $key . '=' . $value;
            } else {
                $url .= '&' . $key . '=' . $value;
            }
        }
        //echo $url;
        // die;

        if ($_SERVER['REMOTE_ADDR'] == '46.98.173.72') {
            var_dump($redirect_url.$url);die();
        }

        return $redirect_url.$url;
    }

    /**
     * HÀM TẠO ĐƯỜNG LINK THANH TOÁN QUA NGÂNLƯỢNG.VN VỚI THAM SỐ CƠ BẢN
     *
     * @param string $return_url: Đường link dùng để cập nhật tình trạng hoá đơn tại website của bạn khi người mua thanh toán thành công tại NgânLượng.vn
     * @param string $receiver: Địa chỉ Email chính của tài khoản NgânLượng.vn của người bán dùng nhận tiền bán hàng
     * @param string $transaction_info: Tham số bổ sung, bạn có thể dùng để lưu các tham số tuỳ ý để cập nhật thông tin khi NgânLượng.vn trả kết quả về
     * @param string $order_code: Mã hoá đơn/Tên sản phẩm
     * @param int $price: Tổng tiền phải thanh toán
     * @return string
     */
    public function buildCheckoutUrl($return_url, $receiver, $transaction_info, $order_code, $price)
    {

        // Bước 1. Mảng các tham số chuyển tới nganluong.vn
        $arr_param = array(
            'merchant_site_code'=>	strval($this->merchant_site_code),
            'return_url'		=>	strtolower(urlencode($return_url)),
            'receiver'			=>	strval($receiver),
            'transaction_info'	=>	strval($transaction_info),
            'order_code'		=>	strval($order_code),
            'price'				=>	strval($price)
        );
        $secure_code ='';
        $secure_code = implode(' ', $arr_param) . ' ' . $this->secure_pass;
        $arr_param['secure_code'] = md5($secure_code);

        /* Bước 2. Kiểm tra  biến $redirect_url xem có '?' không, nếu không có thì bổ sung vào*/
        $redirect_url = $this->nganluong_url;
        if (strpos($redirect_url, '?') === false)
        {
            $redirect_url .= '?';
        }
        else if (substr($redirect_url, strlen($redirect_url)-1, 1) != '?' && strpos($redirect_url, '&') === false)
        {
            // Nếu biến $redirect_url có '?' nhưng không kết thúc bằng '?' và có chứa dấu '&' thì bổ sung vào cuối
            $redirect_url .= '&';
        }

        /* Bước 3. tạo url*/
        $url = '';
        foreach ($arr_param as $key=>$value)
        {
            if ($key != 'return_url') $value = urlencode($value);

            if ($url == '')
                $url .= $key . '=' . $value;
            else
                $url .= '&' . $key . '=' . $value;
        }
        return $redirect_url.$url;
    }

    /**
     * HÀM KIỂM TRA TÍNH ĐÚNG ĐẮN CỦA ĐƯỜNG LINK KẾT QUẢ TRẢ VỀ TỪ NGÂNLƯỢNG.VN
     *
     * @param string $transaction_info: Thông tin về giao dịch, Giá trị do website gửi sang
     * @param string $order_code: Mã hoá đơn/tên sản phẩm
     * @param string $price: Tổng tiền đã thanh toán
     * @param string $payment_id: Mã giao dịch tại NgânLượng.vn
     * @param int $payment_type: Hình thức thanh toán: 1 - Thanh toán ngay (tiền đã chuyển vào tài khoản NgânLượng.vn của người bán); 2 - Thanh toán Tạm giữ (tiền người mua đã thanh toán nhưng NgânLượng.vn đang giữ hộ)
     * @param string $error_text: Giao dịch thanh toán có bị lỗi hay không. $error_text == "" là không có lỗi. Nếu có lỗi, mô tả lỗi được chứa trong $error_text
     * @param string $secure_code: Mã checksum (mã kiểm tra)
     * @return unknown
     */

    public function verifyPaymentUrl()
    {
        // Tạo mã xác thực từ chủ web
        $str = '';
        $str .= ' ' . strval($this->transaction_info);
        $str .= ' ' . strval($this->order_code);
        $str .= ' ' . strval($this->price);
        $str .= ' ' . strval($this->payment_id);
        $str .= ' ' . strval($this->payment_type);
        $str .= ' ' . strval($this->error_text);
        $str .= ' ' . strval($this->merchant_site_code);
        $str .= ' ' . strval($this->secure_pass);

        // Mã hóa các tham số
        $verify_secure_code = '';
        $verify_secure_code = md5($str);

        // Xác thực mã của chủ web với mã trả về từ nganluong.vn
        if ($verify_secure_code === $this->secure_code) return true;
        else return false;
    }
    function GetTransactionDetail($token){
        ###################### BEGIN #####################
        $params = array(
            'merchant_id'       => $this->merchant_site_code ,
            'merchant_password' => MD5($this->secure_pass),
            'version'           => Config::$_VERSION,
            'function'          => 'GetTransactionDetail',
            'token'             => $token
        );
        $api_url = Config::$_URL_SERVICE;
        $post_field = '';
        foreach ($params as $key => $value){
            if ($post_field != '') $post_field .= '&';
            $post_field .= $key."=".$value;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$api_url);
        curl_setopt($ch, CURLOPT_ENCODING , 'UTF-8');
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field);
        $result = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        if ($result != '' && $status==200){
            $nl_result  = simplexml_load_string($result);
            return $nl_result;
        }

        return false;
        ###################### END #####################

    }

    function UpdateOrder($transaction_info,$order_code,$payment_id,$payment_type,$secure_code)
    {
        // test lưu log kiểm tra  gọi cập nhật order:

        // Kiểm tra chuỗi bảo mật
        $secure_code_new = md5($transaction_info.' '.$order_code.' '.$payment_id.' '.$payment_type.' '.$this->secure_pass);
        if($secure_code_new != $secure_code)
        {
            return -1; // Sai mã bảo mật
        }
        else // Thanh toán thành công
        {
            // Trường hợp là thanh toán tạm giữ. Hãy đưa thông báo thành công và cập nhật hóa đơn phù hợp
            if($payment_type == 2)
            {
                $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/nganluong.txt',"a");
                    fwrite($f, '$payment_type == 2 '.$transaction_info.' '.$order_code.' '.$payment_id.'
                ');
                // Lập trình thông báo thành công và cập nhật hóa đơn
            }
            // Trường hợp thanh toán ngay. Hãy đưa thông báo thành công và cập nhật hóa đơn phù hợp
            elseif($payment_type == 1)
            {
                $f = fopen($_SERVER["DOCUMENT_ROOT"].'/protected/runtime/log/nganluong.txt',"a");
                fwrite($f, '$payment_type == 1 '.$transaction_info.' '.$order_code.' '.$payment_id.'
                ');
                // Lập trình thông báo thành công và cập nhật hóa đơn
            }
        }
    }


}