<?php
// 关闭错误显示，避免输出非JSON内容破坏响应
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

// 设置错误日志（已禁用）
ini_set('log_errors', 0);
// ini_set('error_log', __DIR__ . '/../../logs/api_error.log');

// 启动session以支持CSRF防护
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// CSRF防护函数
function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validateCsrfToken($token) {
    if (empty($_SESSION['csrf_token']) || empty($token)) {
        return false;
    }
    return hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * 格式化日志内容，隐藏根目录路径
 * @param string $content 原始日志内容
 * @param string $username 用户名
 * @return string 格式化后的内容
 */
function formatLogContent($content, $username) {
    if (empty($content)) return '';

    // 匹配 /www/wwwroot/用户名/ 前缀并替换为 /
    $pattern = '/\/www\/wwwroot\/' . preg_quote($username, '/') . '\//i';
    $content = preg_replace($pattern, '/', $content);

    // 也处理 Windows 路径格式 D:/wwwroot/用户名/
    $pattern = '/D:\/wwwroot\/' . preg_quote($username, '/') . '\//i';
    $content = preg_replace($pattern, '/', $content);

    return $content;
}

// 测试路由：绕过登录验证
if (isset($_GET['test']) && $_GET['test'] == 'domain_list') {
    // 从数据库配置获取主域名，避免硬编码
    global $conf;
    $main_domain = isset($conf['main_domain']) && !empty($conf['main_domain']) ? $conf['main_domain'] : 'a116.vip';
    
    // 直接输出默认的域名列表
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode(array(
        'code' => 'success',
        'domains' => array(
            array(
                'name' => 'zhibi.' . $main_domain,
                'port' => 80,
                'id' => 0
            )
        ),
        'server_ip' => isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '127.0.0.1'
    ));
    exit;
}

require_once __DIR__ . '/base_api.php';
require_once __DIR__ . '/auth/auth_api.php';
require_once __DIR__ . '/php/php_api.php';
require_once __DIR__ . '/domain/domain_api.php';
require_once __DIR__ . '/site/site_api.php';
require_once __DIR__ . '/file/file_api.php';
require_once __DIR__ . '/backup/backup_api.php';
require_once __DIR__ . '/cron/cron_api.php';
require_once __DIR__ . '/traffic/traffic_api.php';
require_once __DIR__ . '/deploy/deploy_api.php';

header('Content-Type: application/json; charset=UTF-8');

// 支持JSON格式的请求数据
$input_data = file_get_contents('php://input');
if (!empty($input_data)) {
    $json_data = json_decode($input_data, true);
    if ($json_data !== null) {
        $_POST = array_merge($_POST, $json_data);
    }
}

$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : '');

// 需要CSRF防护的操作列表（排除登录、登出等公开操作）
$csrf_required_actions = array(
    'xgmm', 'changepassword', 'updateprofile',
    'send_email_verify_code', 'verify_email',
    'create_database', 'delete_database', 'modify_database',
    'create_ftp', 'delete_ftp', 'modify_ftp',
    'create_site', 'delete_site', 'modify_site',
    'uploadfile', 'uploadchunk', 'delete_file', 'rename_file',
    'create_backup', 'delete_backup', 'restore_backup',
    'create_cron', 'delete_cron', 'modify_cron',
    'apply_ssl', 'delete_ssl',
    'deploy_app', 'delete_deploy',
    'set_php_version', 'set_php_config',
    'add_domain', 'delete_domain',
    'add_subdirectory', 'delete_subdirectory',
    'set_access_limit', 'delete_access_limit',
    'set_anti_hotlink', 'delete_anti_hotlink',
    'set_run_dir', 'set_default_doc',
    'set_rewrite', 'clear_cache',
    'generate_token', 'delete_token'
);

// 验证CSRF Token（对于需要防护的操作）
if (in_array($action, $csrf_required_actions)) {
    $csrf_token = isset($_POST['csrf_token']) ? $_POST['csrf_token'] : (isset($_GET['csrf_token']) ? $_GET['csrf_token'] : '');
    if (!validateCsrfToken($csrf_token)) {
        header('Content-Type: application/json; charset=UTF-8');
        echo json_encode(array('code' => 'error', 'msg' => 'CSRF验证失败，请刷新页面后重试'));
        exit;
    }
}

