<?php
use WHMCS\Database\Capsule;

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

// 登录
function zjmfcloud_Login($params, $force = false){
    if(!$force){
        $access_token = zjmfcloud_GetToken($params['serverid']);
        if($access_token){
            return ['status'=>'success', 'token'=>$access_token];
        }
    }
	$post_data['username'] = $params['serverusername'];
	$post_data['password'] = $params['serverpassword'];
    $accesshash = zjmfcloud_AccessHash($params['serveraccesshash']);
    if($accesshash['account_type'] == 'admin'){
        $res = zjmfcloud_Basecurl($params, '/login?a=a', $post_data);
    }else{
        $res = zjmfcloud_Basecurl($params, '/token', $post_data);
    }
	if($res['status'] == 'success'){
        if($accesshash['account_type'] == 'admin'){
            $access_token = trim($res['origin'], '"');
        }else{
            $access_token = $res['data']['token'];
        }
        zjmfcloud_SetToken($params['serverid'], $access_token);
		return ['status'=>'success', 'token'=>$access_token];
	}else{
		return ['status'=>'error', 'msg'=>$res['msg']];
	}   
}

// 获取token
function zjmfcloud_GetToken($serverid = 0){
    if(empty($serverid)){
        return false;
    }
	$content = file_get_contents(ZJMFCLOUD_TOKEN_FILE);
    $content = str_replace("<?php //", '', $content);
    $content = ltrim($content);

	$data = json_decode($content, true);
	if(empty($data[$serverid]) || $data[$serverid]['time']<time()){
		return false;
	}
	return $data[$serverid]['token'];
}
// 写入token
function zjmfcloud_SetToken($serverid, $token){
    if(empty($serverid)){
        return false;
    }
    if(!file_exists(ZJMFCLOUD_TOKEN_FILE)){
        touch(ZJMFCLOUD_TOKEN_FILE);
    }
	if (!is_writable(ZJMFCLOUD_TOKEN_FILE)) return false;
    $content = file_get_contents(ZJMFCLOUD_TOKEN_FILE);
    $content = str_replace('<?php //', '', $content);
    $content = ltrim($content);

    $data = json_decode($content,true) ?: [];

    $data[$serverid]['time'] = time() + 6*3600;
    $data[$serverid]['token'] = $token;
    return file_put_contents(ZJMFCLOUD_TOKEN_FILE, "<?php //".json_encode($data), LOCK_EX);
}

// 删除TOKEN
function zjmfcloud_DelToken($serverid = 0){
    if(empty($serverid)){
        return false;
    }
	if (!is_writable(ZJMFCLOUD_TOKEN_FILE)) return false;

    $content = file_get_contents(ZJMFCLOUD_TOKEN_FILE);
    $content = str_replace('<?php //', '', $content);
    $content = ltrim($content);
    $data = json_decode($content,true) ?: [];
    unset($data[$serverid]);
	return file_put_contents(ZJMFCLOUD_TOKEN_FILE, "<?php //".json_encode($data), LOCK_EX);
}
function zjmfcloud_Curl($params, $action = '', $data = [], $timeout = 30, $request = 'POST', $relogin = true){
    $res = zjmfcloud_Login($params);
    if($res['status'] == 'error'){
        return ['status'=>'error', 'msg'=>$res['msg']];
    }
    $header = [
        'access-token: '.$res['token']
    ];
    $result = zjmfcloud_Basecurl($params, $action, $data, $timeout, $request, $header);
    // 如果登录失效重试一次
    if($relogin && $result['status'] == 'error' && $result['http_code'] == 401){
        $r = zjmfcloud_Login($params, true);
        if($r['status'] == 'error'){
            return ['status'=>'error', 'msg'=>$r['msg']];
        }
        $header = [
            'access-token: '.$r['token']
        ];
        $result = zjmfcloud_Basecurl($params, $action, $data, $timeout, $request, $header);
    }
    return $result;
}
function zjmfcloud_Basecurl($params, $action = '', $data = [], $timeout = 30, $request = 'POST', $header = []){
    $accesshash = zjmfcloud_AccessHash($params['serveraccesshash']);
    if($accesshash['account_type'] == 'admin'){
        $url = zjmfcloud_GetUrl($params) . '/v1'.$action;
    }else{
        $url = zjmfcloud_GetUrl($params).'/index.php?path='.trim($action, '/');
    }
    $curl = curl_init();
    if($request == 'GET'){
        $s = '';
        if(!empty($data)){
            foreach($data as $k=>$v){
                $s .= $k.'='.urlencode($v).'&';
            }
        }
        if($s){
            if($accesshash['account_type'] == 'admin'){
                $s = '?'.trim($s, '&');
            }else{
                $s = '&'.trim($s, '&');
            }
        }
        curl_setopt($curl, CURLOPT_URL, $url.$s);
    }else{
        curl_setopt($curl, CURLOPT_URL, $url);
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_USERAGENT, 'WHMCS');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //curl_setopt($curl, CURLOPT_COOKIESESSION, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if(strtoupper($request) == 'GET'){
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPGET, 1);
    }
    if(strtoupper($request) == 'POST'){
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        if(is_array($data)){
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }else{
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    }
    if(strtoupper($request) == 'PUT' || strtoupper($request) == 'DELETE'){
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, strtoupper($request));
        if(is_array($data)){
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }else{
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    }
    if(!empty($header)){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
    $content = curl_exec($curl);
    $error = curl_error($curl);
    if(!empty($error)){
        return ['status'=>'error', 'msg'=>'CURL ERROR:'.$error];
    }
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    $res = json_decode($content, true);
    if(isset($res['error'])){
        if($http_code == 401){
            zjmfcloud_DelToken($params['serverid']);
        }
        return ['status'=>'error', 'msg'=>$res['error'], 'http_code'=>$http_code];
    }else if($http_code >= 200 && $http_code < 300){
        return ['status'=>'success', 'data'=>$res, 'origin'=>$content];
    }else{
        return ['status'=>'error', 'msg'=>'请求失败,HTTP状态码:'.$http_code, 'http_code'=>$http_code];
    }
}