<?php
use WHMCS\Database\Capsule;

if (!defined("WHMCS")) {
    exit("This file cannot be accessed directly");
}

// 保存hostID到自定义字段
function zjmfcloud_SetHostID($params, $hostid = 0){
	if(empty($params['packageid']) || empty($params['serviceid']) || empty($hostid)){
		return false;
	}
	$id = Capsule::table('tblcustomfields')
					->where('type', '=', 'product')
					->where('relid', '=', $params['packageid'])
					->where('fieldname', '=', 'hostid')
					->value('id');
	if(empty($id)){
		// 自动创建
		$insert = [
			'type'=>'product',
			'relid'=>$params['packageid'],
			'fieldname'=>'hostid',
			'fieldtype'=>'text',
			'adminonly'=>'on'
		];
		$id = Capsule::table('tblcustomfields')->insertGetId($insert);
	}
	if(!empty($id)){
		$value = Capsule::table('tblcustomfieldsvalues')
				->where('fieldid', $id)
				->where('relid', $params['serviceid'])
				->first();
		if(empty($value)){
			$insert = [
				'fieldid'=>$id,
				'relid'=>$params['serviceid'],
				'value'=>$hostid,
				'created_at'=>date('Y-m-d H:i:s')
			];
			$res = Capsule::table('tblcustomfieldsvalues')->insertGetId($insert);
		}else{
			$res = Capsule::table('tblcustomfieldsvalues')->where('id', $value->id)->update(['value'=>$hostid]);
		}
	}else{
		$res = false;
	}
	return $res;
}

// 保存hostID到自定义字段
function zjmfcloud_SetExtraOs($params, $extra_os = ''){
	$res = false;
	if(empty($params['packageid']) || empty($params['serviceid'])){
		return $res;
	}
    $id = Capsule::table('tblcustomfields')
			->where('type', '=', 'product')
			->where('relid', '=', $params['packageid'])
			->where('fieldname', '=', 'extra_os')
			->value('id');
	if(empty($id)){
		// 自动创建
		$insert = [
			'type'=>'product',
			'relid'=>$params['packageid'],
			'fieldname'=>'extra_os',
			'fieldtype'=>'text',
			'adminonly'=>'on'
		];
		$id = Capsule::table('tblcustomfields')->insertGetId($insert);
	}
	if(!empty($id)){
		$value = Capsule::table('tblcustomfieldsvalues')
				->where('fieldid', $id)
				->where('relid', $params['serviceid'])
				->first();
		if(empty($value)){
			$insert = [
				'fieldid'=>$id,
				'relid'=>$params['serviceid'],
				'value'=>$extra_os,
				'created_at'=>date('Y-m-d H:i:s')
			];
			$res = Capsule::table('tblcustomfieldsvalues')->insertGetId($insert);
		}else{
			$res = Capsule::table('tblcustomfieldsvalues')->where('id', $value->id)->update(['value'=>$extra_os]);
		}
	}
	return $res;
}

// 保存hostID到自定义字段
function zjmfcloud_SetRemotePort($params, $port = 0){
	if(empty($params['packageid']) || empty($params['serviceid']) || empty($port)){
		return false;
	}
	$id = Capsule::table('tblcustomfields')
					->where('type', '=', 'product')
					->where('relid', '=', $params['packageid'])
					->where('fieldname', '=', 'remote_port')
					->value('id');
	if(empty($id)){
		// 自动创建
		$insert = [
			'type'=>'product',
			'relid'=>$params['packageid'],
			'fieldname'=>'remote_port',
			'fieldtype'=>'text',
			'adminonly'=>'on'
		];
		$id = Capsule::table('tblcustomfields')->insertGetId($insert);
	}
	if(!empty($id)){
		$value = Capsule::table('tblcustomfieldsvalues')
				->where('fieldid', $id)
				->where('relid', $params['serviceid'])
				->first();
		if(empty($value)){
			$insert = [
				'fieldid'=>$id,
				'relid'=>$params['serviceid'],
				'value'=>$port,
				'created_at'=>date('Y-m-d H:i:s')
			];
			$res = Capsule::table('tblcustomfieldsvalues')->insertGetId($insert);
		}else{
			$res = Capsule::table('tblcustomfieldsvalues')->where('id', $value->id)->update(['value'=>$port]);
		}
	}else{
		$res = false;
	}
	return $res;
}

