<?php
/**
 * 文件站 - 文件列表
 */
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/header.php';

$pdo = portal_pdo();

// ========== 参数 ==========
$q        = trim((string)($_GET['q'] ?? ''));
$cat      = (string)($_GET['cat'] ?? '');
$page     = max(1, (int)($_GET['page'] ?? 1));
$perPage  = 20;
$offset   = ($page - 1) * $perPage;

// ========== 构建查询 ==========
$where = ['is_deleted = 0'];
$bind  = [];

// 可见性：未登录只看 public；登录看 public + member；管理员全部
if (!is_logged_in()) {
    $where[] = "visibility = 'public'";
} elseif (!is_admin()) {
    $where[] = "visibility IN ('public','member')";
}
// 管理员不加限制（默认 'public','member','admin' 全看）

if ($cat !== '') {
    $where[] = 'category = ?';
    $bind[]  = $cat;
}
if ($q !== '') {
    // 批量搜索：空格拆词 OR
    $terms = array_filter(array_map('trim', explode(' ', $q)));
    if (!empty($terms)) {
        $ors = [];
        foreach ($terms as $t) {
            $ors[] = '(filename LIKE ?)';
            $bind[] = '%' . $t . '%';
        }
        $where[] = '(' . implode(' OR ', $ors) . ')';
    }
}

$whereSql = implode(' AND ', $where);

// ========== 总数 + 列表 ==========
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM files WHERE $whereSql");
$countStmt->execute($bind);
$total = (int)$countStmt->fetchColumn();
$pages = max(1, (int)ceil($total / $perPage));
if ($page > $pages) $page = $pages;

$sql = "SELECT f.*, u.display_name AS uploader_name
        FROM files f LEFT JOIN users u ON f.uploader_id = u.id
        WHERE $whereSql
        ORDER BY f.created_at DESC
        LIMIT $perPage OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($bind);
$files = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ========== 分类列表 ==========
$cats = $pdo->query("SELECT name FROM file_categories ORDER BY sort ASC")->fetchAll(PDO::FETCH_COLUMN);

