<?php
/**
 * 作者: theworld
 * 时间: 2023-03-10
 * 主机相关信息       
 */

class hostIdcsmart {
	
	/**
	 * 作者: theworld
	 * 时间: 2023-03-10
	 * 添加订单
	 * @params  string   $productid  产品ID
	 * @params  string   $hostname  主机名
	 * @params  string   $billingcycle  周期
	 * @params  string   $password  密码
	 * @params  string   $amount  金额
	 * @params  array   $configoptions  配置项
	 * @return array
	 */
	public function addorder($params){	
		$adminUsername="";	
		$idcsmart_reseller_hosts = _pdoSelect("idcsmart_reseller_hosts","`hosting_id`,`downstream_info`,`downstream_host_id`","`downstream_host_id` ='{$params['downstream_id']}'");
		$hosting = [];
		if(!empty($idcsmart_reseller_hosts)){
			$idcsmart_reseller_hosts['downstream_info'] = json_decode($idcsmart_reseller_hosts['downstream_info'], true);
			if($idcsmart_reseller_hosts['downstream_info']['url']==$params['downstream_url'] && $idcsmart_reseller_hosts['downstream_info']['token']==$params['downstream_token']){
				$hosting = _pdoSelect("tblhosting","`id`,`domainstatus`,`packageid`","`id` ='{$idcsmart_reseller_hosts['hosting_id']}' AND `userid`='{$params['account']['userid']}'");	
			}
		}

		//判断主机名是否已经存在
		//$hosting = _pdoSelect("tblhosting","`id`,`domainstatus`,`packageid`","`domain` ='{$params['hostname']}' AND `userid`='{$params['account']['userid']}'");	
		if(!empty($hosting) && $hosting['domainstatus']!="Cancelled"){	
			if($hosting['domainstatus']=="Pending"){
				$tblinvoiceitems = _pdoSelect("tblinvoiceitems","invoiceid","`userid`='{$params['account']['userid']}' AND `type`='Hosting' AND `relid`='{$hosting['id']}'");
				$tblinvoices = _pdoSelect("tblinvoices","`status`,`subtotal`","`id`='{$tblinvoiceitems['invoiceid']}'");				
				if($tblinvoices['status']=="Unpaid"){
					$applycredit = localAPI('ApplyCredit', array(
						'invoiceid' => $tblinvoiceitems['invoiceid'],
						'amount' => $tblinvoices['subtotal'],
					), $adminUsername);					
					if ($applycredit["result"] == "success"){
						$tblorders = _pdoSelect("tblorders","`id`,`status`","`invoiceid`='{$tblinvoiceitems['invoiceid']}'");
						//订单审核
						$responseAccept = localAPI('AcceptOrder', array(
							'orderid' => $tblorders['id'],
							'autosetup' => true,
							'sendemail' => false,
						), $adminUsername);
						if ($responseAccept["result"] == "success") {
							//开通服务
							$ModuleCreate = localAPI('ModuleCreate', array(
								'serviceid'		=> $hosting['id'],
							),$adminUsername);
							if ($ModuleCreate["result"] == "success"){
								$resultMsg['status']=200;
								$resultMsg['msg']="服务开通成功";
								$resultMsg['data']['hosting_id'] = $hosting['id'];
							}else{				
								$resultMsg['status']=400;
								$resultMsg['msg']="服务开通失败: ".$ModuleCreate["message"];
							}									
						} else {
							$resultMsg['status'] = 400;
							$resultMsg['msg'] = "订单审核失败，" . $responseAccept['message'];
						}
					}else{
						$resultMsg['status'] = 400;
						$resultMsg['msg'] = "余额支付失败，" . $applycredit['message'];
					}
				}else if($tblinvoices['status']=="Paid" || empty($tblinvoices)){
					//开通服务
					$ModuleCreate = localAPI('ModuleCreate', array(
						'serviceid'		=> $hosting['id'],
					),$adminUsername);
					if ($ModuleCreate["result"] == "success"){
						$resultMsg['status']=200;
						$resultMsg['msg']="服务开通成功";
						$resultMsg['data']['hosting_id'] = $hosting['id'];
					}else{				
						$resultMsg['status']=400;
						$resultMsg['msg']="服务开通失败: ".$ModuleCreate["message"];
					}				
				}else{
					$resultMsg['status'] = 400;
					$resultMsg['msg'] = '账单状态异常';
				}
				//return $resultMsg;
			}else if($hosting['domainstatus']=="Active"){
				$resultMsg['status']=200;
				$resultMsg['msg']="服务开通成功";
				$resultMsg['data']['hosting_id'] = $hosting['id'];
			}else{
				$resultMsg['status'] = 400;
				$resultMsg['msg'] = '主机状态异常';
			}
		}else{
			//获取支付方式
			$getPaymentMethods = localAPI('GetPaymentMethods',[], $adminUsername);	
			$pwd = $this->randStr();
			//添加订单
			$result = localAPI('AddOrder', array(
				'clientid' => $params['account']['userid'],
				'pid' => [$params['productid']],
				'domain' => [$params['hostname']],
				'billingcycle' => [$params['billingcycle']],
				'customfields' => [base64_encode(serialize($params['customfields']))],
				'configoptions' => [base64_encode(serialize($params['configoptions']))],
				'paymentmethod' => $getPaymentMethods['paymentmethods']['paymentmethod'][0]['module'],
				'rootpw' => [$pwd],
			), $adminUsername);
			if($result['invoiceid']>0) $tblinvoices = _pdoSelect("tblinvoices","`status`","`id`='{$result['invoiceid']}'");
			if ($result["result"] == "success" && !empty($result['serviceids'])) {
				$array=[
					'hosting_id'=>$result['serviceids'],
					'downstream_info'=>json_encode(['url'=>$params['downstream_url'],'token'=>$params['downstream_token']]),
					'downstream_host_id'=>$params['downstream_id'],
				];
				_pdoInsert("idcsmart_reseller_hosts",$array);
				if($tblinvoices['status']=="Paid" || empty($tblinvoices)){
					//订单审核
					$responseAccept = localAPI('AcceptOrder', array(
						'orderid' => $result['orderid'],
						'autosetup' => true,
						'sendemail' => false,
					), $adminUsername);
					if ($responseAccept["result"] == "success") {	
						//开通服务
						$ModuleCreate = localAPI('ModuleCreate', array(
							'serviceid'		=> $result['serviceids'],
						),$adminUsername);
						if ($ModuleCreate["result"] == "success"){
							$resultMsg['status']=200;
							$resultMsg['msg']="服务开通成功";
							$resultMsg['data']['hosting_id'] = $result['serviceids'];
						}else{				
							$hosting = _pdoSelect("tblhosting","`id`,`domainstatus`,`packageid`","`id` ='{$result['serviceids']}'");	
							if($hosting['domainstatus']=="Active"){
								$resultMsg['status']=200;
								$resultMsg['msg']="服务开通成功";
								$resultMsg['data']['hosting_id'] = $result['serviceids'];
							}else{
								$resultMsg['status']=400;
								$resultMsg['msg']="服务开通失败: ".$ModuleCreate["message"];
							}
							
						}
						/* $resultMsg['ststus'] = 200;
						$resultMsg['msg'] = '订单审核成功';
						$resultMsg['data']['hosting_id'] = $result['serviceids']; */
					} else {
						$resultMsg['status'] = 400;
						$resultMsg['msg'] = "订单审核失败，" . $responseAccept['message'];
					}
				}else{
					$resultMsg['status'] = 400;
					$resultMsg['msg'] = '订单创建成功，账单支付失败：余额不足';
				}
			} else {
				$resultMsg['status'] = 400;
				$resultMsg['msg'] = '创建订单失败，' . ($result['message'] ?? '产品创建失败');
			}
		}
		return $resultMsg;
	}	

