<?php
requireAdmin();

// ========== 处理文件上传 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'upload') {
    header('Content-Type: application/json');
    
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $version = trim($_POST['version'] ?? '');
    $sort = intval($_POST['sort'] ?? 0);
    $status = intval($_POST['status'] ?? 1);
    
    if (empty($title)) {
        echo json_encode(['success' => false, 'message' => '标题不能为空']);
        exit;
    }
    
    if (!isset($_FILES['file']) || $_FILES['file']['error'] != 0) {
        $error_msg = isset($_FILES['file']) ? '上传错误码：' . $_FILES['file']['error'] : '请选择文件';
        echo json_encode(['success' => false, 'message' => $error_msg]);
        exit;
    }
    
    $file = $_FILES['file'];
    $max_size = 100 * 1024 * 1024;
    
    if ($file['size'] > $max_size) {
        echo json_encode(['success' => false, 'message' => '文件大小不能超过100MB']);
        exit;
    }
    
    $upload_dir = dirname(__DIR__, 2) . '/assets/uploads/downloads/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = date('YmdHis') . '_' . uniqid() . '.' . $ext;
    $file_path = $upload_dir . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $file_path)) {
        $file_size = formatFileSize($file['size']);
        $file_url = '/assets/uploads/downloads/' . $filename;
        
        $title = $db->escape($title);
        $description = $db->escape($description);
        $version = $db->escape($version);
        $file_name = $db->escape($file['name']);
        $file_url_safe = $db->escape($file_url);
        
        $db->query("INSERT INTO downloads (title, description, file_name, file_path, file_size, version, sort, status) 
                    VALUES ('$title', '$description', '$file_name', '$file_url_safe', '$file_size', '$version', $sort, $status)");
        
        echo json_encode(['success' => true, 'message' => '上传成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '文件上传失败']);
    }
    exit;
}

// ========== 正常页面显示 ==========
$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 15;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

$where = "1=1";
if ($search) {
    $search = $db->escape($search);
    $where .= " AND (title LIKE '%$search%' OR description LIKE '%$search%')";
}

$total_result = $db->query("SELECT COUNT(*) as cnt FROM downloads WHERE $where");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

$downloads = $db->fetchAll("
    SELECT * FROM downloads 
    WHERE $where 
    ORDER BY sort ASC, id DESC 
    LIMIT $offset, $perpage
");

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

<div class="downloads-manager">
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:download-box.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            资源下载管理
        </h2>
        <button class="btn btn-primary" id="showUploadModalBtn">
            <img src="https://api.iconify.design/mdi:cloud-upload.svg?color=white" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
            上传文件
        </button>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-mini">
        <div class="stat-mini-item">
            <img src="https://api.iconify.design/mdi:file-multiple.svg?color=%23667eea" width="20" height="20" alt="">
            <span class="stat-label">总资源数</span>
            <span class="stat-value"><?php echo $total; ?></span>
        </div>
    </div>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
        <form method="GET">
            <input type="hidden" name="page" value="downloads">
            <div class="search-input-wrapper">
                <img src="https://api.iconify.design/mdi:magnify.svg?color=%239ca3af" width="18" height="18" class="search-icon" alt="">
                <input type="text" name="search" placeholder="搜索标题或描述..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <button type="submit" class="btn btn-primary">
                <img src="https://api.iconify.design/mdi:magnify.svg?color=white" width="16" height="16" style="vertical-align: middle; margin-right: 4px;" alt="">
                搜索
            </button>
            <?php if ($search): ?>
                <a href="?page=downloads" class="btn btn-secondary">
                    <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="vertical-align: middle; margin-right: 4px;" alt="">
                    清空
                </a>
            <?php endif; ?>
        </form>
    </div>
    
    <div class="table-wrapper">
        <table class="data-table" id="downloadsTable">
            <thead>
                <tr>
                    <th style="width: 5%;">ID</th>
                    <th style="width: 22%;">标题</th>
                    <th style="width: 20%;">文件名</th>
                    <th style="width: 7%;">大小</th>
                    <th style="width: 7%;">版本</th>
                    <th style="width: 7%;">下载</th>
                    <th style="width: 5%;">排序</th>
                    <th style="width: 7%;">状态</th>
                    <th style="width: 10%;">创建时间</th>
                    <th style="width: 10%;">操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($downloads)): ?>
                    <tr>
                        <td colspan="10">
                            <div class="empty-state">
                                <img src="https://api.iconify.design/mdi:package-variant-closed.svg?color=%239ca3af" width="48" height="48" alt="">
                                <p>暂无资源</p>
                                <span>点击上方按钮上传文件</span>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($downloads as $item): ?>
                        <tr id="download-row-<?php echo $item['id']; ?>">
                            <td class="id-cell">#<?php echo $item['id']; ?></td>
                            <td>
                                <div class="title-cell">
                                    <img src="https://api.iconify.design/mdi:file.svg?color=%23667eea" width="18" height="18" style="margin-right: 8px;" alt="">
                                    <div class="title-info">
                                        <strong><?php echo htmlspecialchars($item['title']); ?></strong>
                                        <?php if (!empty($item['description'])): ?>
                                            <span class="description-preview"><?php echo htmlspecialchars(mb_substr($item['description'], 0, 35)); ?><?php echo mb_strlen($item['description']) > 35 ? '...' : ''; ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            <td><code><?php echo htmlspecialchars($item['file_name']); ?></code></td>
                            <td><span class="file-size"><?php echo $item['file_size']; ?></span></td>
                            <td>
                                <?php if ($item['version']): ?>
                                    <span class="version-badge">v<?php echo htmlspecialchars($item['version']); ?></span>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="download-count">
                                <img src="https://api.iconify.design/mdi:download.svg?color=%239ca3af" width="14" height="14" style="margin-right: 4px;" alt="">
                                <?php echo $item['download_count']; ?>
                            </td>
                            <td class="sort-cell"><?php echo $item['sort']; ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $item['status'] ? 'active' : 'inactive'; ?>" id="status-badge-<?php echo $item['id']; ?>">
                                    <span class="status-dot"></span>
                                    <?php echo $item['status'] ? '启用' : '禁用'; ?>
                                </span>
                            </td>
                            <td class="date-cell"><?php echo date('Y-m-d H:i', strtotime($item['created_at'])); ?></td>
                            <td class="action-buttons">
                                <button class="action-btn toggle-status-btn" data-id="<?php echo $item['id']; ?>" data-status="<?php echo $item['status']; ?>" title="<?php echo $item['status'] ? '禁用' : '启用'; ?>">
                                    <?php if ($item['status']): ?>
                                        <img src="https://api.iconify.design/mdi:eye-off.svg?color=%23ef4444" width="16" height="16" alt="">
                                    <?php else: ?>
                                        <img src="https://api.iconify.design/mdi:eye.svg?color=%2310b981" width="16" height="16" alt="">
                                    <?php endif; ?>
                                </button>
                                <button class="action-btn delete-btn" data-id="<?php echo $item['id']; ?>" title="删除">
                                    <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="16" height="16" alt="">
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=downloads&p=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>" class="page-link page-prev">
                    <img src="https://api.iconify.design/mdi:chevron-left.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
            
            <?php
            $total_pages = ceil($total / $perpage);
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            
            if ($start_page > 1): ?>
                <a href="?page=downloads&p=1&search=<?php echo urlencode($search); ?>" class="page-link">1</a>
                <?php if ($start_page > 2): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
            <?php endif; ?>
            
            <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                <a href="?page=downloads&p=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($end_page < $total_pages): ?>
                <?php if ($end_page < $total_pages - 1): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
                <a href="?page=downloads&p=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>" class="page-link"><?php echo $total_pages; ?></a>
            <?php endif; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=downloads&p=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>" class="page-link page-next">
                    <img src="https://api.iconify.design/mdi:chevron-right.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 上传弹窗 -->
<div id="uploadModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>
                <img src="https://api.iconify.design/mdi:cloud-upload.svg?color=%23667eea" width="22" height="22" style="vertical-align: middle; margin-right: 8px;" alt="">
                上传文件
            </h3>
            <button type="button" class="modal-close" onclick="closeModal()">
                <img src="https://api.iconify.design/mdi:close.svg?color=%239ca3af" width="20" height="20" alt="">
            </button>
        </div>
        <form id="uploadForm" enctype="multipart/form-data">
            <div class="modal-body">
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:format-title.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        标题 <span class="required">*</span>
                    </label>
                    <input type="text" name="title" required placeholder="例如：软件安装包 v1.0">
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:text-box.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        描述
                    </label>
                    <textarea name="description" rows="3" placeholder="资源描述..."></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>
                            <img src="https://api.iconify.design/mdi:tag.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            版本号
                        </label>
                        <input type="text" name="version" placeholder="例如：1.0.0">
                    </div>
                    <div class="form-group">
                        <label>
                            <img src="https://api.iconify.design/mdi:sort.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            排序
                        </label>
                        <input type="number" name="sort" value="0" placeholder="数字越小越靠前">
                    </div>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:toggle-switch.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        状态
                    </label>
                    <select name="status">
                        <option value="1">启用</option>
                        <option value="0">禁用</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:file-upload.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        选择文件 <span class="required">*</span>
                    </label>
                    <div class="file-input-wrapper">
                        <input type="file" name="file" required id="fileInput">
                        <label for="fileInput" class="file-input-label">
                            <img src="https://api.iconify.design/mdi:folder-open.svg?color=%23667eea" width="18" height="18" style="margin-right: 6px;" alt="">
                            选择文件
                        </label>
                        <span class="file-name" id="fileNameDisplay">未选择文件</span>
                    </div>
                    <small>支持任意格式，最大100MB</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn" onclick="closeModal()">
                    <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                    取消
                </button>
                <button type="submit" class="btn btn-primary">
                    <img src="https://api.iconify.design/mdi:cloud-upload.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                    上传
                </button>
            </div>
        </form>
    </div>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.downloads-manager {
    max-width: 100%;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 16px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.page-header h2 img {
    display: inline-block;
}

/* 统计卡片 */
.stats-mini {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
}
.stat-mini-item {
    display: flex;
    align-items: center;
    gap: 10px;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.08) 0%, rgba(102, 126, 234, 0.02) 100%);
    padding: 12px 20px;
    border-radius: var(--radius-md);
    border: 1px solid rgba(102, 126, 234, 0.15);
}
.stat-mini-item .stat-label {
    font-size: 14px;
    color: var(--text-secondary);
}
.stat-mini-item .stat-value {
    font-size: 20px;
    font-weight: 700;
    color: var(--primary-color);
    margin-left: 4px;
}

/* 搜索栏 */
.search-bar {
    margin-bottom: 24px;
}
.search-bar form {
    display: flex;
    gap: 12px;
    align-items: center;
}
.search-input-wrapper {
    position: relative;
    flex: 1;
    max-width: 360px;
}
.search-input-wrapper .search-icon {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    pointer-events: none;
}
.search-input-wrapper input {
    width: 100%;
    padding: 12px 16px 12px 44px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-lg);
    background: var(--bg-primary);
    font-size: 14px;
    transition: all 0.2s;
}
.search-input-wrapper input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 表格 */
.table-wrapper {
    overflow-x: auto;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 1100px;
}
.data-table th {
    padding: 16px 16px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
    white-space: nowrap;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}
