<?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>资源下载管理</h2>
        <button class="btn btn-primary" id="showUploadModalBtn">+ 上传文件</button>
    </div>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
        <form method="GET">
            <input type="hidden" name="page" value="downloads">
            <input type="text" name="search" placeholder="搜索标题/描述" value="<?php echo htmlspecialchars($search); ?>">
            <button type="submit" class="btn btn-primary">搜索</button>
            <?php if ($search): ?>
                <a href="?page=downloads" class="btn btn-secondary">清空</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: 20%;">标题</th>
                    <th style="width: 20%;">文件名</th>
                    <th style="width: 8%;">大小</th>
                    <th style="width: 8%;">版本</th>
                    <th style="width: 8%;">下载次数</th>
                    <th style="width: 5%;">排序</th>
                    <th style="width: 8%;">状态</th>
                    <th style="width: 12%;">创建时间</th>
                    <th style="width: 12%;">操作</th>
                </thead>
            <tbody>
                <?php if (empty($downloads)): ?>
                    <tr>
                        <td colspan="10" style="text-align: center; padding: 60px;">暂无资源</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($downloads as $item): ?>
                        <tr id="download-row-<?php echo $item['id']; ?>">
                            <td style="text-align: center;"><?php echo $item['id']; ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($item['title']); ?></strong>
                                <?php if (!empty($item['description'])): ?>
                                    <br><small style="color: var(--text-muted);"><?php echo htmlspecialchars(mb_substr($item['description'], 0, 40)); ?></small>
                                <?php endif; ?>
                            </td>
                            <td><code><?php echo htmlspecialchars($item['file_name']); ?></code></td>
                            <td><?php echo $item['file_size']; ?></td>
                            <td><?php echo $item['version'] ?: '-'; ?></td>
                            <td style="text-align: center;"><?php echo $item['download_count']; ?></td>
                            <td style="text-align: center;"><?php echo $item['sort']; ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $item['status'] ? 'active' : 'inactive'; ?>" id="status-badge-<?php echo $item['id']; ?>">
                                    <?php echo $item['status'] ? '启用' : '禁用'; ?>
                                </span>
                            </td>
                            <td><?php echo $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']; ?>">
                                    <?php echo $item['status'] ? '🔴 禁用' : '🟢 启用'; ?>
                                </button>
                                <button class="action-btn delete-btn" data-id="<?php echo $item['id']; ?>">
                                    🗑️ 删除
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php
            $total_pages = ceil($total / $perpage);
            for ($i = 1; $i <= $total_pages; $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; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 上传弹窗 -->
<div id="uploadModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 500px;">
        <div class="modal-header">
            <h3>上传文件</h3>
            <span class="close">&times;</span>
        </div>
        <form id="uploadForm" enctype="multipart/form-data">
            <div class="modal-body">
                <div class="form-group">
                    <label>标题 *</label>
                    <input type="text" name="title" required placeholder="例如：软件安装包 v1.0">
                </div>
                <div class="form-group">
                    <label>描述</label>
                    <textarea name="description" rows="3" placeholder="资源描述..."></textarea>
                </div>
                <div class="form-group">
                    <label>版本号</label>
                    <input type="text" name="version" placeholder="例如：1.0.0">
                </div>
                <div class="form-group">
                    <label>排序</label>
                    <input type="number" name="sort" value="0" placeholder="数字越小越靠前">
                </div>
                <div class="form-group">
                    <label>状态</label>
                    <select name="status">
                        <option value="1">启用</option>
                        <option value="0">禁用</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>选择文件 *</label>
                    <input type="file" name="file" required>
                    <small>支持任意格式，最大100MB</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn">取消</button>
                <button type="submit" class="btn btn-primary">上传</button>
            </div>
        </form>
    </div>
</div>

<style>
.downloads-manager {
    max-width: 100%;
    overflow-x: auto;
}
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 15px;
}
.page-header h2 {
    font-size: 22px;
    font-weight: 600;
    margin: 0;
}
.search-bar {
    margin-bottom: 20px;
}
.search-bar form {
    display: flex;
    gap: 10px;
    max-width: 500px;
}
.search-bar input {
    flex: 1;
    padding: 10px 16px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    background: var(--bg-primary);
}
.table-wrapper {
    overflow-x: auto;
    background: var(--bg-primary);
    border-radius: 12px;
    border: 1px solid var(--border-color);
}
.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 800px;
}
.data-table th {
    padding: 14px 12px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
}
.data-table td {
    padding: 12px;
    border-bottom: 1px solid var(--border-color);
    font-size: 13px;
    vertical-align: middle;
}
.data-table tr:hover {
    background: var(--bg-secondary);
}
.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}
.action-btn {
    background: none;
    border: 1px solid var(--border-color);
    padding: 5px 12px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s;
}
.action-btn:hover {
    border-color: var(--primary-color);
    background: var(--primary-light);
}
.delete-btn:hover {
    border-color: var(--danger-color);
    color: var(--danger-color);
    background: #fee2e2;
}
.pagination {
    display: flex;
    gap: 8px;
    justify-content: center;
    margin-top: 20px;
}
.page-link {
    padding: 6px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    text-decoration: none;
    color: var(--text-primary);
    font-size: 13px;
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: 16px;
    width: 90%;
    max-width: 500px;
}
.modal-header {
    padding: 18px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    font-size: 18px;
    font-weight: 600;
    margin: 0;
}
.close {
    cursor: pointer;
    font-size: 24px;
    line-height: 1;
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px;
    border-top: 1px solid var(--border-color);
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}
.form-group {
    margin-bottom: 18px;
}
.form-group label {
    display: block;
    margin-bottom: 6px;
    font-weight: 500;
    font-size: 14px;
}
.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 10px 14px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    font-size: 14px;
    background: var(--bg-primary);
}
.form-group textarea {
    resize: vertical;
}
.form-group small {
    display: block;
    margin-top: 4px;
    font-size: 12px;
    color: var(--text-muted);
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    border: none;
    padding: 8px 20px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
}
.btn-primary:hover {
    background: var(--primary-hover);
}
.btn-secondary {
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    padding: 8px 20px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
}
.loading-spinner {
    display: inline-block;
    width: 14px;
    height: 14px;
    border: 2px solid #fff;
    border-radius: 50%;
    border-top-color: transparent;
    animation: spin 0.6s linear infinite;
    margin-right: 6px;
    vertical-align: middle;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}
