<?php
$base_dir = '/home/pan'; // 素材存放路径

// 为了在Windows环境下也能测试，添加回退路径
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    $base_dir = 'C:/home/pan';
    if (!is_dir($base_dir)) {
        @mkdir($base_dir, 0777, true);
    }
}

// 确保基础目录存在
if (!file_exists($base_dir)) {
    die("素材目录 '{$base_dir}' 不存在，请确保该路径已创建并拥有权限。");
}

// 辅助函数：过滤路径，防止目录遍历攻击
function getValidPath($dir, $base) {
    $real_base = realpath($base);
    $path = $base . DIRECTORY_SEPARATOR . $dir;
    $real_path = realpath($path);
    
    if ($real_path && strpos($real_path, $real_base) === 0) {
        return $real_path;
    }
    return $real_base;
}

// 获取文件扩展名
function getFileExt($filename) {
    return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
}

// 获取文件图标
function getFileIcon($ext) {
    $icons = [
        'video' => 'bi-film',
        'image' => 'bi-image',
        'audio' => 'bi-music-note-beamed',
        'archive' => 'bi-file-zip',
        'document' => 'bi-file-text',
        'code' => 'bi-code-slash',
        'executable' => 'bi-gear',
        'other' => 'bi-file-earmark'
    ];
    
    $video_exts = ['mp4', 'webm', 'ogg', 'mkv', 'avi', 'mov', 'flv', 'wmv'];
    $image_exts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'ico'];
    $audio_exts = ['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma', 'm4a'];
    $archive_exts = ['zip', 'rar', '7z', 'tar', 'gz', 'bz2'];
    $doc_exts = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'];
    $code_exts = ['php', 'js', 'css', 'html', 'py', 'java', 'cpp', 'c', 'h'];
    $exec_exts = ['exe', 'msi', 'dmg', 'pkg', 'deb', 'rpm'];
    
    if (in_array($ext, $video_exts)) return ['icon' => $icons['video'], 'type' => 'video', 'color' => '#e74c3c'];
    if (in_array($ext, $image_exts)) return ['icon' => $icons['image'], 'type' => 'image', 'color' => '#3498db'];
    if (in_array($ext, $audio_exts)) return ['icon' => $icons['audio'], 'type' => 'audio', 'color' => '#9b59b6'];
    if (in_array($ext, $archive_exts)) return ['icon' => $icons['archive'], 'type' => 'archive', 'color' => '#f39c12'];
    if (in_array($ext, $doc_exts)) return ['icon' => $icons['document'], 'type' => 'document', 'color' => '#1abc9c'];
    if (in_array($ext, $code_exts)) return ['icon' => $icons['code'], 'type' => 'code', 'color' => '#34495e'];
    if (in_array($ext, $exec_exts)) return ['icon' => $icons['executable'], 'type' => 'executable', 'color' => '#e67e22'];
    
    return ['icon' => $icons['other'], 'type' => 'other', 'color' => '#95a5a6'];
}

// 格式化文件大小
function formatSize($size) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $unitIndex = 0;
    while ($size >= 1024 && $unitIndex < count($units) - 1) {
        $size /= 1024;
        $unitIndex++;
    }
    return round($size, 2) . ' ' . $units[$unitIndex];
}

$current_dir_param = isset($_GET['dir']) ? $_GET['dir'] : '';
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';
$filter_type = isset($_GET['type']) ? $_GET['type'] : 'all';
$current_path = getValidPath($current_dir_param, $base_dir);

