<?php
// +-------------------------------------------------------------------
// | PHP插件前置处理模块
// +-------------------------------------------------------------------
class bt_panel_plugin
{
	//启动PHP插件
	public function run(){
		$this->init();
		return $this->plugin_main();
	}
	
	//初始化插件环境
	private function init(){
		try {

			$input = file_get_contents('php://stdin');
			$params = json_decode($input, true);

			// 检查解析是否成功
			if (json_last_error() !== JSON_ERROR_NONE) {
				return_status(false, 'Invalid JSON input');
			}

			//检查必要参数
			if(!isset($params['name'])  || !isset($params['s']) || !isset($params['panel_path'])) {
				return_status(false, GetLang('缺少必要参数:{}', ['name/s/panel_path']));
			}
			$panel_path = $params['panel_path'];

			$args_arr = array();
			if(isset($params['args'])) {
				$args_arr = $params['args'];
			}

			//初始化插件配置
			define('PANEL_PATH', $panel_path);
			define('PLU_PATH', $panel_path.'/plugin/'.$params['name']);
			define('PLU_NAME',$params['name']);
			define('PLU_ARGS',$args_arr);
			define('PLU_FUN',$params['s']);
			
			
			$main_file = PLU_PATH . '/index.php';
			if(!file_exists($main_file)) {
				return_status(false, GetLang('插件不存在:{}', [$params['plugin_name']]));
			}
			if(!preg_match("/^[\w-]+$/",PLU_FUN)) return_status(false, GetLang('方法名不合法:{}', [PLU_FUN]));
			chdir(PLU_PATH);
		} catch (Throwable $e) { // 捕获所有异常和错误（PHP 7+）
			// 返回错误信息
			return return_status(false, GetLang('方法执行出错:{}', [$e->getMessage()]));
		}
	}
	

	//调用插件主程序
	private function plugin_main() {

		include_once PLU_PATH . '/index.php';
		if (!class_exists('bt_main')) {
			return return_status(false, GetLang('没有找到{}类', ['bt_main']));
		}
		try {
			$plu = new bt_main();
			$method = PLU_FUN; // 避免多次使用常量

			if (!method_exists($plu, $method)) {
				throw new BadMethodCallException(GetLang("指定方法 {} 不存在!", [$method]));
			}

			// 动态调用并返回结果
			return call_user_func([$plu, $method]);
			
		} catch (Throwable $e) { // 捕获所有异常和错误（PHP 7+）
			// 返回错误信息
			return return_status(false,GetLang('方法执行出错:{}', [$e->getMessage()]));
		}
	}
}

class db extends SQLite3
{
	function __construct($db_file = '../data/default.db') {		
        $this->open($db_file);
    }

	public function queryute($sql){
		$result = $this->query($sql);
		$data = $result->fetchArray(SQLITE3_ASSOC);
		return $data;
	}

	public function execute(){
		$result = $this->exec($sql);
		return $result;
	}
}

/**
 * 多语言消息格式化
 * @param string $msg 消息模板，使用 {key} 占位符
 * @param array $keys 替换的键值对
 * @return string 格式化后的消息
 */
function GetLang(string $msg, array $keys): string {

	$now_lang = GetNowLang();
	$hash = md5(str_replace(" ", "", $msg));
    $filename = PANEL_PATH . "/languages/" . $now_lang . "/server.json";
	if (file_exists($filename)) {
		// 从语言文件中读取
		$lang_data = json_decode(file_get_contents($filename), true);
		if (isset($lang_data[$hash]) && !empty($lang_data[$hash])) {
			$msg = $lang_data[$hash];
		} 
	}
	foreach ($keys as $key) {
		$msg = preg_replace('/\{\}/', $key, $msg, 1);
	}
	return $msg;
}

//获取当前语言
function GetNowLang(): string {
	$conf_file = PANEL_PATH . "/config/config.json";
	if (file_exists($conf_file)) {
		$lang_data = json_decode(file_get_contents($conf_file), true);
		if (isset($lang_data['language']) && !empty($lang_data['language'])) {
			return $lang_data['language'];
		}
	} 
	return "zh";
}

//取指安参数
function _args($_t,$key){
		
	if($key){
		if(!array_key_exists($key, PLU_ARGS)) return false;
		return PLU_ARGS[$key];
	}
	return PLU_ARGS;
}

function _version(){
    $version_file = PANEL_PATH.'/data/version.pl';
    if(file_exists($version_file)){
        $version = file_get_contents($version_file);
        return $version;
    }
	return '1.0.0';
}

//取GET参数
function _get($key = null){
	return _args('GET',$key);
}

//取POST参数
function _post($key=null){
	return _args('POST',$key);
}

//通用返回状态
function return_status($status,$msg){
	exit(json_encode(array('status'=>$status,'msg'=>$msg)));
}

//返回数据
function _return($data){
	exit(json_encode($data));
}

/**
 * 发起GET请求
 * @param String $url 目标网填，带http://
 * @return bool
 */
function _httpGet($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_TIMEOUT, 6);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip, deflate'));
	curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
	curl_setopt($ch, CURLOPT_USERAGENT, "BT-Panel for PHP-Plugin");
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 3);
	$output = curl_exec($ch);
	curl_close($ch);
	return $output;
}

//发起POST请求
function _httpPost($url,$data){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_USERAGENT, "BT-Panel for PHP-Plugin");
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	$output = curl_exec($ch);
	curl_close($ch);
	return $output;
}

//启动插件
$p = new bt_panel_plugin();
_return($p->run());
?>