<?php
require_once '../include/common.php';

if (!isset($_SESSION['role'])) {
    header("Location: login.php");
    exit();
}

$stmt = $pdo->prepare("SELECT title, message, created_at FROM " . table('announcements') . " ORDER BY created_at DESC");
$stmt->execute();
$announcements = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM " . table('announcements') . "");
$stmt->execute();
$announcements_count = $stmt->fetchColumn();

if (!isset($currentSettings['site_qq'])) {
    $currentSettings['site_qq'] = '默认QQ号';
}
?>

<div class="dropdown d-inline-block">
    <button type="button" class="btn header-item noti-icon position-relative" id="page-header-notifications-dropdown"
        data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <i data-feather="bell" class="icon-lg"></i>
        <span class="badge bg-danger rounded-pill"><?php echo htmlspecialchars($announcements_count); ?></span> <!-- 显示公告数量 -->
    </button>
    <div class="dropdown-menu dropdown-menu-lg dropdown-menu-end p-0"
        aria-labelledby="page-header-notifications-dropdown">
        <div class="p-3">
            <div class="row align-items-center">
                <div class="col">
                    <h6 class="m-0">通知栏</h6>
                </div>
                <div class="col-auto">
                    <a href="#!" class="small text-reset text-decoration-underline">信息 (<?php echo htmlspecialchars($announcements_count); ?>)</a> <!-- 显示公告数量 -->
                </div>
            </div>
        </div>
        <div data-simplebar style="max-height: 230px;">
            <?php if (count($announcements) > 0): ?>
                <?php foreach ($announcements as $announcement): ?>
                    <a href="#!" class="text-reset notification-item">
                        <div class="d-flex">
                            <div class="flex-shrink-0 me-3">
                                <img src="https://q2.qlogo.cn/headimg_dl?dst_uin=<?php echo $currentSettings['site_qq']; ?>&spec=640" class="rounded-circle avatar-sm" alt="user-pic">    
                            </div>
                            <div class="flex-grow-1">
                                <h6 class="mb-1"><?php echo htmlspecialchars($announcement['title']); ?></h6>
                                <div class="font-size-13 text-muted">
                                    <p class="mb-1"><?php echo htmlspecialchars($announcement['message']); ?></p>
                                    <p class="mb-0"><i class="mdi mdi-clock-outline"></i> <span><?php echo htmlspecialchars($announcement['created_at']); ?></span></p>
                                </div>
                            </div>
                        </div>
                    </a>
                <?php endforeach; ?>
            <?php else: ?>
                <p class="text-muted">没有公告可显示。</p>
            <?php endif; ?>
        </div>
    </div>
</div>