// 处理文件流（下载或预览）
if (isset($_GET['action']) && isset($_GET['file'])) {
    $file = getValidPath($_GET['file'], $base_dir);
    if ($file && is_file($file)) {
        $mime_type = 'application/octet-stream';
        if (function_exists('mime_content_type')) {
            $mime_type = @mime_content_type($file) ?: $mime_type;
        } else {
            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            $mimes = [
                'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
                'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp',
                'mp4' => 'video/mp4', 'webm' => 'video/webm', 'ogg' => 'video/ogg',
                'mkv' => 'video/x-matroska', 'avi' => 'video/x-msvideo', 'mov' => 'video/quicktime',
                'mp3' => 'audio/mpeg', 'wav' => 'audio/wav', 'pdf' => 'application/pdf'
            ];
            if (isset($mimes[$ext])) $mime_type = $mimes[$ext];
        }
        
        if ($_GET['action'] == 'download') {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($file).'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            readfile($file);
            exit;
        } elseif ($_GET['action'] == 'stream') {
            $fp = @fopen($file, 'rb');
            $size = filesize($file);
            $length = $size;
            $start = 0;
            $end = $size - 1;
            
            header("Content-Type: $mime_type");
            header("Accept-Ranges: bytes");
            
            if (isset($_SERVER['HTTP_RANGE'])) {
                $c_start = $start;
                $c_end = $end;
                list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
                if (strpos($range, ',') !== false) {
                    header('HTTP/1.1 416 Requested Range Not Satisfiable');
                    header("Content-Range: bytes $start-$end/$size");
                    exit;
                }
                if ($range == '-') {
                    $c_start = $size - substr($range, 1);
                } else {
                    $range = explode('-', $range);
                    $c_start = $range[0];
                    $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
                }
                $c_end = ($c_end > $end) ? $end : $c_end;
                if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
                    header('HTTP/1.1 416 Requested Range Not Satisfiable');
                    header("Content-Range: bytes $start-$end/$size");
                    exit;
                }
                $start = $c_start;
                $end = $c_end;
                $length = $end - $start + 1;
                fseek($fp, $start);
                header('HTTP/1.1 206 Partial Content');
            }
            header("Content-Range: bytes $start-$end/$size");
            header("Content-Length: $length");
            
            $buffer = 1024 * 8;
            while (!feof($fp) && ($p = ftell($fp)) <= $end) {
                if ($p + $buffer > $end) {
                    $buffer = $end - $p + 1;
                }
                set_time_limit(0);
                echo fread($fp, $buffer);
                flush();
            }
            fclose($fp);
            exit;
        }
    }
}

// 处理批量下载
if (isset($_POST['action']) && $_POST['action'] == 'batch_download' && isset($_POST['files'])) {
    $files = json_decode($_POST['files'], true);
    if (!empty($files)) {
        $zip = new ZipArchive();
        $zip_name = 'download_' . time() . '.zip';
        $zip_path = sys_get_temp_dir() . '/' . $zip_name;
        
        if ($zip->open($zip_path, ZipArchive::CREATE) === TRUE) {
            foreach ($files as $file) {
                $file_path = getValidPath($file, $base_dir);
                if ($file_path && is_file($file_path)) {
                    $zip->addFile($file_path, basename($file_path));
                }
            }
            $zip->close();
            
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="' . $zip_name . '"');
            header('Content-Length: ' . filesize($zip_path));
            readfile($zip_path);
            unlink($zip_path);
            exit;
        }
    }
}

// 递归搜索文件
function searchFiles($dir, $query, $base_dir) {
    $results = [];
    $items = @scandir($dir);
    if (!$items) return $results;
    
    foreach ($items as $item) {
        if ($item == '.' || $item == '..') continue;
        
        $full_path = $dir . DIRECTORY_SEPARATOR . $item;
        $rel_path = ltrim(str_replace($base_dir, '', $full_path), DIRECTORY_SEPARATOR);
        $rel_path = str_replace('\\', '/', $rel_path);
        
        if (is_dir($full_path)) {
            $results = array_merge($results, searchFiles($full_path, $query, $base_dir));
        } else {
            if (stripos($item, $query) !== false) {
                $ext = getFileExt($item);
                $file_info = getFileIcon($ext);
                $results[] = [
                    'name' => $item,
                    'path' => $rel_path,
                    'full_path' => $full_path,
                    'size' => filesize($full_path),
                    'modified' => filemtime($full_path),
                    'ext' => $ext,
                    'type' => $file_info['type'],
                    'icon' => $file_info['icon'],
                    'color' => $file_info['color']
                ];
            }
        }
    }
    return $results;
}

// 读取当前目录
$items = @scandir($current_path);
if (!$items) $items = [];
$items = array_diff($items, array('.', '..'));

$folders = [];
$files = [];
$total_size = 0;

