<?php
require 'config.php';
require "Des.php";
///////////////////////////////////////////////
//下面代码基本不需要修改
if (empty($_POST)) $_POST = $_GET;  //如果为GET方式访问
if(version_compare(PHP_VERSION,'5.4.0','<')){
	outputError('PHP版本要求大于5.4.0');
}
if(!isset($_POST['appid'])){
	outputError('参数非法');
}
//验证商户号
if($_POST['appid']!=$appid){
	outputError('商户编号不正确');
}
if (!function_exists('openssl_encrypt')){
	outputError('请开启php.ini的openssl扩展');
}
//解密接口参数
$des = new Des();
$parameter=$_POST['parameter'];
$decode=$des->decrypt($parameter,$deskey);
if(empty($decode)){
	outputError('算法密钥不正确');
}
parse_str($decode, $data);
//验证商户密钥
if($appkey!=$data['appkey']){
	outputError('商户密钥不正确');
}

//开始充值
chongzhi($data);
function chongzhi($data){
	//全局变量，函数内调用需要加global声明
	global $dbconfig;
	global $libaoconfig;
	global $quconfig;
	try {
		$database = $data['database'];//数据库名
		$account = $data['account'];//账号
		$money = intval($data['money']);//充值金额
		if (strpos($account,"-" ) !== false) {
    		//拆分账号
    		$list = explode("-",$account);
    		$quid =  $list[0];//分区ID
    		$username = $list[1];//玩家账号
		}else{
		    if(!isset($data['quid'])){
		        outputError('未配置分区ID');
		    }
		    $quid = intval($data['quid']);
		    $username = $account;
		}
		//根据分区ID获取数据库
		foreach ($quconfig as $key=>$value) {
			if($key==$quid){
				$database = $value;
			}
		}
		$conn =mysqli_connect($dbconfig['db_host'],$dbconfig['db_user'],$dbconfig['db_pass'],$database,$dbconfig['port']) or die('数据库连接错误!');
		$conn->query('set names utf8');
		//如果有提交礼包ID，则直接使用（礼包ID放在param参数中）
		if(isset($data['param'])&& !empty($data['param'])){
			$rid = intval($data['param']);
			//printLog("传递过来的param参数值：".$rid);
		}else{
			//默认获取数组对象的第一个key键值
			$rid = key($libaoconfig);
			//根据充值金额算出购买的哪个礼包
			foreach ($libaoconfig as $key=>$value) {
				if($value[0]==$money){
					$rid = $key;
				}
			}
			//printLog("根据价格获取的礼包id：".$rid);
		}
		$oid = time();
		//1.获取玩家账号ID
		$playerid = $conn->query("SELECT * FROM players WHERE account='$username'")->fetch_assoc()['dbid'];
    	if(!empty($playerid)){
    		//2.写入充值语句
    		$sql = "insert into pay(dbid,playerid,serverid,goodsid) values ('$oid','$playerid','$quid','$rid')";
    		//printLog("充值SQL语句：".$sql);
    		if ($conn->query($sql)){
    			$msg = sprintf("账号[%s]成功充值金额%s元",$username,$money);
    			outputSuccess($msg);
    		}else{
    			outputError('充值失败');
    		}
    	}else{
    	    outputError('账号不存在，当前查询账号：'.$username);
    	}
	} catch (\Exception $e) {
		outputError('充值异常，Error：'.$e->getMessage());
	}
}

function outputError($msg){
	$arr=array('code'=>0,'msg'=>$msg);
	echo json_encode($arr, JSON_UNESCAPED_UNICODE);
	exit;
}

function outputSuccess($msg){
	$arr=array('code'=>1,'msg'=>$msg);
	echo json_encode($arr, JSON_UNESCAPED_UNICODE);
	exit;
}

/** 
 * 打印日志
 * $msg 日志内容
 */
function printLog($msg) {
	if (!is_dir('log')){
		mkdir('log',0777,true);
	}
	$path="log/".date('Y-m-d').".log";
	file_put_contents($path, "【" . date('Y-m-d H:i:s') . "】" . $msg . "\r\n\r\n", FILE_APPEND);
}