	/*
	方法名:产品续费周期
	参数:$params array  hosting_id
	*/
	public function billingCycle($params){
		if(empty($params['hosting_id'])){
			$resultMsg['status']=400;
			$resultMsg['msg']="hosting_id不能为空";
			return $resultMsg;
		}
		$hosting = _pdoSelect("tblhosting","`billingcycle`,`domainstatus`,`dedicatedip`,`assignedips`,`nextduedate`,`username`,`password`","id ={$params['hosting_id']} AND `userid`='{$params['account']['userid']}'");
		if(empty($hosting)){
			$resultMsg['status'] = 400;
			$resultMsg['msg'] = 'hosting_id有误';
			return $resultMsg;
		}
		$hosting['billingcycle'] = str_replace( '-', '', strtolower( $hosting['billingcycle'] ) );
		if($hosting['billingcycle']=="free account" || $hosting['billingcycle']=="one time"){
			$resultMsg['status'] = 400;
			$resultMsg['msg'] = '当前产品不支持续费';
			return $resultMsg;
		}
		$billingPrice=$this->billingPrice($params);
		$billingcycle=array(
			'monthly'=>'一月',
			'quarterly'=>'三月',
			'semiannually'=>'半年',
			'annually'=>'一年',
			'biennially'=>'两年',
			'triennially'=>'三年',
		);
		$durationArr = array(
			'monthly' => 30*24*3600,
			'quarterly' => 90*24*3600,
			'semiannually' => 180*24*3600,
			'annually' => 365*24*3600,
			'biennially' => 2*365*24*3600,
			'triennially' => 3*365*24*3600,
		);
		foreach($billingPrice as $key=>$price){
			if($price>=0) $cycle[$key]=$billingcycle[$key];
		}
		$billingPrice=$this->billingConfigPrice($params);

		$arr = [];
		foreach($cycle as $key=>$value){
			$arr[] = ['duration' => $durationArr[$key], 'amount' => $billingPrice[$key], 'billingcycle' => $key];
		}
		$resultMsg = ['status' => 200, 'msg' => '获取成功', 'data' => ['cycle' => $arr]];
		return $resultMsg;
	}