foreach ($items as $item) {
    $full_path = $current_path . DIRECTORY_SEPARATOR . $item;
    $rel_path = ltrim(str_replace($base_dir, '', $full_path), DIRECTORY_SEPARATOR);
    $rel_path = str_replace('\\', '/', $rel_path);
    
    if (is_dir($full_path)) {
        // 计算文件夹大小
        $folder_size = 0;
        $folder_files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($full_path));
        foreach ($folder_files as $file) {
            if ($file->isFile()) {
                $folder_size += $file->getSize();
            }
        }
        
        $folders[] = [
            'name' => $item,
            'path' => $rel_path,
            'size' => $folder_size,
            'modified' => filemtime($full_path)
        ];
    } else {
        $ext = getFileExt($item);
        $file_info = getFileIcon($ext);
        
        // 搜索过滤
        if ($search_query && stripos($item, $search_query) === false) continue;
        
        // 类型过滤
        if ($filter_type != 'all' && $file_info['type'] != $filter_type) continue;
        
        $file_size = filesize($full_path);
        $total_size += $file_size;
        
        $files[] = [
            'name' => $item,
            'path' => $rel_path,
            'full_path' => $full_path,
            'size' => $file_size,
            'modified' => filemtime($full_path),
            'ext' => $ext,
            'type' => $file_info['type'],
            'icon' => $file_info['icon'],
            'color' => $file_info['color']
        ];
    }
}

// 排序
$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'name';
$sort_order = isset($_GET['order']) ? $_GET['order'] : 'asc';

usort($folders, function($a, $b) use ($sort_by, $sort_order) {
    $cmp = strcasecmp($a[$sort_by], $b[$sort_by]);
    if ($sort_by == 'size' || $sort_by == 'modified') {
        $cmp = $a[$sort_by] - $b[$sort_by];
    }
    return $sort_order == 'desc' ? -$cmp : $cmp;
});

usort($files, function($a, $b) use ($sort_by, $sort_order) {
    $cmp = strcasecmp($a[$sort_by], $b[$sort_by]);
    if ($sort_by == 'size' || $sort_by == 'modified') {
        $cmp = $a[$sort_by] - $b[$sort_by];
    }
    return $sort_order == 'desc' ? -$cmp : $cmp;
});

// 统计信息
$stats = [
    'total_files' => count($files),
    'total_folders' => count($folders),
    'total_size' => $total_size
];

