<?php
/**
 * APP API 代理
 * 完全复用前端API的实现
 */

require_once __DIR__ . '/../MPHX/common.php';

header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 加密密钥
define('APP_API_SECRET', isset($conf['app_api_secret']) ? $conf['app_api_secret'] : 'mleoe_app_default_secret_key_2024');

/**
 * APP API代理类
 * 复用前端API的实现
 */
class AppAPIProxy {
    
    private $DB;
    private $conf;
    private $currentUser = null;
    private $currentBtApi = null;
    
    public function __construct() {
        global $DB, $conf;
        $this->DB = $DB;
        $this->conf = $conf;
    }
    
    /**
     * 验证令牌并设置当前用户
     */
    public function verifyToken($token) {
        if (empty($token)) {
            return ['code' => -1, 'msg' => '令牌不能为空'];
        }
        
        $token_info = $this->DB->get_row("SELECT * FROM `app_access_tokens` WHERE `token`='{$token}' AND `status`=1");
        
        if (!$token_info) {
            return ['code' => -1, 'msg' => '令牌无效或已失效'];
        }
        
        // 检查是否过期
        if ($token_info['expire_time'] > 0 && $token_info['expire_time'] < time()) {
            $this->DB->query("UPDATE `app_access_tokens` SET `status`=0 WHERE `id`={$token_info['id']}");
            return ['code' => -1, 'msg' => '令牌已过期'];
        }
        
        // 检查使用次数
        if ($token_info['max_uses'] > 0 && $token_info['used_count'] >= $token_info['max_uses']) {
            $this->DB->query("UPDATE `app_access_tokens` SET `status`=0 WHERE `id`={$token_info['id']}");
            return ['code' => -1, 'msg' => '令牌使用次数已达上限'];
        }
        
        // 解密数据
        $access_data = json_decode($this->decryptData($token_info['access_data']), true);
        if (!$access_data) {
            return ['code' => -1, 'msg' => '数据解密失败'];
        }
        
        // 获取用户最新数据
        $user_id = isset($access_data['user_id']) ? $access_data['user_id'] : (isset($access_data['zjid']) ? $access_data['zjid'] : 0);
        $user = $this->DB->get_row("SELECT * FROM `zj` WHERE `id`='{$user_id}'");
        
        if (!$user) {
            return ['code' => -1, 'msg' => '用户不存在'];
        }
        
        // 更新使用记录
        $now = time();
        $client_ip = $_SERVER['REMOTE_ADDR'];
        $this->DB->query("UPDATE `app_access_tokens` SET 
            `used_count`=`used_count`+1, 
            `last_use_time`={$now}, 
            `last_use_ip`='{$client_ip}' 
            WHERE `id`={$token_info['id']}");
        
        // 设置当前用户
        $this->currentUser = $user;
        
        // 初始化宝塔API
        $bt = $this->DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user['btid']}'");
        if ($bt) {
            $this->currentBtApi = new bt_api();
            $protocol = ($bt['aqfw'] == 'true') ? 'https' : 'http';
            $this->currentBtApi->BT_PANEL = $protocol . '://' . $bt['ip'] . ':' . $bt['dk'];
            $this->currentBtApi->BT_KEY = $bt['key'];
        }
        
        return ['code' => 200, 'msg' => '验证成功', 'user' => $user];
    }
    
    /**
     * 获取当前用户
     */
    public function getCurrentUser() {
        return $this->currentUser;
    }
    
    /**
     * 获取当前宝塔API
     */
    public function getCurrentBtApi() {
        return $this->currentBtApi;
    }
    
    /**
     * 调用前端API
     */
    public function callFrontendAPI($apiClass, $method, $params = []) {
        // 设置全局用户变量，让前端API可以访问
        global $_CURRENT_USER, $_CURRENT_BT_API;
        $_CURRENT_USER = $this->currentUser;
        $_CURRENT_BT_API = $this->currentBtApi;
        
        // 加载前端API类
        $apiFile = __DIR__ . '/../user/api/' . $apiClass . '/' . $apiClass . '_api.php';
        if (!file_exists($apiFile)) {
            // 尝试其他路径
            $apiFile = __DIR__ . '/../user/api/' . $apiClass . '.php';
        }
        
        if (!file_exists($apiFile)) {
            return ['code' => -1, 'msg' => 'API类不存在: ' . $apiClass];
        }
        
        require_once $apiFile;
        
        // 构建类名
        $className = ucfirst($apiClass) . 'API';
        if (!class_exists($className)) {
            return ['code' => -1, 'msg' => 'API类未找到: ' . $className];
        }
        
        try {
            $api = new $className();
            
            if (!method_exists($api, $method)) {
                return ['code' => -1, 'msg' => 'API方法不存在: ' . $method];
            }
            
            // 调用方法
            $result = call_user_func_array([$api, $method], $params);
            
            // 捕获输出（前端API可能直接输出）
            $output = ob_get_clean();
            if (!empty($output)) {
                $decoded = json_decode($output, true);
                if ($decoded !== null) {
                    return $decoded;
                }
            }
            
            return $result;
            
        } catch (Exception $e) {
            return ['code' => -1, 'msg' => 'API调用失败: ' . $e->getMessage()];
        }
    }
    
    /**
     * 解密数据
     */
    private function decryptData($data) {
        $key = hash('sha256', APP_API_SECRET, true);
        $data = base64_decode($data);
        $iv = substr($data, 0, 16);
        $encrypted = substr($data, 16);
        return openssl_decrypt($encrypted, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    }
    
    /**
     * 加密数据
     */
    private function encryptData($data) {
        $key = hash('sha256', APP_API_SECRET, true);
        $iv = openssl_random_pseudo_bytes(16);
        $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $encrypted);
    }
}

