<?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代理类
 */
class AppAPIProxy {
    
    private $DB;
    private $conf;
    private $currentUser = null;
    private $currentBtApi = null;
    private $currentBtInfo = 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->currentBtInfo = $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;
    }
    
    /**
     * 获取当前宝塔信息
     */
    public function getCurrentBtInfo() {
        return $this->currentBtInfo;
    }
    
    /**
     * 调用前端API - 通过HTTP请求方式
     */
    public function callFrontendAPI($action, $params = []) {
        // 构建请求URL
        $url = 'http://' . $_SERVER['HTTP_HOST'] . '/user/api/api_router.php';
        
        // 构建POST数据
        $postData = array_merge([
            'action' => $action
        ], $params);
        
        // 使用cURL发送请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HEADER, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode != 200 || empty($response)) {
            return ['code' => -1, 'msg' => 'API请求失败'];
        }
        
        $result = json_decode($response, true);
        if ($result === null) {
            return ['code' => -1, 'msg' => 'API返回数据解析失败'];
        }
        
        return $result;
    }
    
    /**
     * 解密数据
     */
    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 action
$apiMap = [
    // PHP版本
    'get_php_versions' => 'getPhpVersions',
    'set_php_version' => 'setPhpVersion',
    
    // 域名管理
    'get_domains' => 'getDomainList',
    'add_domain' => 'addDomain',
    'delete_domain' => 'deleteDomain',
    'get_dir_binding' => 'getDirBinding',
    'add_dir_binding' => 'addDirBinding',
    'delete_dir_binding' => 'deleteDirBinding',
    
    // 文件管理
    'get_files' => 'getFiles',
    'create_file' => 'createFile',
    'create_dir' => 'createFolder',
    'delete_file' => 'deleteFile',
    'rename_file' => 'renameFile',
    'get_file_content' => 'getFileContent',
    'save_file_content' => 'saveFile',
    'upload_file' => 'uploadFile',
    
    // 备份管理
    'get_backup_list' => 'getBackups',
    'create_backup' => 'createBackup',
    'delete_backup' => 'deleteBackup',
    'restore_backup' => 'restoreBackup',
    
    // 计划任务
    'get_cron_list' => 'getCronTasks',
    'add_cron' => 'addCronTask',
    'toggle_cron' => 'toggleCronTask',
    'delete_cron' => 'deleteCronTask',
    
    // 站点设置
    'get_site_info' => 'getSiteInfo',
    'get_ssl_info' => 'getSSL',
    'set_ssl' => 'setSSL',
    'get_encrypt_list' => 'getEncryptList',
    'add_encrypt' => 'addEncrypt',
    'delete_encrypt' => 'deleteEncrypt',
    'get_forbid_list' => 'getForbidList',
    'add_forbid' => 'addForbid',
    'delete_forbid' => 'deleteForbid',
    
    // 流量统计
    'get_traffic_stats' => 'getTrafficStats',
    
    // 部署
    'get_deploy_list' => 'getDeployList',
    'start_deploy' => 'deployProgram',
];

// 处理请求
if (isset($apiMap[$action])) {
    $frontendAction = $apiMap[$action];
    
    // 收集所有参数
    $params = [];
    foreach ($_POST as $key => $value) {
        if ($key != 'action' && $key != 'token') {
            $params[$key] = $value;
        }
    }
    foreach ($_GET as $key => $value) {
        if ($key != 'action' && $key != 'token' && !isset($params[$key])) {
            $params[$key] = $value;
        }
    }
    
    // 调用前端API
    $result = $proxy->callFrontendAPI($frontendAction, $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]);
}
