<?php
// ============================================================
//  自动扫描下载站 — 文件丢进 files/ 目录即可，无需任何配置
//  支持: index.php?file=文件名  直接触发下载
// ============================================================

$baseDir = __DIR__ . '/files';
$basePath = 'files/';   // URL 路径前缀
$siteName = '下载站';

// ---- 收集文件信息 ----
$files = [];
if (is_dir($baseDir)) {
    $items = scandir($baseDir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        $fullPath = $baseDir . '/' . $item;
        if (is_file($fullPath)) {
            $files[] = [
                'name' => $item,
                'size' => filesize($fullPath),
                'mtime' => filemtime($fullPath),
            ];
        }
    }
}

// 按修改时间降序（新的在前）
usort($files, function($a, $b) {
    return $b['mtime'] - $a['mtime'];
});

// ---- 文件图标映射 ----
function getFileIcon($filename) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $map = [
        'zip' => ['📦','icon-archive'], 'rar' => ['📦','icon-archive'], '7z' => ['📦','icon-archive'],
        'tar' => ['📦','icon-archive'], 'gz' => ['📦','icon-archive'], 'xz' => ['📦','icon-archive'],
        'bz2' => ['📦','icon-archive'],
        'pdf' => ['📄','icon-document'], 'doc' => ['📄','icon-document'], 'docx' => ['📄','icon-document'],
        'xls' => ['📄','icon-document'], 'xlsx' => ['📄','icon-document'],
        'ppt' => ['📄','icon-document'], 'pptx' => ['📄','icon-document'],
        'txt' => ['📄','icon-document'], 'md' => ['📄','icon-document'],
        'exe' => ['⚙️','icon-app'], 'msi' => ['⚙️','icon-app'], 'apk' => ['📱','icon-android'],
        'dmg' => ['🍎','icon-apple'], 'pkg' => ['🍎','icon-apple'],
        'iso' => ['💿','icon-disc'],
        'mp4' => ['🎬','icon-video'], 'avi' => ['🎬','icon-video'], 'mkv' => ['🎬','icon-video'],
        'mov' => ['🎬','icon-video'], 'webm' => ['🎬','icon-video'],
        'mp3' => ['🎵','icon-audio'], 'wav' => ['🎵','icon-audio'], 'flac' => ['🎵','icon-audio'],
        'aac' => ['🎵','icon-audio'], 'ogg' => ['🎵','icon-audio'],
        'jpg' => ['🖼️','icon-image'], 'jpeg' => ['🖼️','icon-image'], 'png' => ['🖼️','icon-image'],
        'gif' => ['🖼️','icon-image'], 'svg' => ['🖼️','icon-image'], 'webp' => ['🖼️','icon-image'],
        'ico' => ['🖼️','icon-image'],
    ];
    return $map[$ext] ?? ['📁','icon-generic'];
}

function formatSize($bytes) {
    if ($bytes === 0) return '0 B';
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $i = floor(log($bytes, 1024));
    $i = min($i, count($units) - 1);
    return round($bytes / pow(1024, $i), $i === 0 ? 0 : 1) . ' ' . $units[$i];
}

