<?php
/**
 * HuSNS - 话题管理后台页面
 */

$totalTopics = count($topics);
$pinnedCount = count(array_filter($topics, function($t) { return !empty($t['is_pinned']); }));
$blockedCount = count(array_filter($topics, function($t) { return !empty($t['is_blocked']); }));
?>
<style>
.topic-page .stats-cards {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
    flex-wrap: wrap;
}
.topic-page .stats-cards .stat-card {
    flex: 1;
    min-width: 160px;
    background: #fff;
    padding: 15px 18px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    display: flex;
    align-items: center;
    gap: 12px;
}
.topic-page .stats-cards .stat-icon {
    width: 42px;
    height: 42px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    color: #fff;
    flex-shrink: 0;
}
.topic-page .stats-cards .stat-icon.bg-blue { background: #3498db; }
.topic-page .stats-cards .stat-icon.bg-warning { background: #f39c12; }
.topic-page .stats-cards .stat-icon.bg-danger { background: #e74c3c; }
.topic-page .stats-cards .stat-info {
    display: flex;
    flex-direction: column;
}
.topic-page .stats-cards .stat-value {
    font-size: 22px;
    font-weight: 600;
    color: #2c3e50;
    line-height: 1.2;
}
.topic-page .stats-cards .stat-label {
    font-size: 12px;
    color: #7f8c8d;
    margin-top: 2px;
}
.topic-page .topic-search-bar {
    background: #fff;
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 15px;
}
.topic-page .search-form-row {
    display: flex;
    gap: 20px;
    align-items: center;
    flex-wrap: wrap;
}
.topic-page .search-item {
    display: flex;
    align-items: center;
    gap: 8px;
}
.topic-page .search-item label {
    font-weight: 500;
    margin: 0;
    white-space: nowrap;
}
.topic-page .search-item input,
.topic-page .search-item select {
    padding: 6px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 13px;
}
.topic-page .search-item input[type="number"] {
    width: 70px;
}
.topic-page .search-item input[type="text"] {
    width: 160px;
}
.topic-page .search-item select {
    width: 100px;
}
.topic-page .admin-table {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
}
.topic-page .empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #999;
}
.topic-page .empty-state i {
    font-size: 48px;
    color: #ddd;
    margin-bottom: 10px;
    display: block;
}
.topic-page .empty-state p {
    margin: 0;
    font-size: 14px;
}
</style>
<div class="admin-content topic-page">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
        <h1><i class="fa fa-hashtag"></i> 话题管理</h1>
        <button class="btn btn-primary" id="btnAddTopic">
            <i class="fa fa-plus"></i> 添加人工热榜话题
        </button>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-cards">
        <div class="stat-card">
            <div class="stat-icon bg-blue"><i class="fa fa-hashtag"></i></div>
            <div class="stat-info">
                <span class="stat-value"><?php echo $totalTopics; ?></span>
                <span class="stat-label">话题总数</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-warning"><i class="fa fa-thumbtack"></i></div>
            <div class="stat-info">
                <span class="stat-value"><?php echo $pinnedCount; ?></span>
                <span class="stat-label">人工置顶</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-danger"><i class="fa fa-ban"></i></div>
            <div class="stat-info">
                <span class="stat-value"><?php echo $blockedCount; ?></span>
                <span class="stat-label">已屏蔽</span>
            </div>
        </div>
    </div>
    
    <!-- 设置和搜索区域 -->
    <div class="admin-search topic-search-bar">
        <form method="get" class="search-form-row">
            <input type="hidden" name="r" value="topic">
            <div class="search-item">
                <label>统计天数：</label>
                <input type="number" id="topicStatDays" value="<?php echo intval($statDays ?? 7); ?>" min="1" max="365">
                <button type="button" class="btn btn-primary" id="btnSaveStatDays"><i class="fa fa-save"></i> 保存</button>
            </div>
            <div class="search-item">
                <input type="text" name="keyword" value="<?php echo htmlspecialchars($keyword ?? ''); ?>" placeholder="搜索话题">
                <select name="status">
                    <option value="">全部状态</option>
                    <option value="pinned" <?php echo ($status ?? '') === 'pinned' ? 'selected' : ''; ?>>人工置顶</option>
                    <option value="blocked" <?php echo ($status ?? '') === 'blocked' ? 'selected' : ''; ?>>已屏蔽</option>
                    <option value="normal" <?php echo ($status ?? '') === 'normal' ? 'selected' : ''; ?>>正常</option>
                </select>
                <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> 搜索</button>
                <a href="?r=topic" class="btn btn-default"><i class="fa fa-refresh"></i> 重置</a>
            </div>
        </form>
    </div>
    
    <!-- 数据列表 -->
    <div class="admin-table">
        <?php if (empty($topics)): ?>
        <div class="empty-state">
            <i class="fa fa-hashtag"></i>
            <p>暂无话题数据</p>
        </div>
        <?php else: ?>
        <table class="table">
            <thead>
                <tr>
                    <th width="70">ID</th>
                    <th>话题名称</th>
                    <th width="80">动态数</th>
                    <th width="110">状态</th>
                    <th width="70">排序</th>
                    <th width="220">操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($topics as $topic): 
                    $topicId = isset($topic['id']) && $topic['id'] !== null ? $topic['id'] : '-';
                ?>
                <tr data-name="<?php echo htmlspecialchars($topic['name']); ?>">
                    <td><span class="badge badge-secondary"><?php echo $topicId; ?></span></td>
                    <td><strong>#<?php echo htmlspecialchars($topic['name']); ?>#</strong></td>
                    <td><?php echo intval($topic['count']); ?></td>
                    <td>
                        <?php if (!empty($topic['is_blocked'])): ?>
                        <span class="badge badge-warning"><i class="fa fa-ban"></i> 已屏蔽</span>
                        <?php elseif (!empty($topic['is_pinned'])): ?>
                        <span class="badge badge-warning"><i class="fa fa-thumbtack"></i> 人工置顶</span>
                        <?php else: ?>
                        <span class="badge badge-success"><i class="fa fa-check"></i> 正常</span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo intval($topic['sort_order']); ?></td>
                    <td>
                        <div class="btn-group">
                            <?php if (!empty($topic['is_blocked'])): ?>
                            <a href="javascript:void(0)" class="btn btn-sm btn-success" onclick="unblockTopic('<?php echo htmlspecialchars(addslashes($topic['name'])); ?>')"><i class="fa fa-check"></i> 取消屏蔽</a>
                            <?php else: ?>
                                <?php if (empty($topic['is_pinned'])): ?>
                                <a href="javascript:void(0)" class="btn btn-sm btn-default" onclick="pinTopic('<?php echo htmlspecialchars(addslashes($topic['name'])); ?>')"><i class="fa fa-thumbtack"></i> 置顶</a>
                                <?php else: ?>
                                <a href="javascript:void(0)" class="btn btn-sm btn-default" onclick="unpinTopic('<?php echo htmlspecialchars(addslashes($topic['name'])); ?>')"><i class="fa fa-times"></i> 取消置顶</a>
                                <?php endif; ?>
                                <a href="javascript:void(0)" class="btn btn-sm btn-danger" onclick="blockTopic('<?php echo htmlspecialchars(addslashes($topic['name'])); ?>')"><i class="fa fa-ban"></i> 屏蔽</a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <?php if (!empty($totalPages) && $totalPages > 1): ?>
        <div class="pagination-wrap">
            <ul class="pagination" style="margin:0;display:flex;justify-content:center;gap:5px;list-style:none;padding:0;">
                <?php if (($page ?? 1) > 1): ?>
                <li><a href="?r=topic&page=<?php echo $page - 1; ?>&keyword=<?php echo urlencode($keyword ?? ''); ?>&status=<?php echo htmlspecialchars($status ?? ''); ?>">«</a></li>
                <?php endif; ?>
                <?php for ($i = max(1, ($page ?? 1) - 2); $i <= min($totalPages, ($page ?? 1) + 2); $i++): ?>
                <li><a href="?r=topic&page=<?php echo $i; ?>&keyword=<?php echo urlencode($keyword ?? ''); ?>&status=<?php echo htmlspecialchars($status ?? ''); ?>" class="<?php echo ($page ?? 1) == $i ? 'active' : ''; ?>"><?php echo $i; ?></a></li>
                <?php endfor; ?>
                <?php if (($page ?? 1) < $totalPages): ?>
                <li><a href="?r=topic&page=<?php echo $page + 1; ?>&keyword=<?php echo urlencode($keyword ?? ''); ?>&status=<?php echo htmlspecialchars($status ?? ''); ?>">»</a></li>
                <?php endif; ?>
            </ul>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<!-- 添加弹窗 -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"><i class="fa fa-plus-circle text-primary"></i> 添加人工热榜话题</h4>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>话题名称</label>
                    <input type="text" id="topicName" class="form-control" placeholder="输入话题名称（可带#也可不带）">
                </div>
                <div class="form-group">
                    <label>排序权重</label>
                    <input type="number" id="topicSortOrder" value="0" min="0" class="form-control">
                    <small style="color:#999;">数字越小越靠前（仅人工置顶话题有效）</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="btnCreateTopic"><i class="fa fa-plus"></i> 添加</button>
            </div>
        </div>
    </div>
</div>

<script>
$(function() {
    // 确保 CSRF token 已初始化
    <?php if (!isset($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } ?>
    var csrf = '<?php echo $_SESSION['csrf_token']; ?>';
    
    // 提示
    function showMsg(msg) {
        alert(msg);
    }
    
    // AJAX 请求后刷新 CSRF token
    $(document).ajaxComplete(function(event, xhr, settings) {
        var token = xhr.getResponseHeader('X-CSRF-Token');
        if (token) {
            csrf = token;
        }
    });
    
    // 通用 AJAX 请求函数，自动处理 CSRF
    function apiPost(url, data, callback) {
        $.post(url, $.extend({csrf_token: csrf}, data), function(data) {
            if (data.code === 0) {
                // 成功后刷新 token
                csrf = data.csrf_token || csrf;
            }
            callback(data);
        }, 'json');
    }
    
    // 显示添加弹窗
    $('#btnAddTopic').click(function() {
        $('#addModal').modal('show');
    });
    
    // 保存统计天数
    $('#btnSaveStatDays').click(function() {
        var days = $('#topicStatDays').val();
        $.post('<?php echo $this->url("topic/saveStatDays"); ?>', {
            days: days,
            csrf_token: csrf
        }, function(data) {
            if (data.code === 0) {
                csrf = data.csrf_token || csrf;
                showMsg('保存成功');
            } else {
                showMsg(data.message || '保存失败');
            }
        }, 'json');
    });
    
    // 创建话题
    $('#btnCreateTopic').click(function() {
        var name = $('#topicName').val();
        var sortOrder = $('#topicSortOrder').val();
        
        if (!name.trim()) {
            showMsg('请输入话题名称');
            return;
        }
        
        $.post('<?php echo $this->url("topic/create"); ?>', {
            name: name,
            sort_order: sortOrder,
            csrf_token: csrf
        }, function(data) {
            if (data.code === 0) {
                csrf = data.csrf_token || csrf;
                showMsg('添加成功');
                location.reload();
            } else {
                showMsg(data.message || '添加失败');
            }
        }, 'json');
    });
    
    // 更新行状态
    window.updateRowStatus = function(row, isPinned, isBlocked) {
        var name = row.attr('data-name');
        var statusCell = row.find('td:nth-child(4)');
        var actionsCell = row.find('td:nth-child(6)');
        
        if (isBlocked) {
            statusCell.html('<span class="badge badge-warning"><i class="fa fa-ban"></i> 已屏蔽</span>');
            actionsCell.html('<div class="btn-group"><a href="javascript:void(0)" class="btn btn-sm btn-success" onclick="unblockTopic(\'' + name.replace(/'/g, "\\'") + '\')"><i class="fa fa-check"></i> 取消屏蔽</a></div>');
        } else if (isPinned) {
            statusCell.html('<span class="badge badge-warning"><i class="fa fa-thumbtack"></i> 人工置顶</span>');
            actionsCell.html('<div class="btn-group"><a href="javascript:void(0)" class="btn btn-sm btn-default" onclick="unpinTopic(\'' + name.replace(/'/g, "\\'") + '\')"><i class="fa fa-times"></i> 取消置顶</a> <a href="javascript:void(0)" class="btn btn-sm btn-danger" onclick="blockTopic(\'' + name.replace(/'/g, "\\'") + '\')"><i class="fa fa-ban"></i> 屏蔽</a></div>');
        } else {
            statusCell.html('<span class="badge badge-success"><i class="fa fa-check"></i> 正常</span>');
            actionsCell.html('<div class="btn-group"><a href="javascript:void(0)" class="btn btn-sm btn-default" onclick="pinTopic(\'' + name.replace(/'/g, "\\'") + '\')"><i class="fa fa-thumbtack"></i> 置顶</a> <a href="javascript:void(0)" class="btn btn-sm btn-danger" onclick="blockTopic(\'' + name.replace(/'/g, "\\'") + '\')"><i class="fa fa-ban"></i> 屏蔽</a></div>');
        }
    };
    
    window.pinTopic = function(name) {
        $.post('<?php echo $this->url("topic/pin"); ?>', {
            name: name,
            sort_order: 0,
            csrf_token: csrf
        }, function(data) {
            if (data.code === 0) {
                csrf = data.csrf_token || csrf;
                showMsg('置顶成功');
                updateRowStatus($('tr[data-name="' + name.replace(/"/g, '\\"') + '"]'), true, false);
            } else {
                showMsg(data.message || '置顶失败');
            }
        }, 'json');
    };
    
    window.unpinTopic = function(name) {
        $.post('<?php echo $this->url("topic/unpin"); ?>', {
            name: name,
            csrf_token: csrf
        }, function(data) {
            if (data.code === 0) {
                csrf = data.csrf_token || csrf;
                showMsg('取消置顶成功');
                updateRowStatus($('tr[data-name="' + name.replace(/"/g, '\\"') + '"]'), false, false);
            } else {
                showMsg(data.message || '取消置顶失败');
            }
        }, 'json');
    };
    
    window.blockTopic = function(name) {
        $.post('<?php echo $this->url("topic/block"); ?>', {
            name: name,
            csrf_token: csrf
        }, function(data) {
            if (data.code === 0) {
                csrf = data.csrf_token || csrf;
                showMsg('屏蔽成功');
                updateRowStatus($('tr[data-name="' + name.replace(/"/g, '\\"') + '"]'), false, true);
            } else {
                showMsg(data.message || '屏蔽失败');
            }
        }, 'json');
    };
    
    window.unblockTopic = function(name) {
        $.post('<?php echo $this->url("topic/unblock"); ?>', {
            name: name,
            csrf_token: csrf
        }, function(data) {
            if (data.code === 0) {
                csrf = data.csrf_token || csrf;
                showMsg('取消屏蔽成功');
                updateRowStatus($('tr[data-name="' + name.replace(/"/g, '\\"') + '"]'), false, false);
            } else {
                showMsg(data.message || '取消屏蔽失败');
            }
        }, 'json');
    };
});
</script>