	/*
	方法名:获取产品价格
	参数:$params array  hosting_id
	*/
	public function billingPrice($params){
		$sql="SELECT p.monthly,p.quarterly,p.semiannually,p.annually,p.biennially,p.triennially
		FROM tblhosting AS h
		LEFT JOIN tblpricing AS p ON (h.packageid=p.relid AND p.type='product')
		WHERE `h`.id='{$params['hosting_id']}' AND p.currency=1";
		$result=full_query($sql);
		$rows=mysql_fetch_assoc($result);
		return $rows;
	}
	/*
	方法名:获取产品和配置选项的价格
	参数:$params array  hosting_id
	*/
	public function billingConfigPrice($params){
		$cycle=$this->billingPrice($params);
		$sql="SELECT h.qty,opt.optiontype,p.monthly,p.quarterly,p.semiannually,p.annually,p.biennially,p.triennially FROM
		tblhostingconfigoptions AS h
		LEFT JOIN tblproductconfiglinks AS lik ON lik.gid=h.configid
		LEFT JOIN tblproductconfigoptions AS opt ON opt.id=h.configid
		LEFT JOIN tblproductconfigoptionssub AS sub ON sub.id=h.optionid
		LEFT JOIN tblpricing AS p  ON (p.relid=sub.id AND p.type='configoptions')
		WHERE h.relid={$params['hosting_id']} AND p.currency=1";
		$optResult=full_query($sql);
		while($value=mysql_fetch_assoc($optResult)){
			if($value['optiontype']==4){
				$cycle['monthly']+=$value['monthly']*$value['qty'];
				$cycle['quarterly']+=$value['quarterly']*$value['qty'];
				$cycle['semiannually']+=$value['semiannually']*$value['qty'];
				$cycle['annually']+=$value['annually']*$value['qty'];
				$cycle['biennially']+=$value['biennially']*$value['qty'];
				$cycle['triennially']+=$value['triennially']*$value['qty'];
			}else if($value['optiontype']==3 && $value['qty']=='1'){
				$cycle['monthly']+=$value['monthly'];
				$cycle['quarterly']+=$value['quarterly'];
				$cycle['semiannually']+=$value['semiannually'];
				$cycle['annually']+=$value['annually'];
				$cycle['biennially']+=$value['biennially'];
				$cycle['triennially']+=$value['triennially'];
			}else if($value['optiontype']==1 || $value['optiontype']==2){
				$cycle['monthly']+=$value['monthly'];
				$cycle['quarterly']+=$value['quarterly'];
				$cycle['semiannually']+=$value['semiannually'];
				$cycle['annually']+=$value['annually'];
				$cycle['biennially']+=$value['biennially'];
				$cycle['triennially']+=$value['triennially'];
			}
		}
		return $cycle;
	}
	/*
	方法名:生成账单
	参数:$params array  pid,hosting_id,userid
	*/
	public function renew($params){
		require_once( ROOTDIR . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'processinvoices.php' );
		require_once( ROOTDIR . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'invoicefunctions.php' );
		if(empty($params['hosting_id'])){
			$resultMsg['status']=400;
			$resultMsg['msg']="hosting_id不能为空";
			return $resultMsg;
		}
		$hosting = _pdoSelect("tblhosting","`billingcycle`,`domainstatus`,`dedicatedip`,`assignedips`,`nextduedate`,`username`,`password`","id ={$params['hosting_id']} AND `userid`='{$params['account']['userid']}'");
		if(empty($hosting)){
			$resultMsg['status'] = 400;
			$resultMsg['msg'] = 'hosting_id有误';
			return $resultMsg;
		}
		$hosting['billingcycle'] = str_replace( '-', '', strtolower( $hosting['billingcycle'] ) );
		if($hosting['billingcycle']=="free account" || $hosting['billingcycle']=="one time"){
			$resultMsg['status'] = 400;
			$resultMsg['msg'] = '当前产品不支持续费';
			return $resultMsg;
		}

		$this->billingRenewInvoicesDel($params);

		//$items['products'] =array($params['hosting_id']);
		//$invoiceid = createInvoices( $params['userid'], '', '', $items );//生成账单用sql语句写
		$sql="SELECT * FROM tblhosting WHERE `userid`={$params['account']['userid']} AND `id`={$params['hosting_id']}";
		$re=full_query($sql);
		$hostinginfo=mysql_fetch_assoc($re);
		if(strtolower($hostinginfo['billingcycle'])!=strtolower($params['billingcycle'])){
			$params['billingcycle'] = $hostinginfo['billingcycle'];
			$params['changebillingcycle'] = $params['billingcycle'];
			$res = $this->billingRenewChangeCycle($params);
			if(isset($res['error'])){
				$resultMsg['status']=400;
				$resultMsg['msg']=$res['error'];
				return $resultMsg;
			}
			$re=full_query($sql);
			$hostinginfo=mysql_fetch_assoc($re);
		}
		$hostingamount = $hostinginfo['amount'];//续费金额
		$hostingbillingcycle = $hostinginfo['billingcycle'];//续费周期
		$hostingnextduedate = $hostinginfo['nextduedate'];//到期时间
		$billingcycle=array(
			'Monthly'=>'monthly',
			'Quarterly'=>'quarterly',
			'Semi-Annually'=>'semiannually',
			'Annually'=>'annually',
			'Biennially'=>'biennially',
			'Triennially'=>'triennially',
		);
		$pricingbillingcycle = $billingcycle[$hostingbillingcycle];//续费周期转为tblpricing表周期
		$sql="SELECT `name` FROM tblproducts WHERE `id`={$hostinginfo['packageid']}";
		$re=full_query($sql);
		$productinfo=mysql_fetch_assoc($re);
		$productname = $productinfo['name'];
		$date = $this->nextduedate($pricingbillingcycle,$hostingnextduedate);//主机下次续费到期日期
	/*$arr = ['$pricingbillingcycle'=>$pricingbillingcycle,
		'$hostingnextduedate'=>$hostingnextduedate,
		'$date'=>$date
	];
		return $arr;exit;*/
		$invoiceitemsDescription = '续费账单: '.$productname.' - '.$hostinginfo['domain'].' ('.$hostingnextduedate .' to '.$date.')';
		$invoiceData = array(
			'userid' => $params['account']['userid'],
			'date'=>date("Y-m-d",time()),
			'duedate'=>$hostingnextduedate,
			'status' =>'Unpaid',
			'paymentmethod' =>'alipay',
			'subtotal' => $hostingamount,           		 //支付金额
			'total' => $hostingamount,
		);
		$invoiceid = insert_query('tblinvoices',$invoiceData);//新增续费账单
		$invoiceitemsData = array(
			'userid' => $params['account']['userid'],
			'invoiceid'=>$invoiceid,
			'type' =>'Hosting',
			'relid' =>$params['hosting_id'],
			'description' =>$invoiceitemsDescription,
			'amount'=> $hostingamount,
			'duedate'=>$hostingnextduedate,
			'paymentmethod' =>'alipay',
		);
		$invoiceitemsid = insert_query('tblinvoiceitems',$invoiceitemsData);//新增续费账单详情
		if(empty($invoiceid) || empty($invoiceitemsid)){
			$resultMsg['status']=400;
			$resultMsg['msg']="续费账单生成失败";
			$this->renewActivitylog( '生成续费账单失败 Hosting ID : ' . $params['hosting_id'] . ', Invoice ID : ' . $invoiceid );
			return $resultMsg;
		}
		$params['invoiceid']=$invoiceid;
		//$billingRenewCoupon=$this->billingRenewCoupon($params);//
		//if(!empty($billingRenewCoupon))full_query("UPDATE `mod_coupon` SET `status`='3',`invoiceid`=$invoiceid WHERE `id`=$billingRenewCoupon AND `status`='1'");
		$this->renewActivitylog( '生成续费账单成功 Hosting ID : ' . $params['hosting_id'] . ', Invoice ID : ' . $invoiceid );
		/*$result['status']="success";
		$result['msg']="续费账单生成成功";
		$result['invoice']=$invoiceid;
		$result['amount']=$hostingamount;*/

		$command = 'ApplyCredit';
		$postData = array(
		    'invoiceid' => $invoiceid,
		    'amount' => $hostingamount,
		);
		$adminUsername = '';

		$applycredit = localAPI($command, $postData, $adminUsername);
		if ($applycredit["result"] == "success"){
			full_query("UPDATE `tblhosting` SET `nextduedate`='{$date}' WHERE `id`={$params['hosting_id']}");
			$resultMsg['status']=200;
			$resultMsg['msg']="续费成功";
			$resultMsg['data']['nextduedate']=$date;
		}else{
			$resultMsg['status'] = 400;
			$resultMsg['msg'] = "余额支付失败，" . $applycredit['message'];
		}
		return $resultMsg;
	}
	/*
	方法名:改变续费周期
	参数:$params array  pid,hosting_id,userid,promoid,billingcycle,changebillingcycle,amount
	*/
	public function billingRenewChangeCycle($params){
		$this->billingRenewInvoicesDel($params);
		$params['billingcycle'] = str_replace( '-', '', strtolower( $params['billingcycle'] ) );
		$params['changebillingcycle'] = str_replace( '-', '', strtolower( $params['changebillingcycle'] ) );
		$billingRenewProm=$this->billingRenewProm($params);
		if($billingRenewProm['status']=="error"){
			$vars = $billingRenewProm;
			$vars['error'] = '您购买的是特殊优惠产品,要改变付款周期,请联系客服';
			$this->renewActivitylog( '改变续费周期失败 Hosting ID : ' . $params['hosting_id']." , {$params['billingcycle']} to {$params['changebillingcycle']}");
		}else if($billingRenewProm['status']=="success"){
			$this->renewActivitylog( '改变续费周期成功 Hosting ID : ' . $params['hosting_id']." , {$params['billingcycle']} to {$params['changebillingcycle']}");
			$vars = $billingRenewProm;
		}
		return $vars;
	}
	/*
	方法名:判断账单是否存在，存在删除
	参数:$params array  pid,hosting_id,userid
	*/
	public function billingRenewInvoicesDel($params){
		$sql="SELECT b.`invoiceid`,b.`type` FROM tblinvoices AS a
				LEFT JOIN tblinvoiceitems AS b ON b.`invoiceid`=a.`id`
				LEFT JOIN tblupgrades AS c ON c.`id`=b.`relid`
				WHERE (b.`relid`='{$params['hosting_id']}' OR c.`relid`='{$params['hosting_id']}') AND a.`userid`='{$params['account']['userid']}' AND `a`.status='Unpaid' AND (`b`.type='Hosting' OR `b`.type='Upgrade')";
		$tblinvoiceitems_hostingid =full_query($sql);
		while($re=mysql_fetch_assoc($tblinvoiceitems_hostingid)){
			//$re =mysql_fetch_assoc($tblinvoiceitems_hostingid);
			$invoiceid=intval($re['invoiceid']);
			if($invoiceid>0){
				full_query("UPDATE `tblinvoices` SET `status`='Cancelled' WHERE `id`=$invoiceid AND `status`='Unpaid'");
				//full_query("delete from tblinvoiceitems where `invoiceid`='$invoiceid'");
				// if($re['type']=="Upgrade"){
				// 	full_query("delete from tblupgrades where `relid`='{$params['hosting_id']}' AND `status`='Pending' AND `paid`='N'");
				// }
				full_query("UPDATE `mod_coupon` SET `status`='1',`invoiceid`='' WHERE `invoiceid`=$invoiceid AND `status`='3'");
				$this->renewActivitylog( '续费插件：取消账单 Invoice ID: '.$invoiceid);
			}
		}
	}
	/*
	方法名:现金券
	参数:$params array  pid,hosting_id,userid,invoiceid
	*/
	public function billingRenewCoupon($params){
		$sql="SELECT m.*,p.`start_fee`,p.`value`,p.`type`,p.`appliesto`,`p`.couponname
		FROM `mod_coupon` AS m
		LEFT JOIN `mod_coupon_prom` AS p ON m.`proid`=p.`id`
		WHERE m.`userid`='{$params['account']['userid']}' AND p.`codetype`='x' AND m.`status`='1'";
		$userCouponResult=full_query($sql);
		while($getUserCoupon=mysql_fetch_assoc($userCouponResult)){
			if($getUserCoupon['appliesto']=='0'){
				$UseCoupons=$getUserCoupon;
			}else{
				$appliestoArr=explode(',',trim($getUserCoupon['appliesto']));
				if(in_array($params['pid'],$appliestoArr)){
					$UseCoupons=$getUserCoupon;
				}
			}
		}
		if(empty($UseCoupons))return false;
		$tblinvoices=full_query("SELECT * FROM tblinvoices WHERE id={$params['invoiceid']}");
		$invoices=mysql_fetch_assoc($tblinvoices);
		if(!is_array($invoices)) return false;
		if($UseCoupons['type']=="Fixed Amount"){
			$amount=$invoices['total']-$UseCoupons['value'];
			$couponDesc=$UseCoupons['couponname']."现金券固定优惠";
		}else{
			$amount=$UseCoupons['value'];
			$couponDesc=$UseCoupons['couponname']."现金券固定金额";
		}
		$arr['invoiceid']=$params['invoiceid'];
		$arr['userid']=$params['account']['userid'];
		$arr['type']='Coupon';
		$arr['relid']=$params['hosting_id'];
		$arr['description']=$couponDesc;
		$arr['amount']="-".$UseCoupons['value'];
		$arr['duedate']=$invoices['duedate'];
		$arr['paymentmethod']=$invoices['paymentmethod'];
		insert_query("tblinvoiceitems",$arr);
		full_query("UPDATE `tblinvoices` SET `total`=$amount,`subtotal`=$amount WHERE `id`={$params['invoiceid']}");
		full_query("UPDATE `mod_coupon` SET `status`='3',`invoiceid`='' WHERE `invoiceid`={$params['invoiceid']}");
		return $UseCoupons['id'];
	}
	/*
	方法名:优惠码
	参数:$params array  pid,hosting_id,userid,promoid,billingcycle,changebillingcycle
	*/
	public function billingRenewProm($params){
		$tblpromotions=select_query("tblpromotions","*",array("id"=>$params['promoid']));
		$promotions = mysql_fetch_array($tblpromotions,MYSQL_ASSOC);
		if(is_array($promotions) && $promotions['recurring']==1 && $promotions['recurfor']==0){
			$appliesto=explode(",",$promotions['appliesto']);
			$packageid=false;
			foreach($appliesto as $ap){
				if($ap==$params['pid']) $packageid=true;
			}
			$promotions['cycles'] = str_replace( '-', '', strtolower( $promotions['cycles'] ) );
			if($packageid==true && (strpos($promotions['cycles'],$params['changebillingcycle'])!==false || $promotions['cycles']=="")){
				if($promotions['type']=="Percentage"){
					$_promotions=$promotions['value'];
					$type="percent";
				}else if($promotions['type']=="Fixed Amount"){
					$_promotions=$promotions['value'];
					$type="fixedAmount";
				}
			}
		}
		$billingConfigPrice=$this->billingConfigPrice(array("hosting_id"=>$params['hosting_id']));//产品原价
		$changeamount =$billingConfigPrice[$params['changebillingcycle']];
		$amount =$billingConfigPrice[$params['billingcycle']];
		if($type=="percent"){
			$amount =$amount-($amount*$_promotions)/100;
			$changeamount =$changeamount-($changeamount*$_promotions)/100;
		}elseif($type=="fixedAmount"){
			$amount =$amount-$_promotions;
			$changeamount =$changeamount-$_promotions;
		}
		if($params['amount']!=$amount){
			return array("amount"=>$params['amount'],"new_amount"=>$amount,"status"=>"error");
		}
		$changebillingcycle=$this->pricingHostingBillingCycle($params['changebillingcycle']);
		full_query("UPDATE `tblhosting` SET `amount`='$changeamount',`billingcycle`='$changebillingcycle' WHERE `id`={$params['hosting_id']}");
		return array("amount"=>$params['amount'],"new_amount"=>$amount,"status"=>"success");
	}
	/*
	方法名:tblpricing表对应tblhosting产品周期
	参数:$hosting_billingcycle str  tblpricing表周期
	*/
 	public function pricingHostingBillingCycle($hosting_billingcycle){
		$billingcycle=array(
			'monthly'=>'Monthly',
			'quarterly'=>'Quarterly',
			'semiannually'=>'Semi-Annually',
			'annually'=>'Annually',
			'biennially'=>'Biennially',
			'triennially'=>'Triennially',
		);
		return $billingcycle[$hosting_billingcycle];
	}
	/*
	方法名:主机下次续费到期日期
	参数:$billingcycle str tblpricing表周期, $duedate str  主机到期日期
	*/
	public function nextduedate($billingcycle,$duedate){
		if(!empty($duedate))
			$due=$duedate;
		else
			$due=date("Y-m-d",time());
		if($billingcycle=="monthly"){
			$date=date("Y-m-d",strtotime("$due +1 month"));
		}else if($billingcycle=="quarterly"){
			$date=date("Y-m-d",strtotime("$due +3 month"));
		}else if($billingcycle=="semiannually"){
			$date=date("Y-m-d",strtotime("$due +6 month"));
		}else if($billingcycle=="annually"){
			$date=date("Y-m-d",strtotime("$due +1 year"));
		}else if($billingcycle=="biennially"){
			$date=date("Y-m-d",strtotime("$due +2 year"));
		}else if($billingcycle=="triennially"){
			$date=date("Y-m-d",strtotime("$due +3 year"));
		}
		return $date;
	}
	/*
	方法名:日志
	参数:$billingcycle str tblpricing表周期, $duedate str  主机到期日期
	*/
	public function renewActivitylog($description){
		require_once( ROOTDIR . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'functions.php' );
		logActivity($description);
	}
	