// 处理API请求
$action = isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : '');
$token = isset($_POST['token']) ? $_POST['token'] : (isset($_GET['token']) ? $_GET['token'] : '');

$proxy = new AppAPIProxy();

// 验证令牌（除了生成令牌的请求）
if ($action != 'generate_token' && $action != 'verify_token') {
    $verifyResult = $proxy->verifyToken($token);
    if ($verifyResult['code'] != 200) {
        echo json_encode($verifyResult);
        exit;
    }
}

// API路由映射 - 将APP action映射到前端API
$apiMap = [
    // PHP版本
    'get_php_versions' => ['class' => 'php', 'method' => 'getPhpVersions'],
    'set_php_version' => ['class' => 'php', 'method' => 'setPhpVersion', 'params' => ['version']],
    
    // 域名管理
    'get_domains' => ['class' => 'domain', 'method' => 'getDomainList'],
    'add_domain' => ['class' => 'domain', 'method' => 'addDomain', 'params' => ['domain']],
    'delete_domain' => ['class' => 'domain', 'method' => 'deleteDomain', 'params' => ['domain', 'port']],
    'get_dir_binding' => ['class' => 'domain', 'method' => 'getDirBinding'],
    'add_dir_binding' => ['class' => 'domain', 'method' => 'addDirBinding', 'params' => ['domain', 'dir']],
    'delete_dir_binding' => ['class' => 'domain', 'method' => 'deleteDirBinding', 'params' => ['id']],
    
    // 文件管理
    'get_files' => ['class' => 'file', 'method' => 'getFiles', 'params' => ['path']],
    'create_file' => ['class' => 'file', 'method' => 'createFile', 'params' => ['path', 'content']],
    'create_dir' => ['class' => 'file', 'method' => 'createFolder', 'params' => ['path', 'name']],
    'delete_file' => ['class' => 'file', 'method' => 'deleteFile', 'params' => ['path']],
    'rename_file' => ['class' => 'file', 'method' => 'renameFile', 'params' => ['path', 'newName']],
    'get_file_content' => ['class' => 'file', 'method' => 'getFileContent', 'params' => ['path']],
    'save_file_content' => ['class' => 'file', 'method' => 'saveFile', 'params' => ['path', 'content']],
    'upload_file' => ['class' => 'file', 'method' => 'uploadFile', 'params' => ['path']],
    
    // 备份管理
    'get_backup_list' => ['class' => 'backup', 'method' => 'getBackups'],
    'create_backup' => ['class' => 'backup', 'method' => 'createBackup'],
    'delete_backup' => ['class' => 'backup', 'method' => 'deleteBackup', 'params' => ['id']],
    'restore_backup' => ['class' => 'backup', 'method' => 'restoreBackup', 'params' => ['id']],
    
    // 计划任务
    'get_cron_list' => ['class' => 'cron', 'method' => 'getCronTasks'],
    'add_cron' => ['class' => 'cron', 'method' => 'addCronTask'],
    'toggle_cron' => ['class' => 'cron', 'method' => 'toggleCronTask', 'params' => ['id']],
    'delete_cron' => ['class' => 'cron', 'method' => 'deleteCronTask', 'params' => ['id']],
    
    // 站点设置
    'get_site_info' => ['class' => 'site', 'method' => 'getSiteInfo'],
    'get_ssl_info' => ['class' => 'site', 'method' => 'getSSL'],
    'set_ssl' => ['class' => 'site', 'method' => 'setSSL', 'params' => ['type', 'key', 'cert']],
    'get_encrypt_list' => ['class' => 'site', 'method' => 'getEncryptList'],
    'add_encrypt' => ['class' => 'site', 'method' => 'addEncrypt', 'params' => ['path', 'name', 'username', 'password']],
    'delete_encrypt' => ['class' => 'site', 'method' => 'deleteEncrypt', 'params' => ['path']],
    'get_forbid_list' => ['class' => 'site', 'method' => 'getForbidList'],
    'add_forbid' => ['class' => 'site', 'method' => 'addForbid', 'params' => ['name', 'ext', 'path']],
    'delete_forbid' => ['class' => 'site', 'method' => 'deleteForbid', 'params' => ['path']],
    
    // 流量统计
    'get_traffic_stats' => ['class' => 'traffic', 'method' => 'getTrafficStats'],
    
    // 部署
    'get_deploy_list' => ['class' => 'deploy', 'method' => 'getDeployList'],
    'start_deploy' => ['class' => 'deploy', 'method' => 'deployProgram', 'params' => ['id']],
];

// 处理请求
if (isset($apiMap[$action])) {
    $apiConfig = $apiMap[$action];
    $params = [];
    
    // 构建参数
    if (isset($apiConfig['params'])) {
        foreach ($apiConfig['params'] as $param) {
            $value = isset($_POST[$param]) ? $_POST[$param] : (isset($_GET[$param]) ? $_GET[$param] : '');
            $params[] = $value;
        }
    }
    
    // 调用前端API
    $result = $proxy->callFrontendAPI($apiConfig['class'], $apiConfig['method'], $params);
    
    // 转换返回格式
    if (isset($result['status']) && $result['status'] === true) {
        echo json_encode(['code' => 200, 'msg' => $result['msg'] ?? '成功', 'data' => $result]);
    } else {
        echo json_encode(['code' => -1, 'msg' => $result['msg'] ?? $result['error'] ?? '失败', 'data' => $result]);
    }
} else {
    echo json_encode(['code' => -1, 'msg' => '未知的API操作: ' . $action]);
}
