<?php
defined('IN_WEB') or die('Include Error!');
/**
* BluePay支付
*/

class ModelPaymentBluepay
{

    private   $producerId = 887;
    private   $salt = 'Qs2HtcqnMyIqf7Ey';

    protected $goodsTable;//商品表
    protected $summaryListTable;//订单汇总表
    protected $paymentTable;//玩家订单表

    protected $thbExtra = 100;//BluePay支付额外添加

    protected $allowCheckPriceType = array('cashcard');//当传递的价格和商品的价格不符时, 如果为casecard类型,则重新查找一般商品

    protected $operator = array(//运营商类别
        'googleplay' => 1,
        'bluepay' => 2,
        'ios' => 3,
        'bluecoins' => 4,
        'truemoney' => 5,
        '12call' => 6,
        'dtac' => 7,
        'line' => 8
    );

    public function __construct(){
        $this->goodsTable = otable::goods();
        $this->summaryListTable = otable::summarylist();
    }

	/**
	*	BluePay的支付验证
	*/
	public function verifyBluePay($param)
	{
        $price = oo::functions()->uint($param['price']);//价格
        $orderId = oo::functions()->escape($param['orderId']);//订单号
        $currency = oo::functions()->escape($param['currency']);//计费单位
        $operator = strtolower( oo::functions()->escape($param['operator']) );//运营商
        $interfacetype = strtolower( oo::functions()->escape($param['interfacetype']) );//计费类型

        oo::logs()->debug3(array('param' => $param), 'payment_bluepay.log');

        if( empty($price) || empty($orderId) || empty($currency) ){
            return false;
        }

        $now = time();

        //验证订单是否正确
        $sqlSummarylist = " SELECT sl_gid, sl_uid, sl_status FROM {$this->summaryListTable} WHERE sl_orderid = '{$orderId}' LIMIT 1 ";
        $ret = oo::commonOprDb('common')->getOne($sqlSummarylist, MYSQLI_ASSOC);
        if (empty($ret)) {
            oo::logs()->debug3(array('orderId' => $orderId, 'reason' => 'orderIdError', 'time' => $now),'payment_bluePayError.log');
            return false;
        }

        $uid = $ret['sl_uid'];
        //验证订单状态,是否已经支付过
        $status = intval($ret['sl_status']);
        if( $status == 2){
            oo::logs()->debug3(array('orderId' => $orderId, 'reason' => 'alreadyPayed', 'time' => $now),'payment_bluePayError.log');
            return false;
        }

        //验证商品信息是否正确
        $gid = $ret['sl_gid'];
        $sqlGoodsInfo = " SELECT gpriceThb FROM {$this->goodsTable} WHERE gid = {$gid} LIMIT 1 ";
        $retGoods = oo::commonOprDb('common')->getOne($sqlGoodsInfo, MYSQLI_ASSOC);
        if (empty($retGoods)) {
            oo::logs()->debug3(array('orderId' => $orderId, 'reason' => 'getGoodsErr', 'sqlGoodsInfo' => $sqlGoodsInfo, 'time' => $now),'payment_bluePayError.log');
            return false;
        }


        //验证价格是否匹配
        $gprice = intval($retGoods['gpriceThb']) * $this->thbExtra;
        if( $price != $gprice ){
            if( !in_array($interfacetype, $this->allowCheckPriceType) ){
                oo::logs()->debug3(array('orderId' => $orderId, 'reason' => 'priceError', 'price' => $price, 'gprice' => $gprice, 'time' => $now),'payment_bluePayError.log');
                return false;
            }else{
                $checkPriceAgain = $this->checkPriceAgain($price, $orderId, $operator, $uid);
                if( !$checkPriceAgain ){
                    oo::logs()->debug3(array('orderId' => $orderId, 'reason' => 'priceError', 'operator' => $operator, 'price' => $price, 'gprice' => $gprice, 'time' => $now),'payment_bluePayError.log');
                    return false;
                }
            }
        }

        //验证通过后,可以发奖了
        $retReward = oo::commonOprModel('payment')->pubDelivery($uid, $orderId);
        return $retReward;
    }

    /**
     * 当计费类型为充值卡,并且价格不匹配时,重新查找价格对应的商品, 找到后重新修改
     * 因为客户端下单时候,无法确认商品ID
     * @param int $orderId
     */
    protected function checkPriceAgain($price, $orderId = 0, $operator = 0, $uid = 0 ){
        if( $operator == 'test' ){
            $sql = " SELECT gid, gprice, gpriceThb FROM {$this->goodsTable} WHERE gchannel IN(4,5,6,7) ";
        }else{
            $gchannel = $this->operator[$operator];//支付商品渠道
            if( empty($gchannel) ){
                return false;
            }
            $gplatform = 1;
            //查询价格,和商品ID
            $sql = " SELECT gid, gprice, gpriceThb FROM {$this->goodsTable} WHERE gchannel = {$gchannel} AND gplatform = {$gplatform} AND gstatus = 1 ";
        }
        $goodsList = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
        if( empty($goodsList) ){
            return false;
        }

        $sl_gid = $sl_pusd = 0;//新的商品ID和价格(美元)
        $price = $price / $this->thbExtra;
        foreach ($goodsList as $info){
            if( $info['gpriceThb'] == $price ){
                $sl_gid = intval($info['gid']);
                $sl_pusd = $info['gprice'];
                break;
            }
        }
        if( $sl_gid == 0 ){
            return false;
        }

        //更新订单汇总表
        $sqlU = " UPDATE {$this->summaryListTable} SET sl_gid = {$sl_gid}, sl_pusd = '{$sl_pusd}' WHERE sl_orderid = {$orderId} LIMIT 1";
        oo::commonOprDb('common')->query($sqlU);

        //更新玩家订单表中的订单ID
        $paymentTable = otable::payment($uid);
        $sqlPayment = " UPDATE {$paymentTable} SET gid = {$sl_gid}, pusd = '{$sl_pusd}' WHERE uid = {$uid} AND order_id = {$orderId} LIMIT 1 ";
        oo::commonOprDb('common')->query($sqlPayment);

        return true;
    }

    /**
     * 玩家发送 充值卡
     * @param $uid
     * @param $phone
     * @param $operation
     * @param $amount
     */
    public function sendPhonecard($uid, $phone, $operation, $amount){
        if (empty($uid) || empty($phone) || empty($operation) || empty($amount)){
            return -1;
        }

        $transId = $uid.time();//交易ID

        //准备加密参数
        $phone = '66'.$phone;
        $param = array(
            'producer_id'   => $this->producerId,
            'pocket_id'     => 2,
            'amount'        => $amount,
            'msisdn'        => $phone,
            'trans_id'      => $transId,
            'telcoName'     => $operation,
            'description'   => $operation.'Buy'
        );
        $md5enctype = $this->md5encrypt($param);
        if ($md5enctype === false){
            return -2;
        }
        ksort($param);
        $param['encrypt'] = $md5enctype;
//        $url = 'http://award.BluePay.asia:9999/award/apply/';//测试地址
        $url = 'http://award.BluePay.asia/award/apply/';//泰国正式
        $rs = oo::functions()->curl($url, $param);
        return $rs;
    }

    /**
     * md5加密需要的参数
     * @param string $array
     */
    private function md5encrypt($array = ''){
        if (empty($array)){
            return false;
        }

        ksort($array);
        $s = '';
        foreach ($array as $k => $v){
            $s .= $k.'='.$v.'&';
        }
        $s = rtrim($s, '&').$this->salt;

        return md5($s);
    }

}