<?php
/**
 * HuSNS - 附件管理后台页面
 */
?>
<style>
.attachment-page .stats-row {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
    flex-wrap: wrap;
}
.attachment-page .stat-card {
    flex: 1;
    min-width: 80px;
    max-width: 120px;
    background: #fff;
    padding: 10px 12px;
    border-radius: 6px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.06);
    text-align: center;
}
.attachment-page .stat-card .stat-num {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
}
.attachment-page .stat-card .stat-label {
    font-size: 11px;
    color: #7f8c8d;
    margin-top: 3px;
}
.attachment-page .stat-card.warning .stat-num {
    color: #e67e22;
}
.attachment-page .stat-card.danger .stat-num {
    color: #e74c3c;
}
.attachment-page .stat-card.success .stat-num {
    color: #27ae60;
}
.attachment-page .filter-bar {
    background: #fff;
    padding: 15px 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
    align-items: center;
}
.attachment-page .filter-bar select,
.attachment-page .filter-bar input {
    padding: 8px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
}
.attachment-page .filter-bar input[type="text"] {
    width: 200px;
}
.attachment-page .filter-bar button {
    padding: 8px 16px;
    background: #3498db;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}
.attachment-page .filter-bar button:hover {
    background: #2980b9;
}
.attachment-page .filter-bar .btn-warning {
    background: #f39c12;
}
.attachment-page .filter-bar .btn-warning:hover {
    background: #e67e22;
}
.attachment-page .attachment-grid {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    overflow: hidden;
}
.attachment-page .attachment-list {
    list-style: none;
    padding: 0;
    margin: 0;
}
.attachment-page .attachment-item {
    display: flex;
    align-items: center;
    padding: 12px 20px;
    border-bottom: 1px solid #f5f5f5;
    transition: background 0.2s;
}
.attachment-page .attachment-item:last-child {
    border-bottom: none;
}
.attachment-page .attachment-item:hover {
    background: #f8f9fa;
}
.attachment-page .attachment-thumb {
    width: 50px;
    height: 50px;
    border-radius: 6px;
    margin-right: 15px;
    overflow: hidden;
    background: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}
.attachment-page .attachment-thumb img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.attachment-page .attachment-thumb .file-icon {
    font-size: 24px;
    color: #7f8c8d;
}
.attachment-page .attachment-thumb .video-icon {
    color: #e74c3c;
}
.attachment-page .attachment-thumb .attach-icon {
    color: #3498db;
}
.attachment-page .attachment-info {
    flex: 1;
    min-width: 0;
}
.attachment-page .attachment-name {
    font-weight: 600;
    color: #2c3e50;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.attachment-page .attachment-meta {
    font-size: 12px;
    color: #7f8c8d;
    margin-top: 3px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}
.attachment-page .attachment-meta .unused {
    color: #e74c3c;
    font-weight: 500;
}
.attachment-page .attachment-meta .used {
    color: #27ae60;
    font-weight: 500;
}
.attachment-page .attachment-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
}
.attachment-page .btn {
    padding: 6px 12px;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    font-size: 13px;
    transition: all 0.2s;
}
.attachment-page .btn-primary {
    background: #3498db;
    color: #fff;
}
.attachment-page .btn-primary:hover {
    background: #2980b9;
}
.attachment-page .btn-danger {
    background: #e74c3c;
    color: #fff;
}
.attachment-page .btn-danger:hover {
    background: #c0392b;
}
.attachment-page .btn-sm {
    padding: 4px 8px;
    font-size: 12px;
}
.attachment-page .pagination {
    display: flex;
    justify-content: center;
    padding: 20px;
    gap: 5px;
}
.attachment-page .pagination a,
.attachment-page .pagination span {
    padding: 6px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    text-decoration: none;
    color: #333;
    font-size: 13px;
}
.attachment-page .pagination a:hover {
    background: #f0f0f0;
}
.attachment-page .pagination .current {
    background: #3498db;
    color: #fff;
    border-color: #3498db;
}
.attachment-page .empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #7f8c8d;
}
.attachment-page .empty-state i {
    font-size: 48px;
    margin-bottom: 15px;
    display: block;
    color: #ddd;
}
.attachment-page .top-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}
.attachment-page .total-info {
    color: #7f8c8d;
    font-size: 13px;
}
.attachment-page .checkbox-cell {
    width: 40px;
    text-align: center;
}
.attachment-page .checkbox-cell input[type="checkbox"] {
    width: 18px;
    height: 18px;
    cursor: pointer;
}
.attachment-page .batch-actions {
    display: flex;
    gap: 10px;
    align-items: center;
}
.attachment-page .batch-actions label {
    display: flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
    color: #555;
    font-size: 13px;
}
.attachment-page .batch-actions input[type="checkbox"] {
    width: 16px;
    height: 16px;
    cursor: pointer;
}
</style>

