<?php
ob_start();
requireAdmin();



// ========== 获取列表 ==========
$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 15;
$type_filter = isset($_GET['type']) ? $_GET['type'] : '';

$where = "1=1";
if ($type_filter) {
    $where .= " AND type = '$type_filter'";
}

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

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

// 统计数据
$stats = [
    'total' => $db->fetchOne("SELECT COUNT(*) as cnt FROM announcements")['cnt'],
    'active' => $db->fetchOne("SELECT COUNT(*) as cnt FROM announcements WHERE status = 1")['cnt'],
    'inactive' => $db->fetchOne("SELECT COUNT(*) as cnt FROM announcements WHERE status = 0")['cnt'],
    'valid' => $db->fetchOne("SELECT COUNT(*) as cnt FROM announcements WHERE status = 1 AND (start_time IS NULL OR start_time <= NOW()) AND (end_time IS NULL OR end_time >= NOW())")['cnt'],
];
?>

<div class="announcements-manager">
    <!-- 页面头部 -->
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:bullhorn.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            公告管理
        </h2>
        <button class="btn btn-primary" id="showAddModalBtn">
            <img src="https://api.iconify.design/mdi:plus.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
            添加公告
        </button>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:bullhorn.svg?color=%23667eea" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-total"><?php echo $stats['total']; ?></span>
                <span class="stat-label">总公告数</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-active"><?php echo $stats['active']; ?></span>
                <span class="stat-label">已启用</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:close-circle.svg?color=%23ef4444" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-inactive"><?php echo $stats['inactive']; ?></span>
                <span class="stat-label">已禁用</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:clock-check.svg?color=%23f59e0b" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-valid"><?php echo $stats['valid']; ?></span>
                <span class="stat-label">有效公告</span>
            </div>
        </div>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
        <div class="filter-tabs">
            <a href="?page=announcements" class="filter-tab <?php echo $type_filter == '' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:bullhorn.svg?color=<?php echo $type_filter == '' ? 'white' : '%236b7280'; ?>" width="16" height="16" alt="">
                全部
                <span class="count"><?php echo $stats['total']; ?></span>
            </a>
            <a href="?page=announcements&type=user_dashboard" class="filter-tab <?php echo $type_filter == 'user_dashboard' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:view-dashboard.svg?color=<?php echo $type_filter == 'user_dashboard' ? 'white' : '%236b7280'; ?>" width="16" height="16" alt="">
                用户仪表盘
            </a>
            <a href="?page=announcements&type=user_register" class="filter-tab <?php echo $type_filter == 'user_register' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:account-plus.svg?color=<?php echo $type_filter == 'user_register' ? 'white' : '%236b7280'; ?>" width="16" height="16" alt="">
                注册页面
            </a>
            <a href="?page=announcements&type=user_buy" class="filter-tab <?php echo $type_filter == 'user_buy' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:cart.svg?color=<?php echo $type_filter == 'user_buy' ? 'white' : '%236b7280'; ?>" width="16" height="16" alt="">
                购买页面
            </a>
            <a href="?page=announcements&type=admin" class="filter-tab <?php echo $type_filter == 'admin' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:shield-account.svg?color=<?php echo $type_filter == 'admin' ? 'white' : '%236b7280'; ?>" width="16" height="16" alt="">
                管理员后台
            </a>
        </div>
    </div>
    
    <!-- 公告列表 -->
    <div class="table-wrapper">
        <table class="data-table" id="announcementsTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>标题</th>
                    <th>类型</th>
                    <th>位置</th>
                    <th>优先级</th>
                    <th>有效期</th>
                    <th>状态</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($announcements)): ?>
                    <tr>
                        <td colspan="9">
                            <div class="empty-state">
                                <img src="https://api.iconify.design/mdi:bullhorn-outline.svg?color=%239ca3af" width="48" height="48" alt="">
                                <p>暂无公告</p>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($announcements as $item): ?>
                        <tr id="announce-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:bullhorn.svg?color=%23667eea" width="16" height="16" alt="">
                                    <strong><?php echo htmlspecialchars($item['title']); ?></strong>
                                </div>
                            </td>
                            <td>
                                <?php 
                                $type_map = [
                                    'user_dashboard' => ['icon' => 'view-dashboard', 'label' => '用户仪表盘', 'color' => '667eea'],
                                    'user_register' => ['icon' => 'account-plus', 'label' => '注册页面', 'color' => '10b981'],
                                    'user_buy' => ['icon' => 'cart', 'label' => '购买页面', 'color' => 'f59e0b'],
                                    'admin' => ['icon' => 'shield-account', 'label' => '管理员后台', 'color' => '8b5cf6']
                                ];
                                $t = $type_map[$item['type']] ?? ['icon' => 'circle', 'label' => $item['type'], 'color' => '6b7280'];
                                ?>
                                <span class="type-badge" style="background: #<?php echo $t['color']; ?>15; color: #<?php echo $t['color']; ?>;">
                                    <img src="https://api.iconify.design/mdi:<?php echo $t['icon']; ?>.svg?color=%23<?php echo $t['color']; ?>" width="12" height="12" alt="">
                                    <?php echo $t['label']; ?>
                                </span>
                            </td>
                            <td>
                                <?php 
                                $position_map = [
                                    'popup' => ['icon' => 'window-maximize', 'label' => '弹窗'],
                                    'banner' => ['icon' => 'image', 'label' => '横幅'],
                                    'sidebar' => ['icon' => 'dock-right', 'label' => '侧边栏']
                                ];
                                $p = $position_map[$item['position']] ?? ['icon' => 'circle', 'label' => $item['position']];
                                ?>
                                <span class="position-badge">
                                    <img src="https://api.iconify.design/mdi:<?php echo $p['icon']; ?>.svg?color=%236b7280" width="12" height="12" alt="">
                                    <?php echo $p['label']; ?>
                                </span>
                            </td>
                            <td><span class="priority-badge"><?php echo $item['priority']; ?></span></td>
                            <td id="validity-<?php echo $item['id']; ?>">
                                <?php 
                                $valid = true;
                                if ($item['start_time'] && strtotime($item['start_time']) > time()) $valid = false;
                                if ($item['end_time'] && strtotime($item['end_time']) < time()) $valid = false;
                                ?>
                                <?php if ($valid): ?>
                                    <span class="validity-badge valid">
                                        <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="12" height="12" alt="">
                                        有效
                                    </span>
                                <?php else: ?>
                                    <span class="validity-badge expired">
                                        <img src="https://api.iconify.design/mdi:clock-alert.svg?color=%23ef4444" width="12" height="12" alt="">
                                        已过期
                                    </span>
                                <?php endif; ?>
                            </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><?php echo date('Y-m-d H:i', strtotime($item['created_at'])); ?></td>
                            <td class="action-buttons" id="action-buttons-<?php echo $item['id']; ?>">
                                <button class="action-btn edit-btn" data-id="<?php echo $item['id']; ?>" title="编辑">
                                    <img src="https://api.iconify.design/mdi:pencil.svg?color=%23667eea" width="16" height="16" alt="">
                                </button>
                                <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=announcements&p=<?php echo $page - 1; ?>&type=<?php echo $type_filter; ?>" 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=announcements&p=1&type=<?php echo $type_filter; ?>" 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=announcements&p=<?php echo $i; ?>&type=<?php echo $type_filter; ?>" 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=announcements&p=<?php echo $total_pages; ?>&type=<?php echo $type_filter; ?>" class="page-link"><?php echo $total_pages; ?></a>
            <?php endif; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=announcements&p=<?php echo $page + 1; ?>&type=<?php echo $type_filter; ?>" 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="announceModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">
                <img src="https://api.iconify.design/mdi:bullhorn.svg?color=%23667eea" width="20" height="20" style="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="announceForm">
            <input type="hidden" name="id" id="announce_id">
            <div class="modal-body">
                <div class="form-row">
                    <div class="form-group" style="flex:2">
                        <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" id="announce_title" required placeholder="请输入公告标题">
                    </div>
                    <div class="form-group" style="flex:1">
                        <label>
                            <img src="https://api.iconify.design/mdi:tag.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            类型
                        </label>
                        <select name="type" id="announce_type">
                            <option value="user_dashboard">用户仪表盘</option>
                            <option value="user_register">注册页面</option>
                            <option value="user_buy">购买页面</option>
                            <option value="admin">管理员后台</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group" style="flex:1">
                        <label>
                            <img src="https://api.iconify.design/mdi:monitor.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            展示位置
                        </label>
                        <select name="position" id="announce_position">
                            <option value="popup">弹窗</option>
                            <option value="banner">横幅</option>
                            <option value="sidebar">侧边栏</option>
                        </select>
                    </div>
                    <div class="form-group" style="flex:1">
                        <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="priority" id="announce_priority" value="0">
                    </div>
                    <div class="form-group" style="flex:1">
                        <label>
                            <img src="https://api.iconify.design/mdi:refresh.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            显示频率
                        </label>
                        <select name="show_frequency" id="announce_frequency">
                            <option value="0">每次访问</option>
                            <option value="1">每天一次</option>
                            <option value="2">仅一次</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group" style="flex:1">
                        <label>
                            <img src="https://api.iconify.design/mdi:calendar-start.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            开始时间
                        </label>
                        <input type="datetime-local" name="start_time" id="announce_start">
                    </div>
                    <div class="form-group" style="flex:1">
                        <label>
                            <img src="https://api.iconify.design/mdi:calendar-end.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            结束时间
                        </label>
                        <input type="datetime-local" name="end_time" id="announce_end">
                    </div>
                </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="">
                        内容（支持HTML）
                    </label>
                    <textarea name="content" id="announce_content" rows="8" placeholder="请输入公告内容，支持HTML..."></textarea>
                </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" id="announce_status">
                        <option value="1">启用</option>
                        <option value="0">禁用</option>
                    </select>
                </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:content-save.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);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

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

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

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}
.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);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
}