.data-table td {
    padding: 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    vertical-align: middle;
}
.data-table tbody tr {
    transition: background 0.2s;
}
.data-table tbody tr:hover {
    background: var(--bg-secondary);
}
.data-table tbody tr:last-child td {
    border-bottom: none;
}

/* 单元格样式 */
.id-cell {
    font-family: 'Monaco', 'Menlo', monospace;
    font-size: 12px;
    color: var(--text-muted);
    font-weight: 500;
}
.title-cell {
    display: flex;
    align-items: flex-start;
}
.title-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.title-info strong {
    font-size: 14px;
    font-weight: 600;
    color: var(--text-primary);
}
.description-preview {
    font-size: 12px;
    color: var(--text-muted);
    line-height: 1.4;
}
.file-size {
    font-family: 'Monaco', 'Menlo', monospace;
    font-size: 12px;
    color: var(--text-secondary);
}
.version-badge {
    display: inline-block;
    padding: 4px 10px;
    background: linear-gradient(135deg, #e0e7ff 0%, #c7d2fe 100%);
    color: #4338ca;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}
.download-count {
    display: flex;
    align-items: center;
    color: var(--text-secondary);
}
.sort-cell {
    font-weight: 500;
    color: var(--text-secondary);
}
.date-cell {
    font-size: 13px;
    color: var(--text-secondary);
    white-space: nowrap;
}
.text-muted {
    color: var(--text-muted);
}

/* 状态徽章 */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
    white-space: nowrap;
}
.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-active .status-dot {
    background: #10b981;
    box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.status-inactive .status-dot {
    background: #ef4444;
    box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.2);
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    gap: 8px;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    cursor: pointer;
    transition: all 0.2s;
}
.action-btn:hover {
    background: var(--bg-primary);
    border-color: var(--primary-color);
    transform: translateY(-1px);
    box-shadow: var(--shadow-sm);
}
.delete-btn:hover {
    border-color: var(--danger-color);
    background: #fef2f2;
}

/* 空状态 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
}
.empty-state img {
    opacity: 0.4;
    margin-bottom: 16px;
}
.empty-state p {
    font-size: 16px;
    font-weight: 500;
    color: var(--text-secondary);
    margin: 0 0 4px;
}
.empty-state span {
    font-size: 14px;
    color: var(--text-muted);
}

/* 分页 */
.pagination {
    display: flex;
    gap: 6px;
    justify-content: center;
    margin-top: 28px;
}
.page-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    padding: 0 8px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    text-decoration: none;
    color: var(--text-primary);
    font-size: 14px;
    font-weight: 500;
    background: var(--bg-primary);
    transition: all 0.2s;
}
.page-link:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.page-prev, .page-next {
    padding: 0 12px;
}
.page-ellipsis {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    color: var(--text-muted);
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 10px 20px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
    gap: 6px;
}
.btn img {
    display: inline-block;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
    border-color: var(--text-muted);
}

