<?php
/**
 * 管理员专用 - 资源下载
 * 访问路径: /admin.php?page=resources
 */
if (!defined('IN_ADMIN')) {
    define('IN_ADMIN', true);
}
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../includes/LicenseClient.php';

// 权限检查：仅管理员可访问
if (!isAdmin()) {
    redirect(SITE_URL . 'admin.php');
}

$user = currentUser();

// 获取资源列表
$resources = [];
$error = '';
$categories = [];

try {
    $client = new LicenseClient();
    $result = $client->getResources();
    $resources = $result['resources'] ?? [];
    
    // 提取分类
    foreach ($resources as $res) {
        if (!empty($res['category'])) {
            $categories[$res['category']] = true;
        }
    }
    $categories = array_keys($categories);
} catch (Exception $e) {
    $error = $e->getMessage();
}

// SVG 图标
$svg_icons = [
    'resource'  => 'https://api.iconify.design/mdi:package-variant.svg?color=%23667eea',
    'download'  => 'https://api.iconify.design/mdi:download.svg?color=white',
    'php'       => 'https://api.iconify.design/mdi:language-php.svg?color=%23777bb4',
    'zip'       => 'https://api.iconify.design/mdi:folder-zip.svg?color=%23f59e0b',
    'doc'       => 'https://api.iconify.design/mdi:file-document.svg?color=%233b82f6',
    'other'     => 'https://api.iconify.design/mdi:file.svg?color=%236b7280',
    'search'    => 'https://api.iconify.design/mdi:magnify.svg?color=%236b7280',
    'filter'    => 'https://api.iconify.design/mdi:filter-variant.svg?color=%236b7280',
    'error'     => 'https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444',
    'empty'     => 'https://api.iconify.design/mdi:inbox.svg?color=%239ca3af',
];

// 根据文件类型获取图标
function getFileIcon($file_name, $icons) {
    $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $iconMap = [
        'php' => $icons['php'],
        'zip' => $icons['zip'],
        'doc' => $icons['doc'],
        'docx' => $icons['doc'],
        'pdf' => $icons['doc'],
        'txt' => $icons['doc'],
    ];
    return $iconMap[$ext] ?? $icons['other'];
}
?>

<h2 class="page-title">
    <img src="<?php echo $svg_icons['resource']; ?>" alt="" style="width:28px;height:28px;">
    资源下载
</h2>

<?php if ($error): ?>
<div class="alert alert-error">
    <img src="<?php echo $svg_icons['error']; ?>" alt="" style="width:20px;">
    <?php echo htmlspecialchars($error); ?>
</div>
<?php else: ?>

<!-- 筛选栏 -->
<div class="filter-bar">
    <div class="filter-tabs">
        <span class="filter-tab active" data-category="">全部资源</span>
        <?php foreach ($categories as $cat): ?>
        <span class="filter-tab" data-category="<?php echo htmlspecialchars($cat); ?>">
            <?php echo htmlspecialchars($cat); ?>
        </span>
        <?php endforeach; ?>
    </div>
    <div class="search-box">
        <img src="<?php echo $svg_icons['search']; ?>" alt="">
        <input type="text" id="searchInput" placeholder="搜索资源...">
    </div>
</div>

<!-- 资源网格 -->
<div class="resources-grid" id="resourcesGrid">
    <?php if (empty($resources)): ?>
    <div class="empty-state">
        <img src="<?php echo $svg_icons['empty']; ?>" alt="" style="width:80px;">
        <h3>暂无资源</h3>
        <p>管理员暂未上传任何资源</p>
    </div>
    <?php else: ?>
    <?php foreach ($resources as $res): ?>
    <div class="resource-card" data-category="<?php echo htmlspecialchars($res['category']); ?>" data-title="<?php echo htmlspecialchars($res['title']); ?>">
        <div class="resource-icon">
            <img src="<?php echo getFileIcon($res['file_name'], $svg_icons); ?>" alt="">
        </div>
        <div class="resource-info">
            <h4><?php echo htmlspecialchars($res['title']); ?></h4>
            <?php if ($res['description']): ?>
            <p><?php echo htmlspecialchars(mb_substr($res['description'], 0, 50)) . (mb_strlen($res['description']) > 50 ? '...' : ''); ?></p>
            <?php endif; ?>
            <div class="resource-meta">
                <?php if ($res['version']): ?>
                <span class="version-badge">v<?php echo htmlspecialchars($res['version']); ?></span>
                <?php endif; ?>
                <span class="size-badge"><?php echo htmlspecialchars($res['file_size']); ?></span>
                <span class="download-count">
                    <img src="https://api.iconify.design/mdi:download.svg?color=%239ca3af" alt="" style="width:14px;">
                    <?php echo number_format($res['download_count']); ?>
                </span>
            </div>
        </div>
        <div class="resource-action">
            <a href="/api/download_resource.php?id=<?php echo $res['id']; ?>" class="download-btn" data-id="<?php echo $res['id']; ?>">
                <img src="<?php echo $svg_icons['download']; ?>" alt="">
                下载
            </a>
            <span class="resource-date"><?php echo date('m-d', strtotime($res['created_at'])); ?></span>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