code {
    background: var(--bg-secondary);
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
}
</style>

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

// 关闭弹窗
function closeModal() {
    document.getElementById('uploadModal').style.display = 'none';
}
document.querySelectorAll('.close, .cancel-btn').forEach(btn => {
    btn.addEventListener('click', 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;
        closeModal();
    })
    .catch(error => {
        console.error('错误:', error);
        window.showToast('网络错误', 'error');
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
        closeModal();
    });
});

// 切换状态（使用独立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 originalText = 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 = '启用';
                    this.innerHTML = '🟢 启用';
                    this.setAttribute('data-status', '1');
                } else {
                    statusSpan.className = 'status-badge status-inactive';
                    statusSpan.innerHTML = '禁用';
                    this.innerHTML = '🔴 禁用';
                    this.setAttribute('data-status', '0');
                }
                window.showToast('状态已更新', 'success');
            } else {
                window.showToast(data.message || '操作失败', 'error');
            }
            this.innerHTML = originalText;
            this.disabled = false;
        })
        .catch(error => {
            console.error('错误:', error);
            window.showToast('网络错误', 'error');
            this.innerHTML = originalText;
            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 originalText = 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.remove();
                window.showToast('删除成功', 'success');
                if (document.querySelectorAll('#downloadsTable tbody tr').length === 0) {
                    location.reload();
                }
            } else {
                window.showToast(data.message || '删除失败', 'error');
                this.innerHTML = originalText;
                this.disabled = false;
            }
        })
        .catch(error => {
            console.error('错误:', error);
            window.showToast('网络错误', 'error');
            this.innerHTML = originalText;
            this.disabled = false;
        });
    });
});
</script>