/* 弹窗 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    animation: fadeIn 0.2s ease;
}
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}
.modal-content {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    width: 90%;
    max-width: 520px;
    box-shadow: var(--shadow-lg);
    animation: slideUp 0.3s ease;
}
@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    margin: 0;
    color: var(--text-primary);
}
.modal-close {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: var(--radius-sm);
    transition: background 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
}
.modal-close:hover {
    background: var(--bg-secondary);
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px 24px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}

/* 表单 */
.form-group {
    margin-bottom: 20px;
}
.form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
    color: var(--text-primary);
}
.form-group label img {
    display: inline-block;
}
.required {
    color: var(--danger-color);
    margin-left: 2px;
}
.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 14px;
    background: var(--bg-primary);
    color: var(--text-primary);
    transition: all 0.2s;
}
.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group textarea {
    resize: vertical;
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}
.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
}

/* 文件上传 */
.file-input-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
}
.file-input-wrapper input[type="file"] {
    display: none;
}
.file-input-label {
    display: inline-flex;
    align-items: center;
    padding: 10px 18px;
    background: var(--bg-secondary);
    border: 1.5px dashed var(--border-color);
    border-radius: var(--radius-md);
    cursor: pointer;
    font-size: 14px;
    color: var(--text-primary);
    transition: all 0.2s;
    white-space: nowrap;
}
.file-input-label:hover {
    border-color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.file-name {
    font-size: 13px;
    color: var(--text-muted);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 0.6s linear infinite;
    margin-right: 8px;
    vertical-align: middle;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}

/* 代码样式 */
code {
    background: var(--bg-secondary);
    padding: 4px 8px;
    border-radius: var(--radius-sm);
    font-size: 12px;
    font-family: 'Monaco', 'Menlo', 'Courier New', monospace;
    color: var(--text-primary);
    border: 1px solid var(--border-color);
}

/* 响应式 */
@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
        gap: 0;
    }
    .file-input-wrapper {
        flex-direction: column;
        align-items: flex-start;
    }
    .file-name {
        width: 100%;
    }
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .search-bar form {
        flex-wrap: wrap;
    }
    .search-input-wrapper {
        max-width: 100%;
    }
}
</style>