// ---- URL 定向下载 ----
$autoDownload = $_GET['file'] ?? null;
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo htmlspecialchars($siteName); ?></title>
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

  :root {
    --bg: #f0f2f5;
    --card-bg: #ffffff;
    --text: #1a1a2e;
    --text-secondary: #6b7280;
    --border: #e5e7eb;
    --accent: #4f46e5;
    --accent-hover: #4338ca;
    --shadow: 0 1px 3px rgba(0,0,0,0.06), 0 1px 2px rgba(0,0,0,0.04);
    --shadow-hover: 0 10px 25px rgba(0,0,0,0.1), 0 4px 10px rgba(0,0,0,0.05);
    --radius: 12px;
  }

  body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC",
                 "Microsoft YaHei", sans-serif;
    background: var(--bg);
    color: var(--text);
    min-height: 100vh;
    line-height: 1.6;
  }

  .header {
    background: var(--card-bg);
    border-bottom: 1px solid var(--border);
    padding: 0 24px;
    height: 64px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: sticky;
    top: 0;
    z-index: 10;
    box-shadow: var(--shadow);
  }

  .header-left { display: flex; align-items: center; gap: 10px; }

  .logo {
    width: 36px; height: 36px;
    background: var(--accent);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 18px;
    font-weight: 700;
  }

  .site-name { font-size: 18px; font-weight: 700; color: var(--text); }

  .header-right { display: flex; align-items: center; gap: 12px; }

  .file-count-badge {
    font-size: 13px; color: var(--text-secondary);
    background: var(--bg); padding: 4px 12px; border-radius: 20px;
  }

  .search-wrap { max-width: 600px; margin: 32px auto 0; padding: 0 20px; position: relative; }

  .search-box {
    width: 100%;
    padding: 12px 16px 12px 44px;
    border: 1px solid var(--border);
    border-radius: 10px;
    font-size: 15px;
    background: var(--card-bg);
    color: var(--text);
    outline: none;
    transition: border-color 0.2s, box-shadow 0.2s;
  }

  .search-box:focus {
    border-color: var(--accent);
    box-shadow: 0 0 0 3px rgba(79,70,229,0.1);
  }

  .search-icon {
    position: absolute; left: 14px; top: 50%;
    transform: translateY(-50%); color: var(--text-secondary); pointer-events: none;
  }

  .container { max-width: 1100px; margin: 0 auto; padding: 28px 20px 60px; }

  .categories { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 24px; }

  .cat-btn {
    padding: 6px 16px;
    border: 1px solid var(--border);
    border-radius: 20px;
    font-size: 13px;
    cursor: pointer;
    background: var(--card-bg);
    color: var(--text-secondary);
    transition: all 0.2s;
    font-family: inherit;
  }

  .cat-btn:hover { border-color: var(--accent); color: var(--accent); }

  .cat-btn.active { background: var(--accent); color: #fff; border-color: var(--accent); }

  .empty-state { text-align: center; padding: 60px 20px; color: var(--text-secondary); }

  .empty-state .empty-icon { font-size: 48px; margin-bottom: 12px; }

  .card-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
  }

  .card {
    background: var(--card-bg);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 14px;
    box-shadow: var(--shadow);
    transition: transform 0.2s, box-shadow 0.2s;
  }

  .card:hover { transform: translateY(-2px); box-shadow: var(--shadow-hover); }

  .file-icon {
    width: 48px; height: 48px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    flex-shrink: 0;
  }

  .icon-archive  { background: #fef3c7; }
  .icon-document { background: #dbeafe; }
  .icon-app      { background: #e0e7ff; }
  .icon-video    { background: #fce7f3; }
  .icon-audio    { background: #d1fae5; }
  .icon-image    { background: #cffafe; }
  .icon-android  { background: #d1fae5; }
  .icon-apple    { background: #e5e7eb; }
  .icon-disc     { background: #fee2e2; }
  .icon-generic  { background: #f3f4f6; }

  .file-info { flex: 1; min-width: 0; }

  .file-name {
    font-size: 14px; font-weight: 600; color: var(--text);
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    margin-bottom: 2px;
  }

  .file-meta {
    font-size: 12px; color: var(--text-secondary);
    display: flex; gap: 8px; align-items: center; flex-wrap: wrap;
  }

  .dl-btn {
    width: 38px; height: 38px;
    border-radius: 8px;
    border: none;
    background: var(--accent);
    color: #fff;
    cursor: pointer;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    transition: background 0.2s, transform 0.15s;
    text-decoration: none;
  }

  .dl-btn:hover { background: var(--accent-hover); transform: scale(1.06); }
  .dl-btn:active { transform: scale(0.95); }

  .footer {
    text-align: center; padding: 20px; font-size: 12px;
    color: var(--text-secondary); border-top: 1px solid var(--border); margin-top: 20px;
  }

  .toast {
    position: fixed; bottom: 30px; left: 50%;
    transform: translateX(-50%) translateY(80px);
    background: #1a1a2e; color: #fff;
    padding: 10px 24px; border-radius: 8px;
    font-size: 14px; z-index: 999;
    opacity: 0;
    transition: transform 0.3s, opacity 0.3s;
    pointer-events: none;
  }

  .toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }

  @media (max-width: 640px) {
    .card-grid { grid-template-columns: 1fr; }
    .header { padding: 0 16px; }
    .site-name { font-size: 16px; }
    .container { padding: 20px 12px 40px; }
    .search-wrap { margin-top: 20px; }
  }
</style>
</head>
<body>

<header class="header">
  <div class="header-left">
    <div class="logo">📥</div>
    <span class="site-name"><?php echo htmlspecialchars($siteName); ?></span>
  </div>
  <div class="header-right">
    <span class="file-count-badge" id="fileCount">共 <?php echo count($files); ?> 个文件</span>
  </div>
</header>

<div class="search-wrap">
  <span class="search-icon">🔍</span>
  <input class="search-box" type="text" id="searchInput"
         placeholder="搜索文件名..." autocomplete="off">
</div>

<div class="container">
  <div class="categories" id="categories"></div>
  <div class="card-grid" id="cardGrid">
    <?php foreach ($files as $f): ?>
      <?php
        [$emoji, $iconClass] = getFileIcon($f['name']);
        $url = $basePath . rawurlencode($f['name']);
      ?>
      <div class="card" data-ext="<?php echo htmlspecialchars(strtolower(pathinfo($f['name'], PATHINFO_EXTENSION))); ?>"
           data-name="<?php echo htmlspecialchars(strtolower($f['name'])); ?>">
        <div class="file-icon <?php echo $iconClass; ?>"><?php echo $emoji; ?></div>
        <div class="file-info">
          <div class="file-name" title="<?php echo htmlspecialchars($f['name']); ?>"><?php echo htmlspecialchars($f['name']); ?></div>
          <div class="file-meta">
            <span><?php echo formatSize($f['size']); ?></span>
            <span><?php echo date('Y-m-d', $f['mtime']); ?></span>
          </div>
        </div>
        <a class="dl-btn" href="<?php echo htmlspecialchars($url); ?>" download title="下载">⬇</a>
      </div>
    <?php endforeach; ?>
  </div>
  <div class="empty-state" id="emptyState" style="display:none">
    <div class="empty-icon">📭</div>
    <p>没有找到匹配的文件</p>
  </div>
</div>

<div class="footer">
  把文件丢进 files/ 目录即可自动显示 · 无需手动配置
</div>

<div class="toast" id="toast"></div>

<script>
// ============ 分类 & 搜索 ============
(function() {
  const cards = Array.from(document.querySelectorAll('.card'));
  const catsContainer = document.getElementById('categories');
  const searchInput = document.getElementById('searchInput');
  const emptyState = document.getElementById('emptyState');
  const grid = document.getElementById('cardGrid');
  const countEl = document.getElementById('fileCount');

  let activeCat = '全部';
  let searchTerm = '';

  // 收集扩展名
  const extSet = new Set();
  cards.forEach(c => { const ext = c.dataset.ext; if (ext) extSet.add(ext); });
  const extList = ['全部', ...Array.from(extSet).sort()];

  // 渲染分类标签
  catsContainer.innerHTML = extList.map(e =>
    `<button class="cat-btn${e === '全部' ? ' active' : ''}" data-cat="${e}">${e === '全部' ? '📋 全部' : '.' + e.toUpperCase()}</button>`
  ).join('');

  catsContainer.addEventListener('click', function(e) {
    if (!e.target.classList.contains('cat-btn')) return;
    catsContainer.querySelectorAll('.cat-btn').forEach(b => b.classList.remove('active'));
    e.target.classList.add('active');
    activeCat = e.target.dataset.cat;
    filterCards();
  });

  searchInput.addEventListener('input', function() {
    searchTerm = this.value.trim().toLowerCase();
    filterCards();
  });

  function filterCards() {
    let visible = 0;
    cards.forEach(c => {
      let show = true;
      if (activeCat !== '全部' && c.dataset.ext !== activeCat) show = false;
      if (searchTerm && !c.dataset.name.includes(searchTerm)) show = false;
      c.style.display = show ? '' : 'none';
      if (show) visible++;
    });

    emptyState.style.display = visible === 0 ? 'block' : 'none';
    countEl.textContent = '共 ' + visible + ' 个文件';
  }
})();

// ============ Toast ============
function showToast(msg) {
  var t = document.getElementById('toast');
  t.textContent = msg;
  t.classList.add('show');
  clearTimeout(t._timeout);
  t._timeout = setTimeout(function() { t.classList.remove('show'); }, 2000);
}
</script>

<?php if ($autoDownload): ?>
<script>
// URL 定向下载: ?file=文件名
(function() {
  var fileName = <?php echo json_encode($autoDownload); ?>;
  var basePath = <?php echo json_encode($basePath); ?>;
  var url = basePath + encodeURIComponent(fileName);
  setTimeout(function() {
    var a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    showToast('正在下载：' + fileName);
  }, 300);
})();
</script>
<?php endif; ?>

</body>
</html>