/* 统计卡片 */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 24px;
}
.stat-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 20px;
    border: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.2s;
    box-shadow: var(--shadow-sm);
}
.stat-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}
.stat-icon {
    width: 52px;
    height: 52px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
}
.stat-content {
    display: flex;
    flex-direction: column;
}
.stat-value {
    font-size: 26px;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.2;
}
.stat-label {
    font-size: 13px;
    color: var(--text-muted);
    margin-top: 4px;
}

/* 筛选标签 */
.filter-bar {
    margin-bottom: 24px;
}
.filter-tabs {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}
.filter-tab {
    display: inline-flex;
    align-items: center;
    padding: 10px 18px;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 30px;
    font-size: 14px;
    font-weight: 500;
    color: var(--text-secondary);
    text-decoration: none;
    transition: all 0.2s;
}
.filter-tab:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.filter-tab.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.filter-tab .count {
    margin-left: 6px;
    padding: 2px 8px;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 20px;
    font-size: 12px;
}
.filter-tab.active .count {
    background: rgba(255, 255, 255, 0.2);
}

/* 表格 */
.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 14px;
    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 14px;
    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: center;
    gap: 8px;
}
.type-badge, .position-badge, .validity-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 10px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
}
.priority-badge {
    font-weight: 600;
    color: var(--primary-color);
}
.validity-badge.valid {
    background: #d1fae5;
    color: #065f46;
}
.validity-badge.expired {
    background: #fee2e2;
    color: #991b1b;
}