//加载语言文件
function zjmfcloud_lang(){
	global $_LANG,$CONFIG;	
	$langDir=ZJMFCLOUD_FILE. 'lang/';
	$langFile = glob ($langDir. '*.php');	
	if(strpos($_SERVER['REQUEST_URI'],"clientarea.php")!==false || strpos($_SERVER['REQUEST_URI'],"cart.php")!==false){
		$uid=$_SESSION['uid'];
		if($uid>0){
			$tblclients = Capsule::table('tblclients')
					->where('id', '=', $uid)
					->get(['language']);
			$language =$tblclients[0]->language;	
		}else{	
			$language =(isset($_SESSION['Language']))? $_SESSION['Language']:$CONFIG['Language'];
		}
	}else{
		$adminid=$_SESSION['adminid'];
		$tbladmins = Capsule::table('tbladmins')
    			->where('id', '=', $adminid)
    			->get(['language']);
		$language =$tbladmins[0]->language;	
	}	
	$language = strtolower( $language ) . '.php';
	if ( ! in_array( $langDir.$language, $langFile ) ) {
		$language = 'chinese.php';
	}
	require_once( $langDir . $language );
}
// 组装url
function zjmfcloud_GetUrl($params){
	$accesshash=zjmfcloud_AccessHash($params['serveraccesshash']);
	$url = $params['serverhttpprefix'].'://'.($params['serverhostname'] ?: $params['serverip']);
	if(!empty($params['serverport'])){
		$url .= ':'.$params['serverport'];
	}
	if(!empty($accesshash['dir'])){
		$url = $url . $accesshash['dir'];
	}
	return $url;
}
//处理hash数据
function zjmfcloud_AccessHash($serveraccesshash)
{
	if(empty($serveraccesshash)){
		return [
			'dir'=>'',
	 		'user_prefix'=>'',
	 		'username'=>'',
	 		'account_type'=>'admin',
	 		'format_data_disk'=>false, 
		];
	}
	$xmlstring = "<xml>".htmlspecialchars_decode($serveraccesshash)."</xml>";
	$array = json_decode(json_encode((array)simplexml_load_string($xmlstring, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
 	
 	return [
 		'dir'=>$array['zjmfdir'] ? "/".$array['zjmfdir'] : '', //二级目录
 		'user_prefix'=>$array['user_prefix'] ?: '',   //财务标识
 		'username'=>$array['username'] ?: '',
 		'account_type'=>$array['account_type'] == 'agent' ? 'agent' : 'admin',
 		'format_data_disk'=>$array['format_data_disk'] == 'true' ? true : false, 
 	];
    // $dir = $array['zjmfdir'] ? "/".$array['zjmfdir'] : '';
    // return $dir;       
}
// 随机字符串
function zjmfcloud_RandStr($length = 8){
    $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $len = strlen($str)-1;
    $randstr = '';
    for($i=0; $i<$len; $i++){
        $num = mt_rand(0, $len);
        $randstr .= $str[$num];
    }
    return substr($randstr, 0, $length);
}
//对象转数组
function zjmfcloud_ObjectToArray($obj){
	$obj = (array)$obj;
	foreach ($obj as $k => $v){
		if (gettype($v) == 'resource'){
			return;
		}
		if (gettype($v) == 'object' || gettype($v) == 'array'){
			$obj[$k] = (array)zjmfcloud_ObjectToArray($v);
		}
	}
	return $obj;
}

//判断是否是json
function zjmfcloud_IsNotJson($str){ 
	return is_null(json_decode($str));
}

function zjmfcloud_FormatSystemDiskSize($system_disk_size){
	$res = null;
	if(!empty($system_disk_size)){
        if(is_numeric($system_disk_size) && $system_disk_size > 0){
            $res = $system_disk_size;
        }else if(strpos($system_disk_size, 'win:') !== false || strpos($system_disk_size, 'lin:') !== false){
            if(strpos($system_disk_size, ',') !== false){
                $system_disk_size_arr = explode(',', $system_disk_size);
                foreach($system_disk_size_arr as $v){
                    if(strpos($v, 'win:') !== false){
                    	$win_size = (int)str_replace('win:', '', $v);
                    }else if(strpos($v, 'lin:') !== false){
                    	$lin_size = (int)str_replace('lin:', '', $v);
                    }
                }
                $res = [$win_size, $lin_size];
            }else{
                $res = (int)str_replace('lin:', '', str_replace('win:', '', $system_disk_size));
            }
        }
    }
    return $res;
}

function zjmfcloud_GetDataDiskSize($params, $data_disk_size, $key = 'data_disk_size'){
	$res = [];
	if(strpos($data_disk_size, ',') !== false){
        $data_disk = explode(',', $data_disk_size);
        $res = [
            'size'=>$data_disk[0],
            'store'=>$data_disk[1],
        ];
    }else{
        $pdo = Capsule::connection()->getPdo();

        $data_disk_size_config = $pdo->query("SELECT `tblproductconfigoptions`.* FROM `tblhosting` LEFT JOIN `tblproductconfiglinks` ON `tblhosting`.`packageid`=`tblproductconfiglinks`.`pid` LEFT JOIN `tblproductconfigoptions` ON `tblproductconfiglinks`.`gid`=`tblproductconfigoptions`.`gid` WHERE `tblproductconfigoptions`.`optionname` LIKE '%{$key}|%' AND `tblhosting`.`id`={$params['serviceid']}")->fetch(PDO::FETCH_ASSOC);
        // 数量
        if($data_disk_size_config['optiontype'] == 4){
            // 是否有存储
            $sub = $pdo->query("SELECT `tblproductconfigoptionssub`.* FROM `tblhostingconfigoptions` LEFT JOIN `tblproductconfigoptionssub` ON `tblhostingconfigoptions`.`optionid`=`tblproductconfigoptionssub`.`id` WHERE `tblhostingconfigoptions`.`configid`={$data_disk_size_config['id']}  AND `tblhostingconfigoptions`.`relid`={$params['serviceid']}")->fetch(PDO::FETCH_ASSOC);
            $optionname = $sub['optionname'];
            if(strpos($optionname, '|') !== false){
                $optionname = explode('|', $optionname);
                $res = [
                    'size'=>$data_disk_size,
                    'store'=>(int)$optionname[0],
                ];
            }else{
                $res = [
					'size'=>$data_disk_size,
                ];
            }
        }else{
            $res = [
                'size'=>$data_disk_size,
            ];
        }
    }
    return $res;
}

function zjmfcloud_AddTable(){
	$sql = "CREATE TABLE IF NOT EXISTS `zjmfcloud_disk_link` (
	  `option_name` varchar(30) NOT NULL DEFAULT '' COMMENT '字段名称',
	  `host_id` int(11) NOT NULL DEFAULT '0' COMMENT 'tblhosting',
	  `disk_id` int(11) NOT NULL DEFAULT '0' COMMENT '数据盘ID'
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	full_query($sql);
}

function zjmfcloud_GetDiskLink($params){
	return (array)Capsule::table('zjmfcloud_disk_link')
        ->where('host_id', '=', $params['serviceid'])
        ->get();
}

function zjmfcloud_GetDiskId($option_name, $host_id){
	return Capsule::table('zjmfcloud_disk_link')
		->where('option_name', '=', $option_name)
        ->where('host_id', '=', $host_id)
        ->value('disk_id');
}

function zjmfcloud_NeedDiskSync($params){
	$data_disk_size=isset($params['configoptions']['data_disk_size'])?$params['configoptions']['data_disk_size']:$params['configoption18'];
	$data1_disk_size=$params['configoptions']['data1_disk_size'];
    $data2_disk_size=$params['configoptions']['data2_disk_size'];
    $data3_disk_size=$params['configoptions']['data3_disk_size'];
    $data4_disk_size=$params['configoptions']['data4_disk_size'];
    // 至少有一个数据盘
    if(!empty($data_disk_size) || !empty($data1_disk_size) || !empty($data2_disk_size) || !empty($data3_disk_size) || !empty($data4_disk_size)){
    	return empty(zjmfcloud_GetDiskLink($params));
    }
    return false;
}

/**
 * 时间 2022-06-23
 * @title 添加数据盘关联
 * @author hh
 * @version v1
 * @param   string  $option_name 数据盘标识(data_disk_size..)
 * @param   int     $host_id     产品ID
 * @param   integer $disk_id     魔方云数据盘ID
 */
function zjmfcloud_AddDiskLink($option_name, $host_id, $disk_id = 0){
	$data_link = Capsule::table('zjmfcloud_disk_link')
				->where('option_name', '=', $option_name)
        		->where('host_id', '=', $host_id)
        		->first();
    if(empty($data_link)){
		$insert = [
			'option_name' => $option_name,
			'host_id'     => $host_id,
			'disk_id'     => $disk_id
		];
		Capsule::table('zjmfcloud_disk_link')->insert($insert);
	}else{
		Capsule::table('zjmfcloud_disk_link')
		->where('option_name', '=', $option_name)
        ->where('host_id', '=', $host_id)
		->update(['disk_id'=>$disk_id]);
	}
	return true;
}

function zjmfcloud_Langset($key, $vars = []){
	global $_LANG;
	$res = $key;
    if(isset($_LANG[$key])){
        $res = (string)$_LANG[$key];

        if(!empty($vars)){
            $replace = array_keys($vars);
            foreach ($replace as &$v) {
                $v = '{'.$v.'}';
            }
            $res = str_replace($replace, $vars, $res);
        }
    }
    return $res;
}
