<?php

function announcementTypeLabels(): array {
    return [
        'notice' => '일반 공지',
        'update' => '업데이트 안내',
        'maintenance' => '점검 안내',
        'important' => '중요 안내',
    ];
}

function announcementTypeLabel($type): string {
    $labels = announcementTypeLabels();
    return $labels[(string)$type] ?? $labels['notice'];
}

function announcementTypeClass($type): string {
    $type = (string)$type;
    return in_array($type, ['notice', 'update', 'maintenance', 'important'], true) ? $type : 'notice';
}

function fetchActiveAnnouncement(): ?array {
    if (!function_exists('getDBConnection')) return null;
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("
            SELECT id, notice_type, title, body, is_important, created_at, updated_at
            FROM app_announcements
            WHERE is_active = 1
              AND (starts_at IS NULL OR starts_at <= NOW())
              AND (ends_at IS NULL OR ends_at >= NOW())
            ORDER BY is_important DESC, updated_at DESC, id DESC
            LIMIT 1
        ");
        $stmt->execute();
        $row = $stmt->fetch();
        return $row ?: null;
    } catch (Throwable $e) {
        if (function_exists('writeAppLog')) {
            writeAppLog('warning', 'announcement_error', 'Active announcement load failed', ['error' => $e->getMessage()]);
        }
        return null;
    }
}

function renderAnnouncementBanner($basePath = './'): void {
    $notice = fetchActiveAnnouncement();
    if (!$notice) return;

    $id = (int)($notice['id'] ?? 0);
    $type = announcementTypeClass($notice['notice_type'] ?? 'notice');
    $title = trim((string)($notice['title'] ?? ''));
    $body = trim((string)($notice['body'] ?? ''));
    if ($id <= 0 || $title === '') return;
    $hasLongBody = function_exists('mb_strlen') ? mb_strlen($body, 'UTF-8') > 120 : strlen($body) > 120;
    ?>
    <section class="app-announcement-banner announcement-<?php echo h($type); ?>" id="app-announcement-banner" data-announcement-id="<?php echo h($id); ?>" aria-label="공지">
        <div class="announcement-icon" aria-hidden="true">
            <i class="fa-solid <?php echo $type === 'maintenance' ? 'fa-screwdriver-wrench' : ($type === 'update' ? 'fa-rotate' : ($type === 'important' ? 'fa-circle-exclamation' : 'fa-bullhorn')); ?>"></i>
        </div>
        <div class="announcement-content">
            <div class="announcement-title-row">
                <span class="announcement-type"><?php echo h(announcementTypeLabel($type)); ?></span>
                <strong><?php echo h($title); ?></strong>
                <?php if (!empty($notice['is_important'])): ?><span class="announcement-important">중요</span><?php endif; ?>
            </div>
            <?php if ($body !== ''): ?>
                <?php if ($hasLongBody): ?>
                    <details class="announcement-details">
                        <summary><?php echo h(function_exists('mb_substr') ? mb_substr($body, 0, 120, 'UTF-8') . '...' : substr($body, 0, 120) . '...'); ?></summary>
                        <p><?php echo nl2br(h($body)); ?></p>
                    </details>
                <?php else: ?>
                    <p><?php echo nl2br(h($body)); ?></p>
                <?php endif; ?>
            <?php endif; ?>
        </div>
        <div class="announcement-actions">
            <?php if ($type === 'update'): ?>
                <a class="btn btn-secondary btn-sm" href="<?php echo h($basePath . 'updates.php'); ?>">업데이트 보기</a>
            <?php endif; ?>
            <button type="button" class="btn btn-secondary btn-sm" data-announcement-dismiss="today">오늘 하루 보지 않기</button>
            <button type="button" class="announcement-close-btn" data-announcement-dismiss="close" aria-label="공지 닫기"><i class="fa-solid fa-xmark"></i></button>
        </div>
    </section>
    <?php
}