/* 状态徽章 */
.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;
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.status-inactive .status-dot {
    background: #ef4444;
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    gap: 6px;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    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);
    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 {
    color: var(--text-muted);
    font-size: 15px;
    margin: 0;
}

/* 分页 */
.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-ellipsis {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    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;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    width: 90%;
    max-width: 700px;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: var(--shadow-lg);
}
.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;
}
.modal-close {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: var(--radius-sm);
    transition: background 0.2s;
    display: flex;
}
.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;
    border-top: 1px solid var(--border-color);
}
.form-row {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
}
.form-group {
    margin-bottom: 16px;
    flex: 1;
}
.form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
}
.required {
    color: var(--danger-color);
    margin-left: 2px;
}
.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 10px 14px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 14px;
    background: var(--bg-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);
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(102, 126, 234, 0.3);
    border-radius: 50%;
    border-top-color: var(--primary-color);
    animation: spin 0.6s linear infinite;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}

/* 响应式 */
@media (max-width: 1024px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    .form-row {
        flex-direction: column;
        gap: 0;
    }
    .filter-tabs {
        flex-direction: column;
    }
    .filter-tab {
        justify-content: center;
    }
}
</style>

<script>
// 更新统计卡片
function updateStatsDisplay(oldStatus, newStatus, isDelete = false) {
    const statTotal = document.getElementById('stat-total');
    const statActive = document.getElementById('stat-active');
    const statInactive = document.getElementById('stat-inactive');
    
    if (isDelete) {
        if (statTotal) {
            let count = parseInt(statTotal.innerText) || 0;
            statTotal.innerText = Math.max(0, count - 1);
        }
        if (oldStatus === 1 && statActive) {
            let count = parseInt(statActive.innerText) || 0;
            statActive.innerText = Math.max(0, count - 1);
        } else if (oldStatus === 0 && statInactive) {
            let count = parseInt(statInactive.innerText) || 0;
            statInactive.innerText = Math.max(0, count - 1);
        }
    } else {
        if (oldStatus === 1 && statActive) {
            let count = parseInt(statActive.innerText) || 0;
            statActive.innerText = Math.max(0, count - 1);
        } else if (oldStatus === 0 && statInactive) {
            let count = parseInt(statInactive.innerText) || 0;
            statInactive.innerText = Math.max(0, count - 1);
        }
        if (newStatus === 1 && statActive) {
            let count = parseInt(statActive.innerText) || 0;
            statActive.innerText = count + 1;
        } else if (newStatus === 0 && statInactive) {
            let count = parseInt(statInactive.innerText) || 0;
            statInactive.innerText = count + 1;
        }
    }
}