<div class="attachment-page">
    <!-- 统计卡片 -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-num"><?php echo number_format($stats['total_count']); ?></div>
            <div class="stat-label">文件总数</div>
        </div>
        <div class="stat-card">
            <div class="stat-num"><?php echo AttachmentService::formatSize($stats['total_size']); ?></div>
            <div class="stat-label">总占用空间</div>
        </div>
        <div class="stat-card success">
            <div class="stat-num"><?php echo number_format($stats['used_count']); ?></div>
            <div class="stat-label">已使用文件</div>
        </div>
        <div class="stat-card danger">
            <div class="stat-num"><?php echo number_format($stats['unused_count']); ?></div>
            <div class="stat-label">未使用文件</div>
        </div>
        <div class="stat-card">
            <div class="stat-num"><?php echo number_format($stats['by_type']['images']['count']); ?></div>
            <div class="stat-label">图片</div>
        </div>
        <div class="stat-card">
            <div class="stat-num"><?php echo number_format($stats['by_type']['videos']['count']); ?></div>
            <div class="stat-label">视频</div>
        </div>
        <div class="stat-card">
            <div class="stat-num"><?php echo number_format($stats['by_type']['attachments']['count']); ?></div>
            <div class="stat-label">附件</div>
        </div>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
        <form method="get" action="<?php echo $baseUrl ?? '/'; ?>" style="display: flex; gap: 10px; flex-wrap: wrap; align-items: center;">
            <input type="hidden" name="r" value="admin/attachments">
            <select name="type" onchange="this.form.submit()">
                <option value="">全部类型</option>
                <option value="images" <?php echo $type === 'images' ? 'selected' : ''; ?>>图片</option>
                <option value="videos" <?php echo $type === 'videos' ? 'selected' : ''; ?>>视频</option>
                <option value="attachments" <?php echo $type === 'attachments' ? 'selected' : ''; ?>>附件</option>
            </select>
            <select name="used_status" onchange="this.form.submit()">
                <option value="">全部状态</option>
                <option value="1" <?php echo $usedStatus === 1 ? 'selected' : ''; ?>>已使用</option>
                <option value="0" <?php echo $usedStatus === 0 ? 'selected' : ''; ?>>未使用</option>
            </select>
            <input type="text" name="keyword" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="搜索文件名...">
            <button type="submit"><i class="fa fa-search"></i> 搜索</button>
            <a href="<?php echo $baseUrl ?? '/'; ?>?r=admin/attachments" class="btn" style="background: #95a5a6; color: #fff; padding: 8px 16px; border-radius: 4px; text-decoration: none;">
                <i class="fa fa-refresh"></i> 重置
            </a>
        </form>
        <div style="margin-left: auto; display: flex; gap: 10px; align-items: center;">
            <div class="batch-actions">
                <label>
                    <input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)">
                    全选
                </label>
            </div>
            <button class="btn btn-danger" onclick="deleteSelected()" style="display: none;" id="batchDeleteBtn">
                <i class="fa fa-trash"></i> 删除选中 (<span id="selectedCount">0</span>)
            </button>
            <button class="btn btn-warning" onclick="deleteUnused()">
                <i class="fa fa-trash-o"></i> 清理未使用文件
            </button>
        </div>
    </div>
    
    <!-- 文件列表 -->
    <div class="attachment-grid">
        <?php if (!empty($attachments)): ?>
        <div class="top-actions">
            <span class="total-info">共找到 <?php echo number_format($total); ?> 个文件</span>
        </div>
        <ul class="attachment-list">
            <?php foreach ($attachments as $file): ?>
            <li class="attachment-item" data-path="<?php echo htmlspecialchars($file['path']); ?>">
                <div class="checkbox-cell">
                    <input type="checkbox" class="file-checkbox" value="<?php echo htmlspecialchars($file['path']); ?>" onchange="updateBatchButton()">
                </div>
                <div class="attachment-thumb">
                    <?php if ($file['type'] === 'images'): ?>
                    <img src="<?php echo Helper::uploadUrl($file['path']); ?>" alt="" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                    <span class="file-icon" style="display: none;"><i class="fa fa-image"></i></span>
                    <?php elseif ($file['type'] === 'videos'): ?>
                    <span class="file-icon video-icon"><i class="fa fa-video-camera"></i></span>
                    <?php else: ?>
                    <span class="file-icon attach-icon"><i class="fa fa-paperclip"></i></span>
                    <?php endif; ?>
                </div>
                <div class="attachment-info">
                    <div class="attachment-name" title="<?php echo htmlspecialchars($file['path']); ?>">
                        <?php echo htmlspecialchars($file['filename']); ?>
                    </div>
                    <div class="attachment-meta">
                        <span><?php echo htmlspecialchars($file['path']); ?></span>
                        <span>|</span>
                        <span><?php echo AttachmentService::formatSize($file['size']); ?></span>
                        <span>|</span>
                        <span><?php echo date('Y-m-d H:i', $file['mtime']); ?></span>
                        <span>|</span>
                        <?php if ($file['is_used']): ?>
                        <span class="used"><i class="fa fa-check-circle"></i> 已使用</span>
                        <?php else: ?>
                        <span class="unused"><i class="fa fa-times-circle"></i> 未使用</span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="attachment-actions">
                    <a href="<?php echo Helper::uploadUrl($file['path']); ?>" target="_blank" class="btn btn-primary btn-sm">
                        <i class="fa fa-eye"></i> 查看
                    </a>
                    <button class="btn btn-danger btn-sm" onclick="deleteFile('<?php echo htmlspecialchars($file['path']); ?>')">
                        <i class="fa fa-trash"></i> 删除
                    </button>
                </div>
            </li>
            <?php endforeach; ?>
        </ul>
        <?php else: ?>
        <div class="empty-state">
            <i class="fa fa-folder-open"></i>
            <p>暂无文件</p>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- 分页 -->
    <?php
    $paginationBase = ($baseUrl ?? '/') . '?r=admin/attachments';
    $paginationParams = '';
    if ($type) $paginationParams .= '&type=' . urlencode($type);
    if ($usedStatus !== null) $paginationParams .= '&used_status=' . $usedStatus;
    if ($keyword) $paginationParams .= '&keyword=' . urlencode($keyword);
    ?>
    <?php if ($totalPages > 1): ?>
    <div class="pagination">
        <?php if ($page > 1): ?>
        <a href="<?php echo $paginationBase . '&page=' . ($page - 1) . $paginationParams; ?>">上一页</a>
        <?php endif; ?>

        <?php
        $start = max(1, $page - 2);
        $end = min($totalPages, $page + 2);
        if ($start > 1): ?>
        <a href="<?php echo $paginationBase . '&page=1' . $paginationParams; ?>">1</a>
        <?php if ($start > 2): ?>
        <span>...</span>
        <?php endif; ?>
        <?php endif; ?>

        <?php for ($i = $start; $i <= $end; $i++): ?>
        <?php if ($i == $page): ?>
        <span class="current"><?php echo $i; ?></span>
        <?php else: ?>
        <a href="<?php echo $paginationBase . '&page=' . $i . $paginationParams; ?>"><?php echo $i; ?></a>
        <?php endif; ?>
        <?php endfor; ?>

        <?php if ($end < $totalPages): ?>
        <?php if ($end < $totalPages - 1): ?>
        <span>...</span>
        <?php endif; ?>
        <a href="<?php echo $paginationBase . '&page=' . $totalPages . $paginationParams; ?>"><?php echo $totalPages; ?></a>
        <?php endif; ?>

        <?php if ($page < $totalPages): ?>
        <a href="<?php echo $paginationBase . '&page=' . ($page + 1) . $paginationParams; ?>">下一页</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<script>