// ========== 辅助函数 ==========
function file_icon(string $mime, string $filename): string {
    $map = [
        'pdf'   => '📄', 'doc' => '📝', 'docx' => '📝',
        'xls'   => '📊', 'xlsx' => '📊', 'csv'  => '📊',
        'ppt'   => '📽️', 'pptx' => '📽️',
        'zip'   => '🗜️', 'rar' => '🗜️', '7z'   => '🗜️', 'gz' => '🗜️',
        'jpg'   => '🖼️', 'jpeg'=> '🖼️', 'png' => '🖼️', 'gif' => '🖼️', 'webp' => '🖼️',
        'svg'   => '🎨',
        'mp4'   => '🎬', 'webm' => '🎬', 'mov' => '🎬',
        'mp3'   => '🎵', 'wav' => '🎵', 'flac' => '🎵',
    ];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    return $map[$ext] ?? '📁';
}
function is_previewable(string $mime, string $filename = ''): bool {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    // 原生支持
    if (in_array($mime, ['image/jpeg','image/png','image/gif','image/webp','image/svg+xml','image/bmp',
                          'video/mp4','video/webm','audio/mpeg','audio/wav','application/pdf'], true)) return true;
    // 扩展名支持（更准）
    if (in_array($ext, ['jpg','jpeg','png','gif','webp','bmp','svg',
                        'mp4','webm','mov','mp3','wav','flac','ogg',
                        'pdf','txt','csv','md','json','xml',
                        'doc','docx','xls','xlsx','ppt','pptx','odt','ods','odp'], true)) return true;
    return false;
}
function fmt_size(int $b): string {
    if ($b >= 1024*1024*1024) return round($b/1024/1024/1024, 2) . ' GB';
    if ($b >= 1024*1024)     return round($b/1024/1024, 2) . ' MB';
    if ($b >= 1024)          return round($b/1024, 1) . ' KB';
    return $b . ' B';
}
?>
<div class="fs-wrap">

  <!-- 搜索栏 -->
  <div class="fs-toolbar">
    <form class="fs-search" method="get" action="">
      <input type="text" name="q" value="<?= e($q) ?>" placeholder="🔍 搜索文件名（空格分隔多个关键词）">
      <select name="cat">
        <option value="">全部类别</option>
        <?php foreach ($cats as $c): ?>
          <option value="<?= e($c) ?>" <?= $cat === $c ? 'selected' : '' ?>><?= e($c) ?></option>
        <?php endforeach; ?>
      </select>
      <button type="submit">🔎 搜索</button>
      <?php if ($q !== '' || $cat !== ''): ?>
        <a href="/index.html" class="fs-clear">清除</a>
      <?php endif; ?>
    </form>
    <?php if (has_perm('upload_file')): ?>
      <a href="/upload.html" class="fs-btn-primary">⬆️ 上传文件</a>
    <?php endif; ?>
  </div>

  <!-- 统计 -->
  <div class="fs-stats">
    共 <b><?= $total ?></b> 个文件
    <?php if ($q !== ''): ?>· 搜索「<?= e($q) ?>」<?php endif; ?>
    <?php if ($cat !== ''): ?>· 类别「<?= e($cat) ?>」<?php endif; ?>
  </div>

  <?php if (empty($files)): ?>
    <div class="fs-empty">
      <div class="fs-empty-icon">📭</div>
      <div>暂无文件<?= ($q !== '' || $cat !== '') ? '，试试换个关键词' : '' ?></div>
    </div>
  <?php else: ?>

  <!-- 文件表格 -->
  <div class="fs-table-wrap">
    <table class="fs-table">
      <thead>
        <tr>
          <th class="fs-col-icon"></th>
          <th class="fs-col-name">文件名</th>
          <th class="fs-col-size">大小</th>
          <th class="fs-col-uploader">上传者</th>
          <th class="fs-col-date">上传时间</th>
          <th class="fs-col-dl">下载</th>
          <th class="fs-col-ops">操作</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($files as $f): ?>
        <tr>
          <td class="fs-col-icon"><?= file_icon($f['mime'], $f['filename']) ?></td>
          <td class="fs-col-name">
            <a href="/view.html?id=<?= (int)$f['id'] ?>" class="fs-fname" title="<?= e($f['filename']) ?>">
              <?= e(mb_strlen($f['filename']) > 60 ? mb_substr($f['filename'], 0, 57) . '...' : $f['filename']) ?>
            </a>
            <?php if ($f['visibility'] !== 'member'): ?>
              <span class="fs-vis fs-vis-<?= $f['visibility'] ?>">
                <?= $f['visibility'] === 'public' ? '🌐 公开' : '🔒 管理员' ?>
              </span>
            <?php endif; ?>
          </td>
          <td class="fs-col-size"><?= fmt_size((int)$f['size']) ?></td>
          <td class="fs-col-uploader"><?= e($f['uploader_name'] ?: '未知') ?></td>
          <td class="fs-col-date"><?= e($f['created_at']) ?></td>
          <td class="fs-col-dl">⬇️ <?= (int)$f['downloads'] ?></td>
          <td class="fs-col-ops">
            <?php if (is_previewable($f['mime'], $f['filename'])): ?>
              <a href="/view.html?id=<?= (int)$f['id'] ?>">👁️ 预览</a>
            <?php endif; ?>
            <a href="/download.html?id=<?= (int)$f['id'] ?>">⬇️ 下载</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- 分页 -->
  <?php if ($pages > 1): ?>
  <div class="fs-pager">
    <?php if ($page > 1): ?>
      <a href="?<?= e(http_build_query(array_merge($_GET, ['page' => $page - 1]))) ?>">← 上一页</a>
    <?php endif; ?>
    <span><?= $page ?> / <?= $pages ?></span>
    <?php if ($page < $pages): ?>
      <a href="?<?= e(http_build_query(array_merge($_GET, ['page' => $page + 1]))) ?>">下一页 →</a>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <?php endif; ?>
</div>

<?php require __DIR__ . '/includes/footer.php'; ?>