const modal = document.getElementById('announceModal');
const form = document.getElementById('announceForm');

function openModal(data) {
    document.getElementById('modalTitle').innerHTML = '<img src="https://api.iconify.design/mdi:' + (data && !data.error ? 'pencil' : 'plus') + '.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">' + (data && !data.error ? '编辑公告' : '添加公告');
    document.getElementById('announce_id').value = data?.id || '';
    document.getElementById('announce_title').value = data?.title || '';
    document.getElementById('announce_type').value = data?.type || 'user_dashboard';
    document.getElementById('announce_position').value = data?.position || 'popup';
    document.getElementById('announce_priority').value = data?.priority || 0;
    document.getElementById('announce_frequency').value = data?.show_frequency || 0;
    document.getElementById('announce_start').value = data?.start_time ? data.start_time.replace(' ', 'T').slice(0, 16) : '';
    document.getElementById('announce_end').value = data?.end_time ? data.end_time.replace(' ', 'T').slice(0, 16) : '';
    document.getElementById('announce_content').value = data?.content || '';
    document.getElementById('announce_status').value = data?.status || 1;
    modal.style.display = 'flex';
}

function closeModal() { 
    modal.style.display = 'none'; 
    form.reset();
}

document.getElementById('showAddModalBtn')?.addEventListener('click', () => openModal(null));

// 编辑公告
document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const id = this.dataset.id;
        fetch(`/api/admin_announcement_get.php?id=${id}`, {
            credentials: 'include'
        })
            .then(res => res.json())
            .then(data => {
                if (data.error) {
                    window.showToast && window.showToast(data.message || '获取失败', 'error');
                    return;
                }
                openModal(data);
            })
            .catch(err => {
                console.error('获取公告失败:', err);
                window.showToast && window.showToast('获取公告信息失败', 'error');
            });
    });
});

document.querySelectorAll('.modal-close, .cancel-btn').forEach(btn => btn.addEventListener('click', closeModal));

// 点击背景关闭
modal.addEventListener('click', function(e) {
    if (e.target === modal) closeModal();
});

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

// 保存表单
form?.addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalHtml = submitBtn.innerHTML;
    submitBtn.innerHTML = '<span class="loading-spinner"></span> 保存中...';
    submitBtn.disabled = true;
    
    fetch('/api/admin_announcement_save.php', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            window.showToast && window.showToast(data.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            window.showToast && window.showToast(data.message || '操作失败', 'error');
            submitBtn.innerHTML = originalHtml;
            submitBtn.disabled = false;
        }
    })
    .catch(() => {
        window.showToast && window.showToast('网络错误', 'error');
        submitBtn.innerHTML = originalHtml;
        submitBtn.disabled = false;
    });
});

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

// 删除
document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        if (!confirm('确定删除吗？')) return;
        const id = this.dataset.id;
        const row = document.getElementById('announce-row-' + id);
        const statusBadge = document.getElementById('status-badge-' + id);
        const currentStatus = statusBadge?.classList.contains('status-active') ? 1 : 0;
        const btnElement = this;
        
        btnElement.innerHTML = '<span class="loading-spinner"></span>';
        btnElement.disabled = true;
        
        fetch('/api/admin_announcement_delete.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}`
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                updateStatsDisplay(currentStatus, null, true);
                
                row.style.transition = 'opacity 0.3s';
                row.style.opacity = '0';
                setTimeout(() => {
                    row.remove();
                    window.showToast && window.showToast('删除成功', 'success');
                    if (document.querySelectorAll('#announcementsTable tbody tr').length === 1) {
                        location.reload();
                    }
                }, 300);
            } else {
                window.showToast && window.showToast(data.message || '删除失败', 'error');
                btnElement.innerHTML = '<img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="16" height="16" alt="">';
                btnElement.disabled = false;
            }
        })
        .catch(() => {
            window.showToast && window.showToast('网络错误', 'error');
            btnElement.innerHTML = '<img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="16" height="16" alt="">';
            btnElement.disabled = false;
        });
    });
});
</script>