<?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/diagnostics.php';
require_once dirname(__DIR__) . '/includes/layout.php';
requirePermission('alert_view');

$alerts = getDiagnosticAlerts();
try {
    $pdo = getDBConnection();
    $securityEvents = (int)$pdo->query("
        SELECT COUNT(*)
        FROM app_logs
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
          AND (
              log_type IN ('login_error','audit','restore','import','backup')
              OR message LIKE '%Permission denied%'
          )
    ")->fetchColumn();
    if ($securityEvents > 0) {
        array_unshift($alerts, [
            'status' => 'warning',
            'title' => '최근 보안 이벤트',
            'message' => '최근 24시간 동안 로그인 실패, 권한 부족, 백업/복원 관련 이벤트가 있습니다.',
            'detail' => number_format($securityEvents) . '건 · 감사 로그에서 확인하세요.',
        ]);
    }
} catch (Throwable $e) {
}

renderHeader('관리자 알림', 'alerts');
?>
<div class="admin-dashboard alerts-page">
    <div class="page-title-section">
        <h1 class="page-main-title">관리자 알림</h1>
        <p class="page-subtitle">진단 결과 중 확인이 필요한 항목만 모아 보여줍니다.</p>
    </div>
    <?php if (empty($alerts)): ?>
        <section class="home-section"><p class="empty-text">현재 확인이 필요한 알림이 없습니다.</p></section>
    <?php else: ?>
        <div class="diagnostic-grid">
            <?php foreach ($alerts as $alert): ?>
                <article class="diagnostic-card status-<?php echo h($alert['status']); ?>">
                    <div class="diagnostic-card-head">
                        <strong><?php echo h($alert['title']); ?></strong>
                        <span class="diagnostic-badge"><?php echo h($alert['status']); ?></span>
                    </div>
                    <p><?php echo h($alert['message']); ?></p>
                    <?php if (!empty($alert['detail'])): ?><small><?php echo h($alert['detail']); ?></small><?php endif; ?>
                </article>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