function deleteFile(path) {
    if (!confirm('确定要删除文件 "' + path + '" 吗？此操作不可恢复！')) {
        return;
    }
    
    // 创建隐藏表单提交
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = '<?php echo $baseUrl ?? '/'; ?>';
    
    var rInput = document.createElement('input');
    rInput.type = 'hidden';
    rInput.name = 'r';
    rInput.value = 'admin/attachment-delete';
    form.appendChild(rInput);
    
    var pathInput = document.createElement('input');
    pathInput.type = 'hidden';
    pathInput.name = 'path';
    pathInput.value = path;
    form.appendChild(pathInput);
    
    var csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = 'csrf_token';
    csrfInput.value = '<?php echo $_SESSION['csrf_token']; ?>';
    form.appendChild(csrfInput);
    
    document.body.appendChild(form);
    form.submit();
}

function deleteUnused() {
    if (!confirm('确定要删除所有未使用的附件吗？此操作不可恢复！\n\n建议：可以在删除前先筛选查看未使用文件，确认后再执行删除。')) {
        return;
    }
    
    var olderThanDays = prompt('请输入保留天数（0表示删除所有未使用文件）：\n\n例如输入 7 表示只删除7天前创建的未使用文件', '0');
    
    if (olderThanDays === null) {
        return;
    }
    
    olderThanDays = parseInt(olderThanDays) || 0;
    
    // 创建隐藏表单提交
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = '<?php echo $baseUrl ?? '/'; ?>';
    
    var rInput = document.createElement('input');
    rInput.type = 'hidden';
    rInput.name = 'r';
    rInput.value = 'admin/attachment-delete-unused';
    form.appendChild(rInput);
    
    var typeInput = document.createElement('input');
    typeInput.type = 'hidden';
    typeInput.name = 'type';
    typeInput.value = '<?php echo $type ?: ''; ?>';
    form.appendChild(typeInput);
    
    var daysInput = document.createElement('input');
    daysInput.type = 'hidden';
    daysInput.name = 'older_than_days';
    daysInput.value = olderThanDays;
    form.appendChild(daysInput);
    
    var csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = 'csrf_token';
    csrfInput.value = '<?php echo $_SESSION['csrf_token']; ?>';
    form.appendChild(csrfInput);
    
    document.body.appendChild(form);
    form.submit();
}