	/**
	 * 作者: theworld
	 * 时间: 2023-03-10
	 * 升级
	 * @params  string   $email  邮箱
	 * @params  string   $password  密码
	 * @return array
	 */
	public function changePackage($params){
		$adminUsername = ''; 
		if(empty($params['hosting_id'])){
			$resultMsg['status']=400;
			$resultMsg['msg']="hosting_id不能为空";
		}
		$hosting = _pdoSelect("tblhosting","`packageid`,`domainstatus`,`dedicatedip`,`assignedips`,`nextduedate`,`username`,`password`","id ={$params['hosting_id']} AND `userid`='{$params['account']['userid']}'");
		if(empty($hosting)){
			$resultMsg['status'] = 400;
			$resultMsg['msg'] = 'hosting_id有误';
		}else{
			$product = _pdoSelect("tblproducts","id,configoptionsupgrade","id={$hosting['packageid']}");
			if(empty($product['configoptionsupgrade'])){
				$resultMsg['status'] = 400;
				$resultMsg['msg'] = '产品不支持升降级';
				return $resultMsg;
			}
			//获取支付方式
			$getPaymentMethods = localAPI('GetPaymentMethods',[], $adminUsername);	

			$result = localAPI('UpgradeProduct', array(
				'serviceid'		=> $params['hosting_id'],
				'paymentmethod' => $getPaymentMethods['paymentmethods']['paymentmethod'][0]['module'],
				'type' => 'configoptions',
				'configoptions' => $params['configoptions'],
			),$adminUsername);

			if ($result["result"] == "success"){
				if($result['invoiceid']>0) $tblinvoices = _pdoSelect("tblinvoices","`status`","`id`='{$result['invoiceid']}'");
				if ($result["result"] == "success") {
					if($tblinvoices['status']=="Paid" || empty($tblinvoices)){
						//订单审核
						$responseAccept = localAPI('AcceptOrder', array(
							'orderid' => $result['orderid'],
							'autosetup' => true,
							'sendemail' => false,
						), $adminUsername);
						if ($responseAccept["result"] == "success") {	
							//开通服务
							$ModuleChangePackage = localAPI('ModuleChangePackage', array(
								'serviceid'		=> $params['hosting_id'],
							),$adminUsername);
							if ($ModuleChangePackage["result"] == "success"){
								$resultMsg['status']=200;
								$resultMsg['msg']="升降级成功";
								$resultMsg['data']['hosting_id'] = $result['serviceids'];
							}else{				
								$resultMsg['status']=400;
								$resultMsg['msg']="升降级失败: ".$ModuleChangePackage["message"];
							}
						} else {
							$resultMsg['status'] = 400;
							$resultMsg['msg'] = "订单审核失败，" . $responseAccept['message'];
						}
					}else{
						$resultMsg['status'] = 400;
						$resultMsg['msg'] = '订单创建成功，账单支付失败：余额不足';
					}
				} else {
					$resultMsg['status'] = 400;
					$resultMsg['msg'] = '创建订单失败，' . ($result['message'] ?? '升降级失败');
				}
			}else{				
				$resultMsg['status']=400;
				$resultMsg['msg']="升降级失败: ".$result["message"];
			}
		}
		return $resultMsg;
	}	

