<?php   
namespace backend\modules\user\controllers;

use backend\models\forms\PayForm;
use Yii;
use yii\web\BadRequestHttpException;

class PayController extends BaseController
{
    /**
     * @return \yii\web\Response
     * @throws \Exception 
     */
    public function actionOutpay()
    {
        $model = new PayForm();
        if (Yii::$app->getRequest()->getIsPost()) {
            $data = Yii::$app->getRequest()->post();
            $payMethod = isset($data['payMethod']) ? trim($data['payMethod']) : '';
            $data['payType'] = $model->getPayTypeByMethod($payMethod);
            if ($data['payType'] == 1) {
                $data['bankCode'] = isset($data['renrenBankCode']) ? trim($data['renrenBankCode']) : '';
            }
            if ($data['payType'] == 3) {
                $data['bankCode'] = isset($data['sandBankCode']) ? trim($data['sandBankCode']) : '';
            }
			if ($data['payType'] == 8) {
                $data['bankCode'] = isset($data['kexingBankCode']) ? trim($data['kexingBankCode']) : '';
            }

            $model->setAttributes($data);
            if ($model->outPay()) {
                $result = $model->getOutPayResult();
			    
				
				
				
                if ($result['type'] == 'html') {
                    if ($data['payType'] == 3) {
                        return $this->sandPayHtmlHandler($result['html']);
                    } elseif($data['payType'] == 7) {
						for ($i = 0; $i <= 31; ++$i) { 
							$result['html'] = str_replace(chr($i), "", $result['html']); 
						}
						$result['html'] = str_replace(chr(127), "", $result['html']);
						if (0 === strpos(bin2hex($result['html']), 'efbbbf')) {
							$result['html'] = substr($result['html'], 3);
						}
						$tmp = json_decode($result['html'], true);
						$arr = parse_url($tmp['qr_src']);
						$queryParts = explode('&', $arr['query']); 
						$params = array(); 
						foreach ($queryParts as $param) 
						{ 
							$item = explode('=', $param); 
							$params[$item[0]] = $item[1]; 
						}
						
						$orderAmount = $params['amount'];
						//return $this->redirect($tmp['qr_src']);
						$qr_img = "https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=bitcoin:{$tmp['payee_address']}?amount={$orderAmount}";
						$data['qr_img'] = $qr_img;
						$data['amount'] = $orderAmount;
						$data['payee_address'] = $tmp['payee_address'];
						return $this->render('ctypepay',['data' => $data, ]);
					}
                    return $result['html'];
                } else {
                    throw new BadRequestHttpException('支付异常');
                }
            } else {
                throw new BadRequestHttpException(json_encode($model->getErrors(), 320));
            }
        }
        throw new BadRequestHttpException('Bad Request');
    }

    public function actionSucceed()
    {
        return $this->render('succeed');
    }

    public function actionFailed()
    {
        return $this->render('failed');
    }

    public function sandPayHtmlHandler($result)
    {
        $jqueryJs = STATIC_URL.'/ui/js/sand/jquery-1.7.2.min.js';
        $paymentJs = STATIC_URL.'/ui/js/sand/paymentjs.js';
        $html = <<<eot
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="renderer" content="webkit" />
    <script type="text/javascript" src="{$jqueryJs}"></script>
    <script type="text/javascript" src="{$paymentJs}"></script>
    <script>
    function wap_pay() {
        var responseText = $("#credential").text();
        paymentjs.createPayment(responseText, function(result, err) {
        });
    }
</script>
</head>
<body>
<div style="display: none" >
    <p id="credential">{$result}</p>
</div>
<script>
    window.onload=function(){
         wap_pay();
        //window.location.href = "http://www.jb51.net";
    };
</script>
</body>
</html>
eot;

        return $html;
    }

}