<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/admin_notifications.php';
require_once dirname(__DIR__) . '/includes/layout.php';
requirePermission('alert_view');

syncAdminOperationalNotifications();

$message = trim((string)($_GET['message'] ?? ''));
$status = trim((string)($_GET['status'] ?? 'success'));
$category = trim((string)($_GET['category'] ?? ''));
$level = trim((string)($_GET['level'] ?? ''));
$read = trim((string)($_GET['read'] ?? 'unread'));
$pinned = trim((string)($_GET['pinned'] ?? ''));
$hidden = trim((string)($_GET['hidden'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));

function alertCenterUrl($changes = []) {
    $params = $_GET;
    unset($params['message'], $params['status']);
    foreach ($changes as $key => $value) {
        if ($value === null || $value === '') unset($params[$key]);
        else $params[$key] = $value;
    }
    return 'alerts.php?' . http_build_query($params);
}

function alertRedirect($message, $status = 'success') {
    header('Location: ' . alertCenterUrl(['message' => $message, 'status' => $status, 'page' => null]));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    $action = (string)($_POST['action'] ?? '');
    $done = 0;

    try {
        if ($action === 'mark_read') {
            $notificationId = (int)($_POST['id'] ?? 0);
            $done = markAdminNotificationRead($notificationId);
            writeAuditLog('notification_read', 'Admin notification marked as read: ' . $notificationId, 'success', 'info', 'admin_notifications', $notificationId);
        } elseif ($action === 'mark_selected_read') {
            $done = markAdminNotificationsRead($_POST['ids'] ?? []);
            writeAuditLog('notification_read_bulk', 'Selected admin notifications marked as read: ' . $done, 'success', 'info', 'admin_notifications');
        } elseif ($action === 'mark_all_read') {
            $done = markAllAdminNotificationsRead(trim((string)($_POST['category'] ?? '')));
            writeAuditLog('notification_read_all', 'Admin notifications marked as read: ' . $done, 'success', 'info', 'admin_notifications');
        } elseif ($action === 'toggle_pin') {
            $notificationId = (int)($_POST['id'] ?? 0);
            $done = toggleAdminNotificationPin($notificationId);
            writeAuditLog('notification_pin_toggle', 'Admin notification pin toggled: ' . $notificationId, 'success', 'info', 'admin_notifications', $notificationId);
        } elseif ($action === 'hide') {
            $notificationId = (int)($_POST['id'] ?? 0);
            $done = hideAdminNotification($notificationId);
            writeAuditLog('notification_hide', 'Admin notification hidden: ' . $notificationId, 'success', 'info', 'admin_notifications', $notificationId);
        } elseif ($action === 'archive_old') {
            $done = archiveOldAdminNotifications(90);
            writeAuditLog('notification_archive_old', 'Old read admin notifications archived: ' . $done, 'success', 'info', 'admin_notifications');
        } else {
            throw new Exception('지원하지 않는 알림 작업입니다.');
        }
        alertRedirect(number_format($done) . '건 처리했습니다.');
    } catch (Throwable $e) {
        writeAppLog('warning', 'notification_action_error', 'Admin notification action failed', [
            'action' => $action,
            'message' => adminNotificationSanitizeText($e->getMessage()),
        ]);
        alertRedirect('알림 처리 중 오류가 발생했습니다.', 'error');
    }
}

$summary = getAdminNotificationSummary();
$notifications = getAdminNotifications([
    'category' => $category,
    'level' => $level,
    'read' => $read,
    'pinned' => $pinned,
    'hidden' => $hidden,
    'page' => $page,
    'limit' => 24,
]);
$weeklyReport = getWeeklyOperationReport();
$categories = adminNotificationAllowedCategories();
$levels = adminNotificationAllowedLevels();

renderHeader('관리자 알림센터', 'alerts');
?>
<div class="admin-dashboard alerts-page admin-alert-center-page">
    <div class="page-title-section">
        <h1 class="page-main-title">관리자 알림센터</h1>
        <p class="page-subtitle">운영, 오류, 재생 실패, 피드백, 수정 요청, 업데이트, 점검 알림을 한곳에서 확인하고 정리합니다.</p>
    </div>

    <?php if ($message !== ''): ?>
        <div class="alert-box <?php echo $status === 'error' ? 'alert-danger' : 'alert-info'; ?>">
            <div class="alert-content"><p><?php echo h($message); ?></p></div>
        </div>
    <?php endif; ?>

    <section class="diagnostic-report-hero alert-center-hero status-<?php echo $summary['critical'] > 0 ? 'error' : ($summary['unread'] > 0 ? 'warning' : 'ok'); ?>">
        <div>
            <span class="diagnostic-kicker">알림 요약</span>
            <h2><?php echo $summary['unread'] > 0 ? number_format($summary['unread']) . '건 확인 필요' : '새 알림 없음'; ?></h2>
            <p>중요 알림은 상단에 고정되며, 실제 음악 파일 경로와 내부 오류 상세는 화면에 표시하지 않습니다.</p>
        </div>
        <div class="diagnostic-summary-grid">
            <article class="diagnostic-summary-card status-warning"><span>안 읽음</span><strong><?php echo number_format($summary['unread']); ?></strong></article>
            <article class="diagnostic-summary-card status-error"><span>긴급/오류</span><strong><?php echo number_format($summary['critical']); ?></strong></article>
            <article class="diagnostic-summary-card status-ok"><span>고정</span><strong><?php echo number_format($summary['pinned']); ?></strong></article>
            <article class="diagnostic-summary-card status-unknown"><span>전체</span><strong><?php echo number_format($summary['total']); ?></strong></article>
        </div>
    </section>

    <section class="diagnostic-section" id="weekly-report">
        <div class="section-heading">
            <div>
                <h2>최근 7일 운영 리포트</h2>
                <p><?php echo h($weeklyReport['since']); ?> 이후의 가벼운 운영 요약입니다. 전체 기간 통계는 별도 페이지에서 확인합니다.</p>
            </div>
            <a class="btn btn-secondary btn-sm" href="diagnostics.php">자가 진단 보기</a>
        </div>
        <div class="operation-log-grid weekly-report-grid">
            <?php foreach ($weeklyReport['cards'] as $card): ?>
                <article class="operation-log-card status-<?php echo h($card['status']); ?>">
                    <span><?php echo h($card['label']); ?></span>
                    <strong><?php echo h($card['value']); ?></strong>
                    <small><?php echo h($card['detail']); ?></small>
                </article>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="diagnostic-section alert-center-section">
        <div class="section-heading alert-center-heading">
            <div>
                <h2>알림 목록</h2>
                <p>읽음 처리, 중요 알림 고정, 보관 처리를 할 수 있습니다. 같은 오류는 fingerprint 기준으로 중복 생성을 줄입니다.</p>
            </div>
            <form method="POST" class="inline-action-form alert-center-toolbar" onsubmit="return confirm('현재 필터 조건의 안 읽은 알림을 모두 읽음 처리할까요?');">
                <?php echo csrfInput(); ?>
                <input type="hidden" name="category" value="<?php echo h($category); ?>">
                <button class="btn btn-secondary btn-sm" name="action" value="mark_all_read" type="submit">전체 읽음</button>
                <button class="btn btn-secondary btn-sm" name="action" value="archive_old" type="submit" onclick="return confirm('90일이 지난 읽은 알림을 보관 처리할까요?');">오래된 알림 보관</button>
            </form>
        </div>

        <form method="GET" class="settings-card compact-filter-form alert-center-filter">
            <div class="form-row alert-center-form-grid">
                <div class="form-group">
                    <label>유형
                        <select name="category">
                            <option value="">전체</option>
                            <?php foreach ($categories as $item): ?>
                                <option value="<?php echo h($item); ?>" <?php echo $category === $item ? 'selected' : ''; ?>><?php echo h(adminNotificationCategoryLabel($item)); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                </div>
                <div class="form-group">
                    <label>중요도
                        <select name="level">
                            <option value="">전체</option>
                            <?php foreach ($levels as $item): ?>
                                <option value="<?php echo h($item); ?>" <?php echo $level === $item ? 'selected' : ''; ?>><?php echo h(adminNotificationLevelLabel($item)); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                </div>
                <div class="form-group">
                    <label>읽음 상태
                        <select name="read">
                            <option value="unread" <?php echo $read === 'unread' ? 'selected' : ''; ?>>안 읽음</option>
                            <option value="read" <?php echo $read === 'read' ? 'selected' : ''; ?>>읽음</option>
                            <option value="" <?php echo $read === '' ? 'selected' : ''; ?>>전체</option>
                        </select>
                    </label>
                </div>
                <div class="form-group">
                    <label>고정
                        <select name="pinned">
                            <option value="">전체</option>
                            <option value="pinned" <?php echo $pinned === 'pinned' ? 'selected' : ''; ?>>고정만</option>
                        </select>
                    </label>
                </div>
                <div class="form-group">
                    <label>보관
                        <select name="hidden">
                            <option value="">현재 알림</option>
                            <option value="hidden" <?php echo $hidden === 'hidden' ? 'selected' : ''; ?>>보관 알림</option>
                        </select>
                    </label>
                </div>
                <div class="form-group form-group-actions">
                    <button class="btn btn-secondary" type="submit">필터 적용</button>
                </div>
            </div>
        </form>

        <form method="POST" class="alert-center-list-form">
            <?php echo csrfInput(); ?>
            <input type="hidden" name="id" value="">
            <div class="alert-center-list">
                <?php if (!$notifications['rows']): ?>
                    <article class="operation-alert-row status-ok">
                        <strong>조건에 맞는 알림이 없습니다.</strong>
                        <p>필터를 변경하거나 자가 진단 페이지에서 현재 운영 상태를 확인하세요.</p>
                    </article>
                <?php else: ?>
                    <?php foreach ($notifications['rows'] as $item): ?>
                        <?php $levelClass = $item['level'] === 'critical' ? 'error' : $item['level']; ?>
                        <article class="operation-alert-row alert-center-item status-<?php echo h($levelClass); ?> <?php echo (int)$item['is_read'] === 1 ? 'is-read' : 'is-unread'; ?> <?php echo (int)$item['is_pinned'] === 1 ? 'is-pinned' : ''; ?>">
                            <label class="alert-select">
                                <input type="checkbox" name="ids[]" value="<?php echo h($item['id']); ?>">
                                <span class="sr-only">선택</span>
                            </label>
                            <div class="alert-center-main">
                                <div class="alert-center-meta">
                                    <?php if ((int)$item['is_pinned'] === 1): ?><span class="alert-pin-badge">고정</span><?php endif; ?>
                                    <span class="diagnostic-badge level-<?php echo h($item['level']); ?>"><?php echo h(adminNotificationLevelLabel($item['level'])); ?></span>
                                    <span><?php echo h(adminNotificationCategoryLabel($item['category'])); ?></span>
                                    <span><?php echo (int)$item['is_read'] === 1 ? '읽음' : '안 읽음'; ?></span>
                                    <span><?php echo h($item['last_seen_at']); ?></span>
                                </div>
                                <strong><?php echo h($item['title']); ?></strong>
                                <?php if (!empty($item['message'])): ?><p><?php echo h($item['message']); ?></p><?php endif; ?>
                                <?php if (!empty($item['detail'])): ?><small><?php echo h($item['detail']); ?></small><?php endif; ?>
                                <div class="alert-center-actions">
                                    <?php if (!empty($item['related_url'])): ?><a class="btn btn-secondary btn-sm" href="<?php echo h($item['related_url']); ?>">관련 페이지</a><?php endif; ?>
                                    <button class="btn btn-secondary btn-sm" name="action" value="toggle_pin" type="submit" onclick="this.form.id.value='<?php echo h($item['id']); ?>';"><?php echo (int)$item['is_pinned'] === 1 ? '고정 해제' : '중요 고정'; ?></button>
                                    <?php if ((int)$item['is_read'] === 0): ?>
                                        <button class="btn btn-secondary btn-sm" name="action" value="mark_read" type="submit" onclick="this.form.id.value='<?php echo h($item['id']); ?>';">읽음</button>
                                    <?php endif; ?>
                                    <?php if ((int)$item['is_hidden'] === 0): ?>
                                        <button class="btn btn-secondary btn-sm" name="action" value="hide" type="submit" onclick="this.form.id.value='<?php echo h($item['id']); ?>'; return confirm('이 알림을 보관 처리할까요?');">보관</button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </article>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <?php if ($notifications['rows']): ?>
                <div class="alert-center-bulk-actions">
                    <button class="btn btn-secondary" name="action" value="mark_selected_read" type="submit">선택 읽음</button>
                    <span class="settings-muted"><?php echo number_format($notifications['total']); ?>건 중 <?php echo number_format($notifications['page']); ?> / <?php echo number_format($notifications['pages']); ?> 페이지</span>
                </div>
            <?php endif; ?>
        </form>

        <?php if ($notifications['pages'] > 1): ?>
            <nav class="search-pagination" aria-label="알림 페이지">
                <?php if ($notifications['page'] > 1): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(alertCenterUrl(['page' => $notifications['page'] - 1])); ?>">이전</a><?php endif; ?>
                <span class="settings-muted"><?php echo number_format($notifications['page']); ?> / <?php echo number_format($notifications['pages']); ?> 페이지</span>
                <?php if ($notifications['page'] < $notifications['pages']): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(alertCenterUrl(['page' => $notifications['page'] + 1])); ?>">다음</a><?php endif; ?>
            </nav>
        <?php endif; ?>
    </section>
</div>
<?php renderFooter(); ?>