	public function changePackageAmount($params){
		$adminUsername = ''; 
		if(empty($params['hosting_id'])){
			$resultMsg['status']=400;
			$resultMsg['msg']="hosting_id不能为空";
		}
		$hosting = _pdoSelect("tblhosting","`packageid`,`domainstatus`,`regdate`,`billingcycle`,`nextduedate`,`username`,`password`","id ={$params['hosting_id']} AND `userid`='{$params['account']['userid']}'");
		if(empty($hosting)){
			$resultMsg['status'] = 400;
			$resultMsg['msg'] = 'hosting_id有误';
		}else{
			$product = _pdoSelect("tblproducts","id,configoptionsupgrade","id={$hosting['packageid']}");
			if(empty($product['configoptionsupgrade'])){
				$resultMsg['status'] = 400;
				$resultMsg['msg'] = '产品不支持升降级';
				return $resultMsg;
			}

			$setupfeeArr = [
				'monthly' => 'msetupfee',
				'quarterly' => 'qsetupfee',
				'semiannually' => 'ssetupfee',
				'annually' => 'asetupfee',
				'biennially' => 'bsetupfee',
				'triennially' => 'tsetupfee',
			];
			$duetime = strtotime($hosting['nextduedate']);
			$surplustime =  $duetime-strtotime(date("Y-m-d"));
			if ($surplustime<0){
                $surplustime = 0;
            }

            $billingcycle=array(
				'Monthly'=>'monthly',
				'Quarterly'=>'quarterly',
				'Semi-Annually'=>'semiannually',
				'Annually'=>'annually',
				'Biennially'=>'biennially',
				'Triennially'=>'triennially',
			);
			if(isset($billingcycle[$hosting['billingcycle']])){
				$pricingbillingcycle = $billingcycle[$hosting['billingcycle']];//续费周期转为tblpricing表周期
			}
			

			$hostconfigoptions = _pdoQuery("SELECT a.configid,a.optionid,a.qty,b.optiontype FROM tblhostingconfigoptions a LEFT JOIN tblproductconfigoptions b on a.configid=b.id WHERE a.relid = {$params['hosting_id']}");
			$oldconfigoptions = [];
			foreach ($hostconfigoptions as $key => $value) {
				if(in_array($value['optiontype'], ['1', '2'])){
					$oldconfigoptions[$value['configid']] = $value['optionid'];
				}else{
					$oldconfigoptions[$value['configid']] = $value['qty'];
				}
			}


			$pricing = _pdoSelect("tblpricing","msetupfee,qsetupfee,ssetupfee,asetupfee,bsetupfee,tsetupfee,monthly,quarterly,semiannually,annually,biennially,triennially","`type`='product' AND `currency`='1' AND relid ={$hosting['packageid']}");
			$configurable = array();
			$options = _pdoQuery("SELECT co.*, cog.name AS group_name, cog.description AS group_description
										FROM tblproductconfigoptions AS co
										JOIN tblproductconfiggroups AS cog ON co.gid = cog.id
										JOIN tblproductconfiglinks AS col ON cog.id = col.gid
										WHERE col.pid = {$hosting['packageid']}  AND co.hidden=0");
			//配置项价格
			$options_id=implode(",",array_column($options,"id"));
			if($options_id){
				$configoptionssub = _pdoQuery("
				SELECT cos.* , p.msetupfee, p.qsetupfee, p.ssetupfee, p.asetupfee, p.bsetupfee, p.tsetupfee, p.monthly, p.quarterly, p.semiannually, p.annually, p.biennially, p.triennially
				FROM tblproductconfigoptionssub AS cos
				JOIN tblpricing AS p ON type = 'configoptions' AND currency = 1 AND relid = cos.id
				WHERE cos.configid IN ({$options_id})  AND cos.hidden = 0
				ORDER BY cos.sortorder ASC, cos.id ASC");
				foreach($configoptionssub as $v){
					$configoptionssub2[$v['configid']][]=$v;
				}
			}
			foreach($options as $v){
				$opt=array();
				foreach($configoptionssub2[$v['id']] as $c){
					$ex = explode('|', $c['optionname']);
					$c['firstname'] = $ex[0];
					$c['lastname'] = isset($ex[1]) ? $ex[1] : $ex[0];
					$opt[] = $c;
				}
				$ops=array();
				foreach ($opt as $o){
					if($v['optiontype']==1 || $v['optiontype']==2){
						$ops[$o['id']] = array(
							'id'	=> $o['id'],
							'optionname'	=> $o['optionname'],
							'firstname'		=> $o['firstname'],
							'lastname'		=> $o['lastname'],
							'currency'		=> 1,
							'msetupfee'		=> $o['msetupfee'],
							'qsetupfee'		=> $o['qsetupfee'],
							'ssetupfee'		=> $o['ssetupfee'],
							'asetupfee'		=> $o['asetupfee'],
							'bsetupfee'		=> $o['bsetupfee'],
							'tsetupfee'		=> $o['tsetupfee'],
							'monthly'		=> $o['monthly'],
							'quarterly'		=> $o['quarterly'],
							'semiannually'	=> $o['semiannually'],
							'annually'		=> $o['annually'],
							'biennially'	=> $o['biennially'],
							'triennially'	=> $o['triennially'],
						);
					}else{
						$ops[] = array(
							'id'	=> $o['id'],
							'optionname'	=> $o['optionname'],
							'firstname'		=> $o['firstname'],
							'lastname'		=> $o['lastname'],
							'currency'		=> 1,
							'msetupfee'		=> $o['msetupfee'],
							'qsetupfee'		=> $o['qsetupfee'],
							'ssetupfee'		=> $o['ssetupfee'],
							'asetupfee'		=> $o['asetupfee'],
							'bsetupfee'		=> $o['bsetupfee'],
							'tsetupfee'		=> $o['tsetupfee'],
							'monthly'		=> $o['monthly'],
							'quarterly'		=> $o['quarterly'],
							'semiannually'	=> $o['semiannually'],
							'annually'		=> $o['annually'],
							'biennially'	=> $o['biennially'],
							'triennially'	=> $o['triennially'],
						);
					}
					
				}
				$key = explode('|', $v['optionname']);
				//$key = $key[0];
				$configurable[$v['id']] = array(
					'optionname'	=> $v['optionname'],
					'firstname'		=> $key[0],
					'lastname'		=> isset($key[1]) ? $key[1] : $key[0],
					'optiontype'	=> $v['optiontype'],
					'qtyminimum'	=> $v['qtyminimum'],
					'qtymaximum'	=> $v['qtymaximum'],
					'options'		=> $ops
				);
			}
			
			$price = $price_difference = $renew_price_difference = 0;
			$description = [];
			foreach ($params['configoptions'] as $key => $value) {
				$oldPrice = $newPrice = 0;
				if($value!=$oldconfigoptions[$key]){
					if($configurable[$key]['optiontype']==4){
						$description[] = sprintf($configurable[$key]['lastname'].": %d => %d", $oldconfigoptions[$key] ?: 0, $value ?: 0);
						if($hosting['billingcycle']=='One Time'){
							$oldPrice += ($configurable[$key]['options'][0]['monthly']*$oldconfigoptions[$key]);
							$newPrice += ($configurable[$key]['options'][0]['monthly']*$value);
						}else if($hosting['billingcycle']=='Free Account'){
							
						}else{
							$oldPrice += ($configurable[$key]['options'][0][$pricingbillingcycle]*$oldconfigoptions[$key]);
							$newPrice += ($configurable[$key]['options'][0][$pricingbillingcycle]*$value);
						}
						
					}else if($configurable[$key]['optiontype']==3){
						$description[] = sprintf($configurable[$key]['lastname'].": %s => %s", $oldconfigoptions[$key]==1 ? '是' : '否', $value==1 ? '是' : '否');
						if($hosting['billingcycle']=='One Time'){
							if($oldconfigoptions[$key]==1){
								$oldPrice += ($configurable[$key]['options'][0]['monthly']);
							}
							if($value==1){
								$newPrice += ($configurable[$key]['options'][0]['monthly']);
							}
						}else if($hosting['billingcycle']=='Free Account'){
							
						}else{
							if($oldconfigoptions[$key]==1){
								$oldPrice += ($configurable[$key]['options'][0][$pricingbillingcycle]);
							}
							if($value==1){
								$newPrice += ($configurable[$key]['options'][0][$pricingbillingcycle]);
							}
						}
					}else{
						if(isset($configurable[$key]['options'][$oldconfigoptions[$key]]) || isset($configurable[$key]['options'][$value])){
							$description[] = sprintf($configurable[$key]['lastname'].": %s => %s", $configurable[$key]['options'][$oldconfigoptions[$key]]['lastname']?:'无', $configurable[$key]['options'][$value]['lastname']?:'无');
							if($hosting['billingcycle']=='One Time'){
								if(isset($configurable[$key]['options'][$oldconfigoptions[$key]])){
									$oldPrice += ($configurable[$key]['options'][$oldconfigoptions[$key]]['monthly']);
								}
								if(isset($configurable[$key]['options'][$value])){
									$newPrice += ($configurable[$key]['options'][$value]['monthly']);
								}
							}else if($hosting['billingcycle']=='Free Account'){
								
							}else{
								if(isset($configurable[$key]['options'][$oldconfigoptions[$key]])){
									$oldPrice += ($configurable[$key]['options'][$oldconfigoptions[$key]][$pricingbillingcycle]);
								}
								if(isset($configurable[$key]['options'][$value])){
									$newPrice += ($configurable[$key]['options'][$value][$pricingbillingcycle]);
								}
							}
						}
					}
				}
				if(isset($billingcycle[$hosting['billingcycle']])){
					$price += round(($newPrice-$oldPrice)*$surplustime/$this->cycleToTime($pricingbillingcycle, strtotime($hosting['nextduedate'])), 2);
				}else{
					$price += bcsub($newPrice, $oldPrice, 2);
				}
				$price_difference += bcsub($newPrice, $oldPrice, 2);
				$renew_price_difference += bcsub($newPrice, $oldPrice, 2);
			}
			
			
			
			$description = implode("\r\n", $description);
			$resultMsg = ['status' => 200, 'msg' => 'success', 'data' => ['price' => $price, 'price_difference' => $price_difference, 'renew_price_difference' => $renew_price_difference, 'description' => $description]];

		}
		return $resultMsg;
	}

	/*
     * 周期转时间戳
     * @param $billingcycle:周期
     * @return $cycletime:时间戳
     */
    protected function cycleToTime($billingcycle,$end=0)
    {
        switch ($billingcycle){
            case 'monthly':
                $cycletime = $end - strtotime('-1 month', $end);
                break;
            case 'quarterly':
                $cycletime = $end - strtotime('-3 month', $end);
                break;
            case 'semiannually':
                $cycletime = $end - strtotime('-6 month', $end);
                break;
            case 'annually':
                $cycletime = $end - strtotime('-1 year', $end);
                break;
            case 'biennially':
                $cycletime = $end - strtotime('-2 year', $end);
                break;
            case 'triennially':
                $cycletime = $end - strtotime('-3 year', $end);
                break;
            default:
                $cycletime = 0;
                break;
        }
        return $cycletime;
    }

	/**
	 * 作者: theworld
	 * 时间: 2023-03-10
	 * 主机信息
	 * @params  string   $hosting_id  主机ID
	 * @return array
	 */
	public function detail($params){
		if(empty($params['hosting_id'])){
			$resultMsg['status']=400;
			$resultMsg['msg']="hosting_id不能为空";
		}
		$hosting = _pdoSelect("tblhosting","`id`,`domain`,`domainstatus`,`dedicatedip`,`assignedips`,`regdate`,`nextduedate`,`username`,`password`,`firstpaymentamount`,`amount`,`billingcycle`","id ='{$params['hosting_id']}' AND `userid`='{$params['account']['userid']}'");
		if(empty($hosting)){
			$resultMsg['status'] = 400;
			$resultMsg['msg'] = 'hosting_id有误';
		}else{
			$billingcycleArr = [
				'One Time' => 'onetime',
				'Free Account' => 'free',
				'Monthly' => 'recurring_prepayment',
				'Quarterly' => 'recurring_prepayment',
				'Semiannually' => 'recurring_prepayment',
				'Annually' => 'recurring_prepayment',
				'Biennially' => 'recurring_prepayment',
				'Triennially' => 'recurring_prepayment',
			];
			$billingcycleNameArr = [
				'One Time' => '一次性',
				'Free Account' => '免费',
				'Monthly' => '月付',
				'Quarterly' => '季付',
				'Semiannually' => '半年付',
				'Annually' => '年付',
				'Biennially' => '两年付',
				'Triennially' => '三年付',
			];
			$billingcycleTimeArr = [
				'One Time' => 0,
				'Free Account' => 0,
				'Monthly' => 30*24*3600,
				'Quarterly' => 90*24*3600,
				'Semiannually' => 180*24*3600,
				'Annually' => 365*24*3600,
				'Biennially' => 2*365*24*3600,
				'Triennially' => 3*365*24*3600,
			];
			$statusArr = [
		    	'Pending' => 'Pending',
		    	'Active' => 'Active',
		    	'Suspended' => 'Suspended',
		    	'Terminated' => 'Deleted',
		    	'Cancelled' => 'Cancelled',
		    	'Fraud' => 'Failed',
		    	'Completed' => 'Failed',
		    ];
			$data=array(
				'status' => $statusArr[$hosting['domainstatus']],
				'dedicatedip'   => $hosting['dedicatedip'],
				'assignedips'   => $hosting['assignedips'],
				'nextduedate'=> $hosting['nextduedate'],
				'hostname'   => $hosting['domain'],
				'username'   => $hosting['username'],
				'password'   => decrypt($hosting['password']),
				'active_time' => strtotime($hosting['regdate']),
                'billing_cycle'=>$billingcycleArr[$hosting['billingcycle']] ?? 'recurring_prepayment',
                'billing_cycle_name'=>$billingcycleNameArr[$hosting['billingcycle']] ?? $hosting['billingcycle'],
                'billing_cycle_time'=>$billingcycleTimeArr[$hosting['billingcycle']] ?? 0,
                'due_time'=>strtotime($hosting['nextduedate'])>0 ? strtotime($hosting['nextduedate']) : 0,
                'first_payment_amount'=>$hosting['firstpaymentamount'],
                'id'=>$hosting['id'],
                'name'   => $hosting['domain'],
                'renew_amount'=>$hosting['amount'],
			);
			$resultMsg['status']=200;
			$resultMsg['msg']="success";
			$resultMsg['data']=$data;
		}
		return $resultMsg;
	}

	private function randStr(){
	    $strtolower='abcdefghijklmnopqrstuvwxyz';
		$strtoupper='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$number='0123456789';
		$password = '';  

		for ( $i = 0; $i < 4; $i++ ) {   
			$password .= $strtolower[ mt_rand(0, strlen($strtolower) - 1) ];  
		} 
		for ( $i = 0; $i < 4; $i++ ) {   
			$password .= $strtoupper[ mt_rand(0, strlen($strtoupper) - 1) ];  
		} 
		for ( $i = 0; $i < 4; $i++ ) {   
			$password .= $number[ mt_rand(0, strlen($number) - 1) ];  
		} 	
		return $password;  
	}
}