// 如果是搜索模式，递归搜索所有文件
$search_results = [];
if ($search_query) {
    $search_results = searchFiles($base_dir, $search_query, $base_dir);
    $stats['search_results'] = count($search_results);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>资源下载站 - 专业文件分享平台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #4a90d9;
            --secondary-color: #2c3e50;
            --accent-color: #e74c3c;
            --bg-color: #f5f7fa;
            --card-bg: #ffffff;
        }
        
        body { 
            background-color: var(--bg-color);
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .navbar {
            background: linear-gradient(135deg, var(--primary-color) 0%, #357abd 100%);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .navbar-brand {
            font-weight: 700;
            font-size: 1.5rem;
        }
        
        .search-box {
            background: rgba(255,255,255,0.15);
            border: 1px solid rgba(255,255,255,0.3);
            border-radius: 25px;
            padding: 8px 20px;
            color: white;
            width: 300px;
            transition: all 0.3s;
        }
        
        .search-box::placeholder {
            color: rgba(255,255,255,0.7);
        }
        
        .search-box:focus {
            background: rgba(255,255,255,0.25);
            outline: none;
            width: 350px;
        }
        
        .stats-bar {
            background: var(--card-bg);
            border-radius: 10px;
            padding: 15px 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .stat-item {
            text-align: center;
            padding: 0 20px;
            border-right: 1px solid #eee;
        }
        
        .stat-item:last-child {
            border-right: none;
        }
        
        .stat-number {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary-color);
        }
        
        .stat-label {
            font-size: 0.85rem;
            color: #666;
        }
        
        .breadcrumb {
            background: var(--card-bg);
            border-radius: 10px;
            padding: 15px 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .filter-bar {
            background: var(--card-bg);
            border-radius: 10px;
            padding: 15px 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .file-card {
            background: var(--card-bg);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            transition: all 0.3s;
            border: 2px solid transparent;
        }
        
        .file-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }
        
        .file-card.selected {
            border-color: var(--primary-color);
            background: #f0f7ff;
        }
        
        .file-icon {
            width: 50px;
            height: 50px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            margin-right: 15px;
        }
        
        .file-info h5 {
            font-size: 1rem;
            margin-bottom: 5px;
            color: var(--secondary-color);
        }
        
        .file-meta {
            font-size: 0.85rem;
            color: #888;
        }
        
        .file-actions .btn {
            padding: 8px 15px;
            border-radius: 8px;
            font-size: 0.9rem;
        }
        
        .folder-card {
            background: linear-gradient(135deg, #fff9e6 0%, #fff5d6 100%);
            border: 2px solid #f0e4c3;
        }
        
        .folder-icon {
            background: #f39c12;
            color: white;
        }
        
        .batch-actions {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            background: var(--card-bg);
            padding: 15px 30px;
            border-radius: 50px;
            box-shadow: 0 5px 30px rgba(0,0,0,0.2);
            z-index: 1000;
            display: none;
        }
        
        .batch-actions.show {
            display: flex;
            gap: 10px;
        }
        
        .type-filter {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .type-filter .btn {
            border-radius: 20px;
            padding: 6px 16px;
            font-size: 0.85rem;
        }
        
        .preview-modal .modal-content {
            border-radius: 15px;
            overflow: hidden;
        }
        
        .preview-modal .modal-header {
            background: var(--secondary-color);
            color: white;
        }
        
        .preview-content {
            background: #000;
            min-height: 400px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .preview-content img,
        .preview-content video {
            max-width: 100%;
            max-height: 70vh;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            color: #ddd;
        }
        
        .checkbox-wrapper {
            margin-right: 15px;
        }
        
        .checkbox-wrapper input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }
        
        @media (max-width: 768px) {
            .search-box {
                width: 200px;
            }
            .search-box:focus {
                width: 220px;
            }
            .stat-item {
                padding: 0 10px;
            }
        }
    </style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark sticky-top">
    <div class="container">
        <a class="navbar-brand" href="?dir=">
            <i class="bi bi-cloud-download me-2"></i>资源下载站
        </a>
        <form class="d-flex" method="get" action="">
            <input type="hidden" name="dir" value="<?= htmlspecialchars($current_dir_param) ?>">
            <input type="text" name="search" class="search-box" placeholder="搜索文件..." 
                   value="<?= htmlspecialchars($search_query) ?>">
        </form>
    </div>
</nav>

<div class="container mt-4 mb-5">
    <!-- 统计信息 -->
    <div class="stats-bar d-flex justify-content-center flex-wrap">
        <div class="stat-item">
            <div class="stat-number"><?= number_format($stats['total_folders']) ?></div>
            <div class="stat-label">文件夹</div>
        </div>
        <div class="stat-item">
            <div class="stat-number"><?= number_format($stats['total_files']) ?></div>
            <div class="stat-label">文件</div>
        </div>
        <div class="stat-item">
            <div class="stat-number"><?= formatSize($stats['total_size']) ?></div>
            <div class="stat-label">总大小</div>
        </div>
        <?php if ($search_query): ?>
        <div class="stat-item">
            <div class="stat-number"><?= number_format($stats['search_results']) ?></div>
            <div class="stat-label">搜索结果</div>
        </div>
        <?php endif; ?>
    </div>

    <!-- 面包屑导航 -->
    <?php if (!$search_query): ?>
    <nav aria-label="breadcrumb" class="mb-3">
        <ol class="breadcrumb mb-0">
            <li class="breadcrumb-item">
                <a href="?dir=" class="text-decoration-none"><i class="bi bi-house-door"></i> 首页</a>
            </li>
            <?php
            $parts = explode('/', str_replace('\\', '/', $current_dir_param));
            $accumulated = '';
            foreach ($parts as $part) {
                if (empty($part)) continue;
                $accumulated .= ($accumulated ? '/' : '') . $part;
                echo '<li class="breadcrumb-item">
                    <a href="?dir=' . urlencode($accumulated) . '" class="text-decoration-none">' . htmlspecialchars($part) . '</a>
                </li>';
            }
            ?>
        </ol>
    </nav>
    <?php endif; ?>

    <!-- 筛选栏 -->
    <?php if (!$search_query): ?>
    <div class="filter-bar">
        <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
            <div class="type-filter">
                <a href="?dir=<?= urlencode($current_dir_param) ?>&type=all" 
                   class="btn btn-sm <?= $filter_type == 'all' ? 'btn-primary' : 'btn-outline-secondary' ?>">全部</a>
                <a href="?dir=<?= urlencode($current_dir_param) ?>&type=video" 
                   class="btn btn-sm <?= $filter_type == 'video' ? 'btn-danger' : 'btn-outline-danger' ?>">
                   <i class="bi bi-film me-1"></i>视频</a>
                <a href="?dir=<?= urlencode($current_dir_param) ?>&type=image" 
                   class="btn btn-sm <?= $filter_type == 'image' ? 'btn-info' : 'btn-outline-info' ?>">
                   <i class="bi bi-image me-1"></i>图片</a>
                <a href="?dir=<?= urlencode($current_dir_param) ?>&type=audio" 
                   class="btn btn-sm <?= $filter_type == 'audio' ? 'btn-warning' : 'btn-outline-warning' ?>">
                   <i class="bi bi-music-note-beamed me-1"></i>音频</a>
                <a href="?dir=<?= urlencode($current_dir_param) ?>&type=archive" 
                   class="btn btn-sm <?= $filter_type == 'archive' ? 'btn-success' : 'btn-outline-success' ?>">
                   <i class="bi bi-file-zip me-1"></i>压缩包</a>
                <a href="?dir=<?= urlencode($current_dir_param) ?>&type=document" 
                   class="btn btn-sm <?= $filter_type == 'document' ? 'btn-secondary' : 'btn-outline-secondary' ?>">
                   <i class="bi bi-file-text me-1"></i>文档</a>
            </div>
            <div class="d-flex gap-2">
                <select class="form-select form-select-sm" onchange="location.href=this.value" style="width: auto;">
                    <option value="?dir=<?= urlencode($current_dir_param) ?>&sort=name&order=asc" <?= $sort_by=='name'&&$sort_order=='asc'?'selected':'' ?>>名称 ↑</option>
                    <option value="?dir=<?= urlencode($current_dir_param) ?>&sort=name&order=desc" <?= $sort_by=='name'&&$sort_order=='desc'?'selected':'' ?>>名称 ↓</option>
                    <option value="?dir=<?= urlencode($current_dir_param) ?>&sort=size&order=desc" <?= $sort_by=='size'&&$sort_order=='desc'?'selected':'' ?>>大小 ↓</option>
                    <option value="?dir=<?= urlencode($current_dir_param) ?>&sort=modified&order=desc" <?= $sort_by=='modified'&&$sort_order=='desc'?'selected':'' ?>>时间 ↓</option>
                </select>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- 文件列表 -->
    <?php if ($search_query): ?>
        <h5 class="mb-3"><i class="bi bi-search me-2"></i>搜索结果: "<?= htmlspecialchars($search_query) ?>"</h5>
        <?php if (empty($search_results)): ?>
            <div class="empty-state">
                <i class="bi bi-search"></i>
                <h4>未找到相关文件</h4>
                <p>请尝试其他关键词</p>
            </div>
        <?php else: ?>
            <?php foreach ($search_results as $file): ?>
            <div class="file-card" data-file="<?= htmlspecialchars($file['path']) ?>">
                <div class="d-flex align-items-center">
                    <div class="checkbox-wrapper">
                        <input type="checkbox" class="file-checkbox" value="<?= htmlspecialchars($file['path']) ?>">
                    </div>
                    <div class="file-icon" style="background: <?= $file['color'] ?>20; color: <?= $file['color'] ?>">
                        <i class="bi <?= $file['icon'] ?>"></i>
                    </div>
                    <div class="file-info flex-grow-1">
                        <h5 class="mb-1"><?= htmlspecialchars($file['name']) ?></h5>
                        <div class="file-meta">
                            <span class="me-3"><i class="bi bi-hdd me-1"></i><?= formatSize($file['size']) ?></span>
                            <span class="me-3"><i class="bi bi-calendar me-1"></i><?= date('Y-m-d H:i', $file['modified']) ?></span>
                            <span><i class="bi bi-folder me-1"></i><?= htmlspecialchars(dirname($file['path'])) ?></span>
                        </div>
                    </div>
                    <div class="file-actions">
                        <?php if (in_array($file['type'], ['image', 'video'])): ?>
                        <button class="btn btn-outline-primary btn-sm" onclick="openPreview('<?= urlencode($file['path']) ?>', '<?= $file['type'] ?>', '<?= htmlspecialchars($file['name'], ENT_QUOTES) ?>')">
                            <i class="bi bi-eye"></i> 预览
                        </button>
                        <?php endif; ?>
                        <a href="?action=download&file=<?= urlencode($file['path']) ?>" class="btn btn-primary btn-sm">
                            <i class="bi bi-download"></i> 下载
                        </a>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    <?php else: ?>
        <!-- 文件夹列表 -->
        <?php foreach ($folders as $folder): ?>
        <div class="file-card folder-card">
            <div class="d-flex align-items-center">
                <div class="file-icon folder-icon">
                    <i class="bi bi-folder-fill"></i>
                </div>
                <div class="file-info flex-grow-1">
                    <h5 class="mb-1"><?= htmlspecialchars($folder['name']) ?></h5>
                    <div class="file-meta">
                        <span class="me-3"><i class="bi bi-hdd me-1"></i><?= formatSize($folder['size']) ?></span>
                        <span><i class="bi bi-calendar me-1"></i><?= date('Y-m-d H:i', $folder['modified']) ?></span>
                    </div>
                </div>
                <div class="file-actions">
                    <a href="?dir=<?= urlencode($folder['path']) ?>" class="btn btn-warning btn-sm">
                        <i class="bi bi-folder2-open"></i> 打开
                    </a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <!-- 文件列表 -->
        <?php foreach ($files as $file): ?>
        <div class="file-card" data-file="<?= htmlspecialchars($file['path']) ?>">
            <div class="d-flex align-items-center">
                <div class="checkbox-wrapper">
                    <input type="checkbox" class="file-checkbox" value="<?= htmlspecialchars($file['path']) ?>">
                </div>
                <div class="file-icon" style="background: <?= $file['color'] ?>20; color: <?= $file['color'] ?>">
                    <i class="bi <?= $file['icon'] ?>"></i>
                </div>
                <div class="file-info flex-grow-1">
                    <h5 class="mb-1"><?= htmlspecialchars($file['name']) ?></h5>
                    <div class="file-meta">
                        <span class="me-3"><i class="bi bi-hdd me-1"></i><?= formatSize($file['size']) ?></span>
                        <span><i class="bi bi-calendar me-1"></i><?= date('Y-m-d H:i', $file['modified']) ?></span>
                    </div>
                </div>
                <div class="file-actions">
                    <?php if (in_array($file['type'], ['image', 'video'])): ?>
                    <button class="btn btn-outline-primary btn-sm me-2" onclick="openPreview('<?= urlencode($file['path']) ?>', '<?= $file['type'] ?>', '<?= htmlspecialchars($file['name'], ENT_QUOTES) ?>')">
                        <i class="bi bi-eye"></i> 预览
                    </button>
                    <?php endif; ?>
                    <a href="?action=download&file=<?= urlencode($file['path']) ?>" class="btn btn-primary btn-sm">
                        <i class="bi bi-download"></i> 下载
                    </a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <?php if (empty($folders) && empty($files)): ?>
            <div class="empty-state">
                <i class="bi bi-inbox"></i>
                <h4>该目录下没有文件</h4>
                <p>当前文件夹为空</p>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<!-- 批量操作栏 -->
<div class="batch-actions" id="batchActions">
    <span class="me-3">已选择 <strong id="selectedCount">0</strong> 个文件</span>
    <button class="btn btn-primary" onclick="batchDownload()">
        <i class="bi bi-download me-1"></i>批量下载
    </button>
    <button class="btn btn-outline-secondary" onclick="clearSelection()">
        <i class="bi bi-x-lg me-1"></i>取消
    </button>
</div>

<!-- 预览模态框 -->
<div class="modal fade preview-modal" id="previewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="previewTitle">预览</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="preview-content" id="previewContent">
                <!-- 媒体内容将通过JS注入 -->
            </div>
            <div class="modal-footer justify-content-center">
                <a href="#" class="btn btn-primary" id="previewDownload">
                    <i class="bi bi-download me-1"></i>下载文件
                </a>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- Toast 提示 -->
<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 9999">
    <div id="liveToast" class="toast align-items-center text-white bg-success border-0" role="alert">
        <div class="d-flex">
            <div class="toast-body" id="toastMessage">操作成功</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const previewModal = new bootstrap.Modal(document.getElementById('previewModal'));
    const toast = new bootstrap.Toast(document.getElementById('liveToast'));
    let selectedFiles = new Set();

    // 文件选择
    document.querySelectorAll('.file-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const fileCard = this.closest('.file-card');
            const filePath = this.value;
            
            if (this.checked) {
                selectedFiles.add(filePath);
                fileCard.classList.add('selected');
            } else {
                selectedFiles.delete(filePath);
                fileCard.classList.remove('selected');
            }
            
            updateBatchActions();
        });
    });

    // 更新批量操作栏
    function updateBatchActions() {
        const batchActions = document.getElementById('batchActions');
        const selectedCount = document.getElementById('selectedCount');
        
        selectedCount.textContent = selectedFiles.size;
        
        if (selectedFiles.size > 0) {
            batchActions.classList.add('show');
        } else {
            batchActions.classList.remove('show');
        }
    }

    // 清除选择
    function clearSelection() {
        selectedFiles.clear();
        document.querySelectorAll('.file-checkbox').forEach(cb => {
            cb.checked = false;
            cb.closest('.file-card').classList.remove('selected');
        });
        updateBatchActions();
    }

    // 批量下载
    function batchDownload() {
        if (selectedFiles.size === 0) return;
        
        if (selectedFiles.size === 1) {
            // 单个文件直接下载
            const file = Array.from(selectedFiles)[0];
            window.location.href = '?action=download&file=' + encodeURIComponent(file);
        } else {
            // 多个文件打包下载
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '';
            
            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'action';
            actionInput.value = 'batch_download';
            form.appendChild(actionInput);
            
            const filesInput = document.createElement('input');
            filesInput.type = 'hidden';
            filesInput.name = 'files';
            filesInput.value = JSON.stringify(Array.from(selectedFiles));
            form.appendChild(filesInput);
            
            document.body.appendChild(form);
            form.submit();
            document.body.removeChild(form);
        }
        
        showToast('开始下载 ' + selectedFiles.size + ' 个文件');
    }

    // 打开预览
    function openPreview(filePath, type, fileName) {
        document.getElementById('previewTitle').textContent = fileName;
        const contentDiv = document.getElementById('previewContent');
        const downloadBtn = document.getElementById('previewDownload');
        
        const streamUrl = '?action=stream&file=' + filePath;
        downloadBtn.href = '?action=download&file=' + filePath;
        
        if (type === 'image') {
            contentDiv.innerHTML = `<img src="${streamUrl}" alt="${fileName}" class="img-fluid">`;
        } else if (type === 'video') {
            contentDiv.innerHTML = `
                <video controls autoplay style="max-width: 100%; max-height: 70vh;">
                    <source src="${streamUrl}" type="video/mp4">
                    您的浏览器不支持视频播放。
                </video>
            `;
        }
        
        previewModal.show();
    }

    // 显示提示
    function showToast(message) {
        document.getElementById('toastMessage').innerHTML = '<i class="bi bi-check-circle-fill me-2"></i>' + message;
        toast.show();
    }

    // 模态框关闭时停止视频
    document.getElementById('previewModal').addEventListener('hidden.bs.modal', function () {
        document.getElementById('previewContent').innerHTML = '';
    });
</script>

</body>
</html>