// 多选功能
function toggleSelectAll(checkbox) {
    var checkboxes = document.querySelectorAll('.file-checkbox');
    checkboxes.forEach(function(cb) {
        cb.checked = checkbox.checked;
    });
    updateBatchButton();
}

function updateBatchButton() {
    var checkboxes = document.querySelectorAll('.file-checkbox:checked');
    var count = checkboxes.length;
    var btn = document.getElementById('batchDeleteBtn');
    var countSpan = document.getElementById('selectedCount');
    
    if (countSpan) {
        countSpan.textContent = count;
    }
    
    if (btn) {
        btn.style.display = count > 0 ? 'inline-block' : 'none';
    }
}

function deleteSelected() {
    var checkboxes = document.querySelectorAll('.file-checkbox:checked');
    if (checkboxes.length === 0) {
        alert('请先选择要删除的文件');
        return;
    }
    
    if (!confirm('确定要删除选中的 ' + checkboxes.length + ' 个文件吗？此操作不可恢复！')) {
        return;
    }
    
    // 创建隐藏表单提交
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = '<?php echo $baseUrl ?? '/'; ?>';
    
    var rInput = document.createElement('input');
    rInput.type = 'hidden';
    rInput.name = 'r';
    rInput.value = 'admin/attachment-delete-batch';
    form.appendChild(rInput);
    
    var pathsInput = document.createElement('input');
    pathsInput.type = 'hidden';
    pathsInput.name = 'paths';
    var paths = [];
    checkboxes.forEach(function(cb) {
        paths.push(cb.value);
    });
    pathsInput.value = JSON.stringify(paths);
    form.appendChild(pathsInput);
    
    var csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = 'csrf_token';
    csrfInput.value = '<?php echo $_SESSION['csrf_token']; ?>';
    form.appendChild(csrfInput);
    
    document.body.appendChild(form);
    form.submit();
}
</script>