<script>
// 文件选择显示文件名
document.getElementById('fileInput')?.addEventListener('change', function(e) {
    const fileName = e.target.files[0]?.name || '未选择文件';
    document.getElementById('fileNameDisplay').textContent = fileName;
});

// 显示上传弹窗
document.getElementById('showUploadModalBtn')?.addEventListener('click', function() {
    document.getElementById('uploadModal').style.display = 'flex';
});

// 关闭弹窗
function closeModal() {
    document.getElementById('uploadModal').style.display = 'none';
    document.getElementById('uploadForm')?.reset();
    document.getElementById('fileNameDisplay').textContent = '未选择文件';
}

// 点击弹窗背景关闭
document.getElementById('uploadModal')?.addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal();
    }
});

// ESC 关闭弹窗
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeModal();
    }
});

// 上传表单提交
document.getElementById('uploadForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<span class="loading-spinner"></span> 上传中...';
    submitBtn.disabled = true;
    
    fetch('?page=downloads&action=upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.showToast('上传成功', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            window.showToast(data.message || '上传失败', 'error');
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('错误:', error);
        window.showToast('网络错误', 'error');
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});

// 切换状态（使用独立API）
document.querySelectorAll('.toggle-status-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.getAttribute('data-id');
        const currentStatus = parseInt(this.getAttribute('data-status'));
        const newStatus = currentStatus === 1 ? 0 : 1;
        const statusSpan = document.getElementById('status-badge-' + id);
        const originalHtml = this.innerHTML;
        
        this.innerHTML = '<span class="loading-spinner"></span>';
        this.disabled = true;
        
        fetch('/api/download_toggle_status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}&status=${newStatus}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (newStatus === 1) {
                    statusSpan.className = 'status-badge status-active';
                    statusSpan.innerHTML = '<span class="status-dot"></span>启用';
                    this.innerHTML = '<img src="https://api.iconify.design/mdi:eye-off.svg?color=%23ef4444" width="16" height="16" alt="">';
                    this.setAttribute('data-status', '1');
                    this.setAttribute('title', '禁用');
                } else {
                    statusSpan.className = 'status-badge status-inactive';
                    statusSpan.innerHTML = '<span class="status-dot"></span>禁用';
                    this.innerHTML = '<img src="https://api.iconify.design/mdi:eye.svg?color=%2310b981" width="16" height="16" alt="">';
                    this.setAttribute('data-status', '0');
                    this.setAttribute('title', '启用');
                }
                window.showToast('状态已更新', 'success');
            } else {
                window.showToast(data.message || '操作失败', 'error');
            }
            this.disabled = false;
        })
        .catch(error => {
            console.error('错误:', error);
            window.showToast('网络错误', 'error');
            this.innerHTML = originalHtml;
            this.disabled = false;
        });
    });
});

// 删除资源（使用独立API）
document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.getAttribute('data-id');
        if (!confirm('确定要删除此资源吗？此操作不可恢复。')) return;
        
        const row = document.getElementById('download-row-' + id);
        const originalHtml = this.innerHTML;
        
        this.innerHTML = '<span class="loading-spinner"></span>';
        this.disabled = true;
        
        fetch('/api/download_delete.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                row.style.transition = 'opacity 0.3s';
                row.style.opacity = '0';
                setTimeout(() => {
                    row.remove();
                    window.showToast('删除成功', 'success');
                    if (document.querySelectorAll('#downloadsTable tbody tr').length === 0) {
                        location.reload();
                    }
                }, 300);
            } else {
                window.showToast(data.message || '删除失败', 'error');
                this.innerHTML = originalHtml;
                this.disabled = false;
            }
        })
        .catch(error => {
            console.error('错误:', error);
            window.showToast('网络错误', 'error');
            this.innerHTML = originalHtml;
            this.disabled = false;
        });
    });
});
</script>