switch ($action) {
    // 认证相关
    case 'login':
        if (isset($_GET['logout']) || isset($_POST['logout'])) {
            $auth_api = new AuthAPI();
            $auth_api->logout();
        }
        
        if (isset($_POST['user']) && isset($_POST['pass'])) {
            $user = daddslashes($_POST['user']);
            $pass = daddslashes($_POST['pass']);
            $code = daddslashes($_POST['code']);
            
            $auth_api = new AuthAPI();
            $auth_api->login($user, $pass, $code);
        }
        break;
        
    case 'xgmm':
        $oldpass = daddslashes($_POST['oldpass']);
        $newpass = daddslashes($_POST['newpass']);
        
        $auth_api = new AuthAPI();
        $auth_api->changePassword($oldpass, $newpass);
        break;
    
    // 邮箱验证相关
    case 'send_email_verify_code':
        require_once __DIR__ . '/auth/email_verify_api.php';
        $email_verify_api = new EmailVerifyAPI();
        $email_verify_api->sendVerifyCode();
        break;
        
    case 'verify_email':
        require_once __DIR__ . '/auth/email_verify_api.php';
        $email_verify_api = new EmailVerifyAPI();
        $email_verify_api->verifyEmail();
        break;
    
    // 个人资料相关
    case 'updateprofile':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '\u8bf7\u5148\u767b\u5f55'));
            exit;
        }
        
        $user_id = intval($user['id']);
        $realname = isset($_POST['realname']) ? daddslashes($_POST['realname']) : '';
        $email = isset($_POST['email']) ? daddslashes($_POST['email']) : '';
        $phone = isset($_POST['phone']) ? daddslashes($_POST['phone']) : '';
        
        // 验证邮箱格式
        if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo json_encode(array('code' => 'error', 'msg' => '\u90ae\u7bb1\u683c\u5f0f\u4e0d\u6b63\u786e'));
            exit;
        }
        
        // 处理头像上传
        $avatar_path = '';
        if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = dirname(__DIR__) . '/uploads/avatars/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_info = pathinfo($_FILES['avatar']['name']);
            $file_ext = strtolower($file_info['extension']);
            $allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
            
            if (!in_array($file_ext, $allowed_ext)) {
                echo json_encode(array('code' => 'error', 'msg' => '\u5934\u50cf\u683c\u5f0f\u4e0d\u652f\u6301\uff0c\u4ec5\u652f\u6301 JPG\u3001PNG\u3001GIF'));
                exit;
            }
            
            if ($_FILES['avatar']['size'] > 2 * 1024 * 1024) {
                echo json_encode(array('code' => 'error', 'msg' => '\u5934\u50cf\u5927\u5c0f\u4e0d\u80fd\u8d85\u8fc72MB'));
                exit;
            }
            
            $filename = 'avatar_' . $user_id . '_' . time() . '.' . $file_ext;
            $upload_path = $upload_dir . $filename;
            
            if (move_uploaded_file($_FILES['avatar']['tmp_name'], $upload_path)) {
                $avatar_path = '/user/uploads/avatars/' . $filename;
            } else {
                echo json_encode(array('code' => 'error', 'msg' => '\u5934\u50cf\u4e0a\u4f20\u5931\u8d25'));
                exit;
            }
        }
        
        // 更新用户资料 - 使用zj表的正确字段
        // 注意：这里使用isset判断，允许清空字段（空字符串也是有效值）
        $updates = array();
        if (isset($_POST['realname'])) {
            $realname_escaped = $DB->escape($realname);
            $updates[] = "realname='{$realname_escaped}'";
        }
        if (isset($_POST['email'])) {
            $email_escaped = $DB->escape($email);
            $updates[] = "email='{$email_escaped}'";
        }
        if (isset($_POST['phone'])) {
            $phone_escaped = $DB->escape($phone);
            $updates[] = "phone='{$phone_escaped}'";
        }
        if ($avatar_path !== '') {
            $avatar_path_escaped = $DB->escape($avatar_path);
            $updates[] = "avatar='{$avatar_path_escaped}'";
        }
        
        if (!empty($updates)) {
            $sql = "UPDATE `zj` SET " . implode(', ', $updates) . " WHERE id={$user_id}";
            $result = $DB->query($sql);
        }
        
        echo json_encode(array('code' => 'success', 'msg' => '\u4e2a\u4eba\u8d44\u6599\u66f4\u65b0\u6210\u529f'));
        exit;
        break;
    
    case 'changepassword':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '\u8bf7\u5148\u767b\u5f55'));
            exit;
        }
        
        $oldpass = daddslashes($_POST['oldpass']);
        $newpass = daddslashes($_POST['newpass']);
        
        if (empty($oldpass) || empty($newpass)) {
            echo json_encode(array('code' => 'error', 'msg' => '密码不能为空'));
            exit;
        }
        
        if (strlen($newpass) < 6) {
            echo json_encode(array('code' => 'error', 'msg' => '新密码长度至少6位'));
            exit;
        }
        
        // 验证原密码
        $user_id_escaped = intval($user['id']);
        $user_row = $DB->get_row("SELECT * FROM `zj` WHERE id={$user_id_escaped}");
        if (!$user_row) {
            echo json_encode(array('code' => 'error', 'msg' => '用户不存在'));
            exit;
        }
        
        // 验证密码（明文对比）
        if ($user_row['pass'] != $oldpass) {
            echo json_encode(array('code' => 'error', 'msg' => '原密码错误'));
            exit;
        }
        
        // 更新密码（明文存储）
        $newpass_escaped = $DB->escape($newpass);
        $user_id_escaped = intval($user['id']);
        $DB->query("UPDATE `zj` SET pass='{$newpass_escaped}' WHERE id={$user_id_escaped}");
        
        echo json_encode(array('code' => 'success', 'msg' => '密码修改成功'));
        exit;
        break;
    
    // 邮箱绑定
    case 'bindemail':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '请先登录'));
            exit;
        }
        
        $email = isset($_POST['email']) ? daddslashes($_POST['email']) : '';
        
        // 验证邮箱格式
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo json_encode(array('code' => 'error', 'msg' => '邮箱格式不正确'));
            exit;
        }
        
        // 检查邮箱是否已被其他用户使用
        $email_escaped = $DB->escape($email);
        $user_id_escaped = intval($user['id']);
        $existing = $DB->get_row("SELECT id FROM `zj` WHERE email='{$email_escaped}' AND id != {$user_id_escaped}");
        if ($existing) {
            echo json_encode(array('code' => 'error', 'msg' => '该邮箱已被其他用户使用'));
            exit;
        }
        
        // 更新用户邮箱
        $DB->query("UPDATE `zj` SET email='{$email_escaped}' WHERE id={$user_id_escaped}");
        
        echo json_encode(array('code' => 'success', 'msg' => '邮箱绑定成功'));
        exit;
        break;
    
    // PHP相关
    case 'checkphp':
        $php_api = new PhpAPI();
        $php_api->getPhpVersions();
        break;
        
    case 'setphp':
        $version = daddslashes($_POST['version']);
        
        $php_api = new PhpAPI();
        $php_api->setPhpVersion($version);
        break;
    
    // 域名相关
    case 'setym':
        $ym = daddslashes($_POST['ym']);
        
        $domain_api = new DomainAPI();
        $domain_api->addDomain($ym);
        break;
        
    case 'getymlist':
        $domain_api = new DomainAPI();
        $domain_api->getDomainList();
        break;
        
    case 'delym':
        $domain = daddslashes($_POST['domain']);
        $port = isset($_POST['port']) ? intval($_POST['port']) : 80;
        
        $domain_api = new DomainAPI();
        $domain_api->deleteDomain($domain, $port);
        break;

    // 域名子目录绑定相关
    case 'getdirbinding':
        $domain_api = new DomainAPI();
        $domain_api->getDirBinding();
        break;

    case 'adddirbinding':
        $domain = daddslashes($_POST['domain']);
        $dir = daddslashes($_POST['dir']);
        $domain_api = new DomainAPI();
        $domain_api->addDirBinding($domain, $dir);
        break;

    case 'deldirbinding':
        $id = intval($_POST['id']);
        $domain_api = new DomainAPI();
        $domain_api->deleteDirBinding($id);
        break;
        
    case 'getserverip':
        $domain_api = new DomainAPI();
        $domain_api->getServerIP();
        break;

    // 一键部署
    case 'deploy':
    case 'deploy_program':
        $program_id = isset($_POST['id']) ? intval($_POST['id']) : (isset($_POST['program_id']) ? intval($_POST['program_id']) : 0);
        $deploy_api = new DeployAPI();
        $deploy_api->deployProgram($program_id);
        break;
    
    // 购买程序
    case 'purchase_program':
        $program_id = isset($_POST['program_id']) ? intval($_POST['program_id']) : 0;
        $deploy_api = new DeployAPI();
        $deploy_api->purchaseProgram($program_id);
        break;
    
    // 站点相关
    case 'setpass':
        $username = daddslashes($_POST['username']);
        $password = daddslashes($_POST['password']);
        
        $site_api = new SiteAPI();
        $site_api->setPassword($username, $password);
        break;
        
    case 'getpassstatus':
        $site_api = new SiteAPI();
        $site_api->getPasswordStatus();
        break;
        
    case 'closepass':
        $site_api = new SiteAPI();
        $site_api->closePassword();
        break;
        
    case 'getencryptlist':
        $site_api = new SiteAPI();
        $site_api->getEncryptList();
        break;
        
    case 'getforbidlist':
        $site_api = new SiteAPI();
        $site_api->getForbidList();
        break;
        
    case 'addencrypt':
        $path = daddslashes($_POST['path']);
        $name = $_POST['name'];
        $username = daddslashes($_POST['username']);
        $password = daddslashes($_POST['password']);
        
        $site_api = new SiteAPI();
        $site_api->addEncrypt($path, $name, $username, $password);
        break;
        
    case 'addforbid':
        $name = daddslashes($_POST['name']);
        $ext = daddslashes($_POST['ext']);
        $path = daddslashes($_POST['path']);
        
        $site_api = new SiteAPI();
        $site_api->addForbid($name, $ext, $path);
        break;
        
    case 'deleteencrypt':
        $path = daddslashes($_POST['path']);
        
        $site_api = new SiteAPI();
        $site_api->deleteEncrypt($path);
        break;
        
    case 'deleteforbid':
        $path = daddslashes($_POST['path']);
        
        $site_api = new SiteAPI();
        $site_api->deleteForbid($path);
        break;
        
    case 'cleanupduplicateforbid':
        $site_api = new SiteAPI();
        $site_api->cleanupDuplicateForbid();
        break;
        
    case 'getmrwd':
        $site_api = new SiteAPI();
        $site_api->getIndex();
        break;
        
    case 'setmrwd':
        $index = daddslashes($_POST['index']);
        
        $site_api = new SiteAPI();
        $site_api->setIndex($index);
        break;
        
    case 'getyxml':
        $site_api = new SiteAPI();
        $site_api->getRunDir();
        break;
        
    case 'setyxml':
        $rundir = daddslashes($_POST['rundir']);
        
        $site_api = new SiteAPI();
        $site_api->setRunDir($rundir);
        break;
        
    case 'setwjt':
        $rewrite = daddslashes($_POST['rewrite']);
        $content = daddslashes($_POST['content']);
        
        $site_api = new SiteAPI();
        $site_api->setRewrite($rewrite, $content);
        break;
        
    case 'setssl':
        $type = daddslashes($_POST['type']);
        $key = daddslashes($_POST['key']);
        $cert = daddslashes($_POST['cert']);
        
        $site_api = new SiteAPI();
        $site_api->setSSL($type, $key, $cert);
        break;
        
    case 'getssl':
        $site_api = new SiteAPI();
        $site_api->getSSL();
        break;
        
    case 'setHttpToHttps':
        require_once __DIR__ . '/site/site_api.php';
        $enable = isset($_POST['type']) ? (int)$_POST['type'] : (isset($_POST['enable']) ? (int)$_POST['enable'] : 0);
        $site_api = new SiteAPI();
        $site_api->setHttpToHttps($enable);
        break;

    case 'getsslcert':
    case 'getsslcertlist':
    case 'getSSLCertList':
    case 'getsslcertificates':
        require_once __DIR__ . '/site/site_api.php';
        $site_api = new SiteAPI();
        $site_api->getSSLCertList();
        break;

    case 'applycert':
    case 'applyCertificate':
    case 'applysslcertificate':
        require_once __DIR__ . '/site/site_api.php';
        $brand = isset($_POST['brand']) ? daddslashes($_POST['brand']) : 'letsencrypt';
        $verifyMethod = isset($_POST['verifyMethod']) ? daddslashes($_POST['verifyMethod']) : 'file';
        $domains = isset($_POST['domains']) ? $_POST['domains'] : (isset($_POST['domain']) ? $_POST['domain'] : '');
        $site_api = new SiteAPI();
        $site_api->applyCertificate($brand, $verifyMethod, $domains);
        break;

    case 'deploycert':
    case 'deployCertificate':
    case 'deploysslcertificate':
        require_once __DIR__ . '/site/site_api.php';
        $cert_hash = isset($_POST['cert_hash']) ? daddslashes($_POST['cert_hash']) : (isset($_POST['id']) ? daddslashes($_POST['id']) : '');
        $site_api = new SiteAPI();
        $site_api->deployCertificate($cert_hash);
        break;
        
    case 'renewcert':
    case 'renewCertificate':
    case 'renewsslcertificate':
        require_once __DIR__ . '/site/site_api.php';
        $domain = isset($_POST['domain']) ? daddslashes($_POST['domain']) : '';
        $id = isset($_POST['id']) ? daddslashes($_POST['id']) : '';
        
        $site_api = new SiteAPI();
        if (empty($domain) && !empty($id)) {
            $cert_list_result = $site_api->getBtApi()->GetSSLCertList('0', 1, 100);
            if (is_array($cert_list_result)) {
                $certs = array();
                if (isset($cert_list_result['status'])) {
                    if (isset($cert_list_result['data']['list'])) $certs = $cert_list_result['data']['list'];
                    elseif (isset($cert_list_result['data'])) $certs = $cert_list_result['data'];
                } else {
                    $certs = $cert_list_result;
                }
                foreach ($certs as $cert) {
                    if (isset($cert['hash']) && $cert['hash'] == $id) {
                        $domain = isset($cert['subject']) ? $cert['subject'] : '';
                        break;
                    }
                }
            }
        }
        $site_api->renewCertificate($domain);
        break;
        
    case 'downloadcert':
    case 'downloadCertificate':
    case 'downloadsslcertificate':
        require_once __DIR__ . '/site/site_api.php';
        $cert_hash = isset($_POST['cert_hash']) ? daddslashes($_POST['cert_hash']) : (isset($_POST['id']) ? daddslashes($_POST['id']) : '');
        $domain = isset($_POST['domain']) ? daddslashes($_POST['domain']) : '';
        
        $site_api = new SiteAPI();
        if (empty($cert_hash) && !empty($domain)) {
            $cert_list_result = $site_api->getBtApi()->GetSSLCertList('0', 1, 100);
            if (is_array($cert_list_result)) {
                $certs = array();
                if (isset($cert_list_result['status'])) {
                    if (isset($cert_list_result['data']['list'])) $certs = $cert_list_result['data']['list'];
                    elseif (isset($cert_list_result['data'])) $certs = $cert_list_result['data'];
                } else {
                    $certs = $cert_list_result;
                }
                foreach ($certs as $cert) {
                    if (isset($cert['subject']) && $cert['subject'] == $domain) {
                        $cert_hash = isset($cert['hash']) ? $cert['hash'] : '';
                        break;
                    }
                }
            }
        }
        $site_api->downloadCertificate($cert_hash);
        break;
        
    case 'deletecert':
    case 'deleteCertificate':
    case 'deletesslcertificate':
        require_once __DIR__ . '/site/site_api.php';
        $cert_hash = isset($_POST['cert_hash']) ? daddslashes($_POST['cert_hash']) : (isset($_POST['id']) ? daddslashes($_POST['id']) : '');
        $domain = isset($_POST['domain']) ? daddslashes($_POST['domain']) : '';
        
        $site_api = new SiteAPI();
        if (empty($cert_hash) && !empty($domain)) {
            $cert_list_result = $site_api->getBtApi()->GetSSLCertList('0', 1, 100);
            if (is_array($cert_list_result)) {
                $certs = array();
                if (isset($cert_list_result['status'])) {
                    if (isset($cert_list_result['data']['list'])) $certs = $cert_list_result['data']['list'];
                    elseif (isset($cert_list_result['data'])) $certs = $cert_list_result['data'];
                } else {
                    $certs = $cert_list_result;
                }
                foreach ($certs as $cert) {
                    if (isset($cert['subject']) && $cert['subject'] == $domain) {
                        $cert_hash = isset($cert['hash']) ? $cert['hash'] : '';
                        break;
                    }
                }
            }
        }
        $site_api->deleteCertificate($cert_hash);
        break;

    case 'uploadcert':
    case 'uploadCertificate':
        require_once __DIR__ . '/site/site_api.php';
        $cert_key = isset($_POST['cert_key']) ? $_POST['cert_key'] : '';
        $cert_pem = isset($_POST['cert_pem']) ? $_POST['cert_pem'] : '';
        
        $site_api = new SiteAPI();
        if (empty($cert_key) || empty($cert_pem)) {
            $site_api->outputError('密钥和证书内容不能为空');
        }
        
        $site_api->uploadCertificate($cert_key, $cert_pem);
        break;
        
    case 'querysslstatus':
        require_once __DIR__ . '/site/site_api.php';
        $site_api = new SiteAPI();
        $site_api->querySSLCertificateStatus();
        break;
        
    case 'setfdl':
        require_once __DIR__ . '/site/site_api.php';
        $enable = isset($_POST['enable']) && $_POST['enable'] == 'true' ? 'true' : 'false';
        $domains = daddslashes($_POST['domains']);
        $exts = daddslashes($_POST['exts']);
        $return_rule = isset($_POST['return_rule']) ? daddslashes($_POST['return_rule']) : '404';
        $http_status = isset($_POST['http_status']) && $_POST['http_status'] == 'true' ? 'true' : 'false';
        
        $site_api = new SiteAPI();
        $site_api->setHotlink($enable, $domains, $exts, $return_rule, $http_status);
        break;
        
    case 'getfdl':
        require_once __DIR__ . '/site/site_api.php';
        $site_api = new SiteAPI();
        $site_api->getHotlinkStatus();
        break;
        
    case 'gettrafficlimitstatus':
        $site_api = new SiteAPI();
        $site_api->getTrafficLimitStatus();
        break;
        
    case 'settrafficlimit':
        $limit = intval($_POST['limit']);
        $enable = isset($_POST['enable']) ? 'true' : 'false';
        
        $site_api = new SiteAPI();
        $site_api->setTrafficLimit($limit, $enable);
        break;
        
    // 文件相关
    case 'getfiles':
        $dir = daddslashes($_POST['dir']);
        
        $file_api = new FileAPI();
        $file_api->getFiles($dir);
        break;
        
    case 'createfolder':
        $dir = daddslashes($_POST['dir']);
        $name = daddslashes($_POST['name']);
        
        $file_api = new FileAPI();
        $file_api->createFolder($dir, $name);
        break;
        
    case 'createfile':
        $dir = daddslashes($_POST['dir']);
        $name = daddslashes($_POST['name']);
        $content = $_POST['content'];
        
        $file_api = new FileAPI();
        $file_api->createFile($dir, $name, $content);
        break;

    case 'upload':
        $path = isset($_POST['path']) ? daddslashes($_POST['path']) : '/';
        $file_api = new FileAPI();
        $file_api->uploadFiles($path, $_FILES);
        break;
        
    case 'uploadfile':
        $dir = daddslashes($_POST['dir']);
        
        $file_api = new FileAPI();
        $file_api->uploadFile($dir);
        break;
    
    case 'uploadchunk':
        $dir = daddslashes($_POST['dir']);
        
        $file_api = new FileAPI();
        $file_api->uploadChunk($dir);
        break;
    
    case 'checkchunk':
        $file_api = new FileAPI();
        $file_api->checkChunkExists();
        break;
        
    case 'getfilecontent':
        $path = daddslashes($_POST['path']);
        
        $file_api = new FileAPI();
        $file_api->getFileContent($path);
        break;
        
    case 'savefile':
        $path = daddslashes($_POST['path']);
        $content = $_POST['content'];
        
        $file_api = new FileAPI();
        $file_api->saveFile($path, $content);
        break;
        
    case 'renamefile':
        $path = daddslashes($_POST['path']);
        $newName = daddslashes($_POST['newName']);
        
        $file_api = new FileAPI();
        $file_api->renameFile($path, $newName);
        break;
        
    case 'deletefile':
        $path = daddslashes($_POST['path']);
        
        $file_api = new FileAPI();
        $file_api->deleteFile($path);
        break;
        
    case 'deletefiles':
        $files = json_decode($_POST['files'], true);
        
        $file_api = new FileAPI();
        $file_api->deleteFiles($files);
        break;
        
    case 'downloadfile':
        if (ob_get_level()) {
            ob_end_clean();
        }
        $path = daddslashes($_GET['path']);
        
        $file_api = new FileAPI();
        $file_api->downloadFile($path);
        break;
        
    case 'copyfile':
        $source = daddslashes($_POST['source']);
        $target = daddslashes($_POST['target']);
        
        $file_api = new FileAPI();
        $file_api->copyFile($source, $target);
        break;
        
    case 'movefile':
        $source = daddslashes($_POST['source']);
        $target = daddslashes($_POST['target']);
        
        $file_api = new FileAPI();
        $file_api->moveFile($source, $target);
        break;
        
    case 'chmodfile':
        $path = daddslashes($_POST['path']);
        $mode = daddslashes($_POST['mode']);
        $owner = isset($_POST['owner']) ? daddslashes($_POST['owner']) : 'www';
        $recursive = isset($_POST['recursive']) ? intval($_POST['recursive']) : 0;
        
        $file_api = new FileAPI();
        $file_api->chmodFile($path, $mode, $owner, $recursive);
        break;
        
    case 'downloadurl':
        $urls = json_decode($_POST['urls'], true);
        $path = daddslashes($_POST['path']);
        $filename = isset($_POST['filename']) ? daddslashes($_POST['filename']) : '';
        
        $file_api = new FileAPI();
        $file_api->downloadFromUrl($urls, $path, $filename);
        break;
        
    case 'zip':
        $dir = daddslashes($_POST['dir']);
        $files = json_decode($_POST['files'], true);
        $zipname = isset($_POST['zipname']) ? daddslashes($_POST['zipname']) : '';
        
        $file_api = new FileAPI();
        $file_api->zipFiles($dir, $files, $zipname);
        break;
        
    case 'unzip':
        $dir = isset($_POST['dir']) ? daddslashes($_POST['dir']) : '/';
        $file = isset($_POST['file']) ? daddslashes($_POST['file']) : '';
        $target_dir = isset($_POST['target_dir']) ? daddslashes($_POST['target_dir']) : '';

        // 如果dir为空，默认为根目录
        if (empty($dir)) {
            $dir = '/';
        }

        // 如果没有指定目标目录，则使用源文件所在目录
        if (empty($target_dir)) {
            $target_dir = $dir;
        }

        $file_api = new FileAPI();
        $file_api->unzipFile($dir, $file, $target_dir);
        break;

    case 'getdirsize':
        $dir = isset($_POST['dir']) ? daddslashes($_POST['dir']) : '/';
        if (empty($dir)) {
            $dir = '/';
        }
        $file_api = new FileAPI();
        $file_api->getDirSize($dir);
        break;

    case 'importsql':
        $path = daddslashes($_POST['path']);
        $db_name = daddslashes($_POST['db_name']);
        
        $file_api = new FileAPI();
        $file_api->importSql($path, $db_name);
        break;
    
    case 'getdatabaselist':
        $file_api = new FileAPI();
        $file_api->getDatabaseList();
        break;
        
    case 'remotedownload':
        $url = daddslashes($_POST['url']);
        $path = daddslashes($_POST['path']);
        
        $file_api = new FileAPI();
        $file_api->remoteDownload($url, $path);
        break;
        
    case 'searchfiles':
        $path = daddslashes($_POST['path']);
        $keyword = daddslashes($_POST['keyword']);
        $content = isset($_POST['content']) && $_POST['content'] == '1';
        
        $file_api = new FileAPI();
        if ($content) {
            $file_api->searchFileContent($path, $keyword);
        } else {
            $file_api->searchFiles($path, $keyword);
        }
        break;
    
    case 'saveremark':
        $path = daddslashes($_POST['path']);
        $remark = isset($_POST['remark']) ? $_POST['remark'] : '';
        
        $file_api = new FileAPI();
        $file_api->saveRemark($path, $remark);
        break;
    
    case 'getrecyclebinlist':
        $file_api = new FileAPI();
        $file_api->getRecycleBinList();
        break;
    
    case 'restorerecyclebin':
        $recycle_name = daddslashes($_POST['recycle_name']);
        $file_api = new FileAPI();
        $file_api->restoreFromRecycleBin($recycle_name);
        break;
    
    case 'emptyrecyclebin':
        $file_api = new FileAPI();
        $file_api->emptyRecycleBin();
        break;
    
    case 'getpathsize':
        $path = daddslashes($_POST['path']);
        $file_api = new FileAPI();
        $file_api->getPathSize($path);
        break;
    
    case 'getfileattribute':
        $path = daddslashes($_POST['path']);
        $file_api = new FileAPI();
        $file_api->getFileAttribute($path);
        break;
    
    case 'getfilehash':
        $path = daddslashes($_POST['path']);
        $file_api = new FileAPI();
        $file_api->getFileHash($path);
        break;
    
    case 'createdownloadurl':
        $path = daddslashes($_POST['path']);
        $ps = isset($_POST['ps']) ? daddslashes($_POST['ps']) : '';
        $expire = isset($_POST['expire']) ? intval($_POST['expire']) : 24;
        $file_api = new FileAPI();
        $file_api->createDownloadUrl($path, $ps, $expire);
        break;
    
    case 'zipanddownload':
        $dir = daddslashes($_POST['dir']);
        $files = json_decode($_POST['files'], true);
        $file_api = new FileAPI();
        $file_api->zipAndDownload($dir, $files);
        break;
        
    case 'createlink':
        $path = daddslashes($_POST['path']);
        $link_name = daddslashes($_POST['link_name']);
        $type = daddslashes($_POST['type']);
        
        $file_api = new FileAPI();
        $file_api->createLink($path, $link_name, $type);
        break;
        
    case 'batchrename':
        $files = json_decode($_POST['files'], true);
        
        $file_api = new FileAPI();
        $file_api->batchRename($files);
        break;
        
    case 'getdirectory':
        $path = daddslashes($_POST['path']);
        $file_api = new FileAPI();
        $file_api->getFiles($path);
        break;
    
    case 'getdirectorylist':
        $path = daddslashes($_POST['path']);
        $file_api = new FileAPI();
        $file_api->getDirectories($path);
        break;
    
    case 'getrewriterules':
        $file_api = new FileAPI();
        $file_api->getRewriteRules();
        break;
        
    case 'getrewritecontent':
        $name = daddslashes($_POST['name']);
        $file_api = new FileAPI();
        $file_api->getRewriteContent($name);
        break;
        
    case 'getcurrentrewrite':
        $file_api = new FileAPI();
        $file_api->getCurrentRewrite();
        break;
    
    // 子目录伪静态相关
    case 'getsubdirrewrite':
        $domain = daddslashes($_POST['domain']);
        $path = daddslashes($_POST['path']);
        $domain_api = new DomainAPI();
        $domain_api->getSubdirRewrite($domain, $path);
        break;
        
    case 'setsubdirrewrite':
        $id = isset($_POST['id']) ? daddslashes($_POST['id']) : '';
        $domain = isset($_POST['domain']) ? daddslashes($_POST['domain']) : '';
        $path = isset($_POST['path']) ? daddslashes($_POST['path']) : '';
        $content = isset($_POST['content']) ? $_POST['content'] : '';
        $domain_api = new DomainAPI();
        $domain_api->setSubdirRewrite($id, $domain, $path, $content);
        break;

    // 备份相关
    case 'getbackups':
        $backup_api = new BackupAPI();
        $backup_api->getBackups();
        break;

    case 'createbackup':
        $backup_api = new BackupAPI();
        $backup_api->createBackup();
        break;

    case 'downloadbackup':
        $id = isset($_GET['id']) ? daddslashes($_GET['id']) : '';
        $backup_api = new BackupAPI();
        $backup_api->downloadBackup($id);
        break;

    case 'deletebackup':
        $id = daddslashes($_POST['id']);
        $backup_api = new BackupAPI();
        $backup_api->deleteBackup($id);
        break;

    case 'restorebackup':
        $id = daddslashes($_POST['id']);
        $backup_api = new BackupAPI();
        $backup_api->restoreBackup($id);
        break;

    // 计划任务相关
    case 'getcrontasks':
        $cron_api = new CronAPI();
        $cron_api->getCronTasks();
        break;

    case 'addcrontask':
        $cron_api = new CronAPI();
        $cron_api->addCronTask();
        break;

    case 'togglecrontask':
        $cron_api = new CronAPI();
        $cron_api->toggleCronTask();
        break;

    case 'deletecrontask':
        $cron_api = new CronAPI();
        $cron_api->deleteCronTask();
        break;

    // 流量统计
    case 'gettrafficstats':
        $traffic_api = new TrafficAPI();
        $traffic_api->getTrafficStats();
        break;
    
    // 流量统计详情
    case 'getdetailedstats':
        $traffic_api = new TrafficAPI();
        $traffic_api->getDetailedStats();
        break;
    
    // 流量趋势
    case 'gettraffictrend':
        $traffic_api = new TrafficAPI();
        $traffic_api->getTrafficTrend();
        break;
    
    // 实时访问数据
    case 'getrealtimedata':
        $traffic_api = new TrafficAPI();
        $traffic_api->getRealtimeData();
        break;
    
    // 网站配置信息
    case 'getsiteconfig':
        $traffic_api = new TrafficAPI();
        $traffic_api->getSiteConfig();
        break;
        
    // 通知相关
    case 'getnotifications':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '请先登录'));
            exit;
        }
        
        // 获取用户ID
        $user_id = $user['id'];
        
        // 获取可选的分类参数
        $category = isset($_POST['category']) ? daddslashes($_POST['category']) : '';
        
        // 构建查询条件
        $where = "(user_id=0 OR user_id={$user_id}) AND type='announcement'";
        if (!empty($category)) {
            $where .= " AND category='{$category}'";
        }
        
        // 获取通知
        $notifications = $DB->query("SELECT * FROM `notifications` WHERE {$where} ORDER BY create_time DESC LIMIT 50");
        $notification_list = array();
        while ($notif = $DB->fetch($notifications)) {
            $status = $notif['is_read'] == 0 ? 'unread' : 'read';
            // 分类映射
            $category_map = array(
                'general' => '通用',
                'maintenance' => '维护',
                'update' => '更新',
                'important' => '重要',
                'activity' => '活动'
            );
            $category_display = isset($category_map[$notif['category']]) ? $category_map[$notif['category']] : $notif['category'];
            $notification_list[] = array(
                'id' => $notif['id'],
                'title' => $notif['title'],
                'content' => $notif['content'],
                'category' => $notif['category'],
                'category_display' => $category_display,
                'type' => '公告',
                'status' => $status,
                'created_at' => $notif['create_time']
            );
        }
        
        echo json_encode(array('code' => 'success', 'notifications' => $notification_list));
        exit;
        break;
        
    case 'marknotificationread':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '请先登录'));
            exit;
        }
        
        $id = intval($_POST['id']);
        $DB->query("UPDATE `notifications` SET is_read=1 WHERE id={$id}");
        echo json_encode(array('code' => 'success'));
        exit;
        break;
        
    case 'markallnotificationsread':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '请先登录'));
            exit;
        }
        
        // 获取用户ID
        $user_id = $user['id'];
        
        $DB->query("UPDATE `notifications` SET is_read=1 WHERE (user_id=0 OR user_id={$user_id}) AND type='announcement'");
        echo json_encode(array('code' => 'success'));
        exit;
        break;
        
    case 'deletenotification':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '请先登录'));
            exit;
        }
        
        $id = intval($_POST['id']);
        $DB->query("DELETE FROM `notifications` WHERE id={$id}");
        echo json_encode(array('code' => 'success'));
        exit;
        break;
        
    // 订单相关
    case 'getorders':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '请先登录'));
            exit;
        }
        
        // 获取用户ID
        $user_id = $user['id'];
        
        // 获取筛选参数
        $status = isset($_POST['status']) ? daddslashes($_POST['status']) : '';
        $payment_method = isset($_POST['payment_method']) ? daddslashes($_POST['payment_method']) : '';
        $order_no = isset($_POST['order_no']) ? daddslashes($_POST['order_no']) : '';
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $page_size = isset($_POST['page_size']) ? intval($_POST['page_size']) : 10;
        $offset = ($page - 1) * $page_size;
        
        // 状态映射
        $status_map = array(
            'pending' => '待支付',
            'paid' => '已支付',
            'failed' => '支付失败',
            'cancelled' => '已取消'
        );
        
        $orders = array();
        $total = 0;
        
        // 查询 balance_orders 表（充值记录）
        $balance_orders_exists = $DB->query("SHOW TABLES LIKE 'balance_orders'");
        if ($balance_orders_exists && $DB->num_rows($balance_orders_exists) > 0) {
            $where = "uid={$user_id}";
            // balance_orders 表中存储的是英文状态码，直接使用前端传来的值
            if (!empty($status)) {
                $where .= " AND status='{$status}'";
            }
            if (!empty($order_no)) {
                $where .= " AND order_no LIKE '%{$order_no}%'";
            }
            if (!empty($payment_method)) {
                $where .= " AND payment_method='{$payment_method}'";
            }
            
            $count_result = $DB->query("SELECT COUNT(*) as total FROM `balance_orders` WHERE {$where}");
            $count_row = $DB->fetch($count_result);
            $total += $count_row ? intval($count_row['total']) : 0;
            
            $result = $DB->query("SELECT * FROM `balance_orders` WHERE {$where} ORDER BY create_time DESC");
            while ($row = $DB->fetch($result)) {
                $orders[] = array(
                    'order_no' => $row['order_no'],
                    'amount' => $row['amount'],
                    'payment_method' => $row['payment_method'],
                    'status' => $row['status'],
                    'create_time' => $row['create_time'],
                    'payment_time' => $row['pay_time'],
                    'order_type' => 'recharge'
                );
            }
        }
        
        // 查询 orders 表（普通订单）
        $orders_table_exists = $DB->query("SHOW TABLES LIKE 'orders'");
        if ($orders_table_exists && $DB->num_rows($orders_table_exists) > 0) {
            $where = "user_id={$user_id}";
            if (!empty($status)) {
                // orders 表可能存储中文或英文状态，尝试匹配
                $where .= " AND (status='{$status}' OR status='{$status_map[$status]}')";
            }
            if (!empty($order_no)) {
                $where .= " AND order_no LIKE '%{$order_no}%'";
            }
            if (!empty($payment_method)) {
                $where .= " AND payment_method='{$payment_method}'";
            }
            
            $count_result = $DB->query("SELECT COUNT(*) as total FROM `orders` WHERE {$where}");
            $count_row = $DB->fetch($count_result);
            $total += $count_row ? intval($count_row['total']) : 0;
            
            $result = $DB->query("SELECT * FROM `orders` WHERE {$where} ORDER BY create_time DESC");
            while ($row = $DB->fetch($result)) {
                $frontend_status = $row['status'];
                // 转换中文状态为英文
                if ($row['status'] == '待支付') $frontend_status = 'pending';
                elseif ($row['status'] == '已支付') $frontend_status = 'paid';
                elseif ($row['status'] == '支付失败') $frontend_status = 'failed';
                elseif ($row['status'] == '已取消') $frontend_status = 'cancelled';
                
                $orders[] = array(
                    'order_no' => $row['order_no'],
                    'amount' => $row['amount'],
                    'payment_method' => $row['payment_method'],
                    'status' => $frontend_status,
                    'create_time' => $row['create_time'],
                    'payment_time' => $row['payment_time'],
                    'order_type' => 'order'
                );
            }
        }
        
        // 查询 dd 表（旧订单表）
        $dd_table_exists = $DB->query("SHOW TABLES LIKE 'dd'");
        if ($dd_table_exists && $DB->num_rows($dd_table_exists) > 0) {
            $where = "uid={$user_id}";
            if (!empty($status) && isset($status_map[$status])) {
                $db_status = $status_map[$status];
                $where .= " AND zt='{$db_status}'";
            }
            if (!empty($order_no)) {
                $where .= " AND ddh LIKE '%{$order_no}%'";
            }
            
            $count_result = $DB->query("SELECT COUNT(*) as total FROM `dd` WHERE {$where}");
            $count_row = $DB->fetch($count_result);
            $total += $count_row ? intval($count_row['total']) : 0;
            
            $result = $DB->query("SELECT * FROM `dd` WHERE {$where} ORDER BY time DESC");
            while ($row = $DB->fetch($result)) {
                $frontend_status = 'pending';
                if ($row['zt'] == '已支付') $frontend_status = 'paid';
                elseif ($row['zt'] == '支付失败') $frontend_status = 'failed';
                elseif ($row['zt'] == '已取消') $frontend_status = 'cancelled';
                
                $orders[] = array(
                    'order_no' => $row['ddh'],
                    'amount' => $row['je'],
                    'payment_method' => '',
                    'status' => $frontend_status,
                    'create_time' => $row['time'],
                    'payment_time' => '',
                    'order_type' => 'dd'
                );
            }
        }
        
        // 按创建时间排序（倒序）
        usort($orders, function($a, $b) {
            return strtotime($b['create_time']) - strtotime($a['create_time']);
        });
        
        // 分页处理
        $orders = array_slice($orders, $offset, $page_size);
        
        // 检查是否有待支付订单
        $has_pending = false;
        foreach ($orders as $order) {
            if ($order['status'] === 'pending') {
                $has_pending = true;
                break;
            }
        }
        
        echo json_encode(array('code' => 'success', 'orders' => $orders, 'total' => $total, 'has_pending' => $has_pending));
        exit;
        break;
        
    // 清空待支付订单
    case 'clearpendingorders':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '请先登录'));
            exit;
        }
        
        $user_id = $user['id'];
        $deleted_count = 0;
        
        // 优先清空 balance_orders 表中的待支付订单
        $balance_orders_exists = $DB->query("SHOW TABLES LIKE 'balance_orders'");
        if ($balance_orders_exists && $DB->num_rows($balance_orders_exists) > 0) {
            // 先查询待支付订单数量
            $count_result = $DB->query("SELECT COUNT(*) as total FROM `balance_orders` WHERE uid={$user_id} AND status='pending'");
            $count_row = $DB->fetch($count_result);
            $pending_count = $count_row ? intval($count_row['total']) : 0;
            
            if ($pending_count > 0) {
                // 删除待支付订单
                $DB->query("DELETE FROM `balance_orders` WHERE uid={$user_id} AND status='pending'");
                $deleted_count = $pending_count;
            }
        }
        
        // 如果 balance_orders 表没有数据或没有删除记录，尝试 orders 表
        if ($deleted_count == 0) {
            $orders_table_exists = $DB->query("SHOW TABLES LIKE 'orders'");
            if ($orders_table_exists && $DB->num_rows($orders_table_exists) > 0) {
                // 查询待支付订单数量
                $count_result = $DB->query("SELECT COUNT(*) as total FROM `orders` WHERE user_id={$user_id} AND status='待支付'");
                $count_row = $DB->fetch($count_result);
                $pending_count = $count_row ? intval($count_row['total']) : 0;
                
                if ($pending_count > 0) {
                    // 删除待支付订单
                    $DB->query("DELETE FROM `orders` WHERE user_id={$user_id} AND status='待支付'");
                    $deleted_count = $pending_count;
                }
            }
        }
        
        // 如果还是没有删除记录，尝试 dd 表
        if ($deleted_count == 0) {
            $dd_table_exists = $DB->query("SHOW TABLES LIKE 'dd'");
            if ($dd_table_exists && $DB->num_rows($dd_table_exists) > 0) {
                // 查询待支付订单数量
                $count_result = $DB->query("SELECT COUNT(*) as total FROM `dd` WHERE uid={$user_id} AND zt='待支付'");
                $count_row = $DB->fetch($count_result);
                $pending_count = $count_row ? intval($count_row['total']) : 0;
                
                if ($pending_count > 0) {
                    // 删除待支付订单
                    $DB->query("DELETE FROM `dd` WHERE uid={$user_id} AND zt='待支付'");
                    $deleted_count = $pending_count;
                }
            }
        }
        
        echo json_encode(array('code' => 'success', 'msg' => '已清空待支付订单', 'count' => $deleted_count));
        exit;
        break;
    
    // 测试URL是否可以访问
    case 'test_url':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '请先登录'));
            exit;
        }
        
        $url = isset($_POST['url']) ? trim($_POST['url']) : '';
        if (empty($url)) {
            echo json_encode(array('code' => 'error', 'msg' => '请输入URL地址'));
            exit;
        }
        
        // 验证URL格式
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            echo json_encode(array('code' => 'error', 'msg' => 'URL格式不正确'));
            exit;
        }
        
        // 使用cURL测试URL是否可以访问
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_NOBODY, true); // 只获取header，不获取body
        curl_setopt($ch, CURLOPT_HEADER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        // HTTP状态码 200-399 认为是可访问的
        if ($response !== false && $httpCode >= 200 && $httpCode < 400) {
            echo json_encode(array('code' => 'success', 'status' => true, 'msg' => 'URL可以访问', 'http_code' => $httpCode));
        } else {
            echo json_encode(array('code' => 'error', 'status' => false, 'msg' => 'URL无法访问', 'http_code' => $httpCode, 'error' => $error));
        }
        exit;
        break;
    
    // 操作日志相关
    case 'getlogs':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '请先登录'));
            exit;
        }
        
        // 获取筛选参数
        $startDate = isset($_POST['startDate']) ? daddslashes($_POST['startDate']) : '';
        $endDate = isset($_POST['endDate']) ? daddslashes($_POST['endDate']) : '';
        $logType = isset($_POST['logType']) ? daddslashes($_POST['logType']) : '';
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $pageSize = isset($_POST['pageSize']) ? intval($_POST['pageSize']) : 20;
        $offset = ($page - 1) * $pageSize;
        
        // 构建查询条件
        $where = "WHERE `user` = '" . $DB->escape($user['user']) . "'";
        if ($startDate) {
            $where .= " AND date >= '$startDate'";
        }
        if ($endDate) {
            $where .= " AND date <= '$endDate'";
        }
        if ($logType) {
            $where .= " AND lx = '$logType'";
        }
        
        // 获取总记录数
        $total_result = $DB->query("SELECT COUNT(*) as total FROM log $where");
        $total_row = $DB->fetch($total_result);
        $total = $total_row['total'];
        $totalPages = ceil($total / $pageSize);
        
        // 查询日志列表
        $sql = "SELECT * FROM log $where ORDER BY date DESC LIMIT $offset, $pageSize";
        $result = $DB->query($sql);
        
        $logs = [];
        while ($row = $DB->fetch($result)) {
            $logs[] = array(
                'date' => $row['date'],
                'type' => $row['lx'],
                'content' => formatLogContent($row['lr'], $user['user']),
                'ip' => $row['ip']
            );
        }
        
        echo json_encode(array(
            'code' => 'success',
            'logs' => $logs,
            'total' => $total,
            'totalPages' => $totalPages,
            'currentPage' => $page
        ));
        exit;
        break;
    
    case 'clearlogs':
        $user = check_user();
        if (!$user) {
            echo json_encode(array('code' => 'error', 'msg' => '请先登录'));
            exit;
        }
        
        $result = $DB->query("DELETE FROM log WHERE `user` = '" . $DB->escape($user['user']) . "'");
        if ($result !== false) {
            echo json_encode(array('code' => 'success', 'msg' => '清空成功'));
        } else {
            echo json_encode(array('code' => 'error', 'msg' => '清空失败'));
        }
        exit;
        break;
    
    // 余额相关
    case 'get_balance':
        require_once __DIR__ . '/balance_api.php';
        $balance_api = new BalanceAPI();
        $balance_api->getBalance();
        break;
    
    case 'recharge':
        require_once __DIR__ . '/balance_api.php';
        $balance_api = new BalanceAPI();
        $balance_api->recharge();
        break;
    
    case 'get_history':
        require_once __DIR__ . '/balance_api.php';
        $balance_api = new BalanceAPI();
        $balance_api->getRechargeHistory();
        break;
    
    // 语言切换
    case 'changelanguage':
        $lang_code = isset($_POST['lang']) ? $_POST['lang'] : (isset($_GET['lang']) ? $_GET['lang'] : '');
        
        if (empty($lang_code)) {
            echo json_encode(array('code' => 'error', 'msg' => '语言参数不能为空'));
            exit;
        }
        
        $allowed_langs = array('zh_CN', 'en_US');
        if (!in_array($lang_code, $allowed_langs)) {
            echo json_encode(array('code' => 'error', 'msg' => '不支持的语言'));
            exit;
        }
        
        // 设置 Session 和 Cookie
        $_SESSION['lang'] = $lang_code;
        setcookie('lang', $lang_code, time() + 86400 * 30, '/');
        
        echo json_encode(array('code' => 'success', 'msg' => '语言切换成功'));
        exit;
        break;
        
    default:
        echo json_encode(array('status' => false, 'code' => '功能代码错误', 'msg' => '功能代码错误'));
        exit;
}
?>