<style>
.page-title {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 28px;
    font-size: 24px;
    font-weight: 700;
    color: var(--text-primary);
}

.filter-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 28px;
    flex-wrap: wrap;
    gap: 16px;
}

.filter-tabs {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.filter-tab {
    padding: 8px 18px;
    background: var(--bg-secondary);
    border-radius: 30px;
    font-size: 14px;
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}

.filter-tab:hover {
    background: var(--bg-primary);
    border-color: var(--border-color);
}

.filter-tab.active {
    background: #667eea;
    color: white;
}

.search-box {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 18px;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 40px;
    width: 260px;
}

.search-box img {
    width: 18px;
    height: 18px;
    opacity: 0.6;
}

.search-box input {
    border: none;
    background: transparent;
    outline: none;
    font-size: 14px;
    width: 100%;
    color: var(--text-primary);
}

.resources-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
}

.resource-card {
    background: var(--bg-primary);
    border-radius: 18px;
    padding: 24px;
    border: 1px solid var(--border-color);
    display: flex;
    align-items: flex-start;
    gap: 16px;
    transition: all 0.2s;
}

.resource-card:hover {
    box-shadow: var(--shadow-md);
    border-color: transparent;
    transform: translateY(-2px);
}

.resource-icon {
    width: 52px;
    height: 52px;
    background: var(--bg-secondary);
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.resource-icon img {
    width: 30px;
    height: 30px;
}

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

.resource-info h4 {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 6px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.resource-info p {
    font-size: 13px;
    color: var(--text-secondary);
    margin-bottom: 10px;
    line-height: 1.4;
}

.resource-meta {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.version-badge {
    background: #e0f2fe;
    color: #0284c7;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 500;
}

.size-badge {
    color: var(--text-muted);
    font-size: 12px;
}

.download-count {
    display: flex;
    align-items: center;
    gap: 4px;
    color: var(--text-muted);
    font-size: 12px;
}

.resource-action {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 8px;
    flex-shrink: 0;
}

.download-btn {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 8px 18px;
    background: #667eea;
    color: white;
    border-radius: 30px;
    text-decoration: none;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.2s;
}

.download-btn:hover {
    background: #5a67d8;
    transform: scale(1.02);
}

.download-btn img {
    width: 18px;
    height: 18px;
    filter: brightness(0) invert(1);
}

.resource-date {
    font-size: 11px;
    color: var(--text-muted);
}

.empty-state {
    grid-column: 1 / -1;
    text-align: center;
    padding: 60px 20px;
}

.empty-state img {
    opacity: 0.4;
    margin-bottom: 20px;
}

.empty-state h3 {
    font-size: 18px;
    color: var(--text-primary);
    margin-bottom: 8px;
}

.empty-state p {
    color: var(--text-secondary);
}

.alert {
    padding: 16px 20px;
    border-radius: 14px;
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.alert-error {
    background: #fee2e2;
    color: #dc2626;
}

@media (max-width: 768px) {
    .filter-bar {
        flex-direction: column;
        align-items: stretch;
    }
    
    .search-box {
        width: 100%;
    }
    
    .resources-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const filterTabs = document.querySelectorAll('.filter-tab');
    const searchInput = document.getElementById('searchInput');
    const cards = document.querySelectorAll('.resource-card');
    
    // 分类筛选
    filterTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            filterTabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            filterResources();
        });
    });
    
    // 搜索
    if (searchInput) {
        searchInput.addEventListener('input', filterResources);
    }
    
    function filterResources() {
        const activeTab = document.querySelector('.filter-tab.active');
        const category = activeTab ? activeTab.dataset.category : '';
        const searchTerm = searchInput ? searchInput.value.toLowerCase() : '';
        
        let visibleCount = 0;
        cards.forEach(card => {
            const cardCategory = card.dataset.category;
            const cardTitle = card.dataset.title.toLowerCase();
            
            const categoryMatch = !category || cardCategory === category;
            const searchMatch = !searchTerm || cardTitle.includes(searchTerm);
            
            if (categoryMatch && searchMatch) {
                card.style.display = 'flex';
                visibleCount++;
            } else {
                card.style.display = 'none';
            }
        });
        
        // 显示空状态
        const grid = document.getElementById('resourcesGrid');
        const emptyState = grid.querySelector('.empty-state');
        if (visibleCount === 0 && !emptyState) {
            const emptyDiv = document.createElement('div');
            emptyDiv.className = 'empty-state';
            emptyDiv.innerHTML = `
                <img src="https://api.iconify.design/mdi:file-search.svg?color=%239ca3af" style="width:80px;">
                <h3>没有找到资源</h3>
                <p>尝试更换筛选条件或搜索关键词</p>
            `;
            grid.appendChild(emptyDiv);
        } else if (visibleCount > 0 && emptyState) {
            emptyState.remove();
        }
    }
});
</script>
<?php endif; ?>