<?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('diagnostics_view');

$results = getDiagnosticsResults();
$report = getSelfDiagnosticReport();
$summary = $report['summary'];
$operationAlerts = getOperationalAlerts(8);
$logBreakdown = getOperationalLogBreakdown(7);
$recentOperationalLogs = getRecentOperationalLogs(8);
$recentAuditLogs = getRecentAuditSummary(6);

renderHeader('진단센터', 'diagnostics');
?>
<div class="admin-dashboard diagnostics-page">
    <div class="page-title-section">
        <h1 class="page-main-title">운영 모니터링</h1>
        <p class="page-subtitle">성능, 오류, 스캔, 백업, PWA, API, getID3, 보안 상태를 가볍게 점검합니다. 무거운 스캔이나 백업 작업은 자동 실행하지 않습니다.</p>
    </div>

    <section class="diagnostic-report-hero status-<?php echo h($summary['overall']); ?>">
        <div>
            <span class="diagnostic-kicker">자가진단 리포트</span>
            <h2><?php echo h(diagnosticStatusLabel($summary['overall'])); ?></h2>
            <p>생성 시각 <?php echo h($report['generated_at']); ?> · Service Worker <?php echo h($report['service_worker_version']); ?></p>
        </div>
        <div class="diagnostic-summary-grid">
            <article class="diagnostic-summary-card status-ok">
                <span>정상</span>
                <strong><?php echo number_format((int)$summary['ok']); ?></strong>
            </article>
            <article class="diagnostic-summary-card status-warning">
                <span>주의</span>
                <strong><?php echo number_format((int)$summary['warning']); ?></strong>
            </article>
            <article class="diagnostic-summary-card status-error">
                <span>오류</span>
                <strong><?php echo number_format((int)$summary['error']); ?></strong>
            </article>
            <article class="diagnostic-summary-card status-unknown">
                <span>확인 필요</span>
                <strong><?php echo number_format((int)$summary['unknown']); ?></strong>
            </article>
        </div>
    </section>

    <section class="diagnostic-section">
        <div class="section-heading">
            <div>
                <h2>운영 알림</h2>
                <p>최근 7일 로그와 보관함 상태에서 조치가 필요한 항목만 모았습니다.</p>
            </div>
            <div class="diagnostic-actions">
                <?php if (hasPermission('log_view')): ?><a class="btn btn-secondary btn-sm" href="logs.php">앱 로그 보기</a><?php endif; ?>
                <?php if (hasPermission('backup_view')): ?><a class="btn btn-secondary btn-sm" href="backup_center.php">백업 센터</a><?php endif; ?>
                <?php if (hasPermission('music_scan')): ?><a class="btn btn-secondary btn-sm" href="scan.php">스캔 관리</a><?php endif; ?>
            </div>
        </div>
        <div class="operation-alert-list">
            <?php if (!$operationAlerts): ?>
                <article class="operation-alert-row status-ok">
                    <strong>즉시 확인할 운영 알림이 없습니다.</strong>
                    <p>최근 오류 로그, 캐시 경고, 권한 실패, 메타데이터 경고가 안정 범위입니다.</p>
                </article>
            <?php else: ?>
                <?php foreach ($operationAlerts as $alert): ?>
                    <?php $status = $alert['status'] ?? 'unknown'; ?>
                    <article class="operation-alert-row status-<?php echo h($status); ?>">
                        <div>
                            <strong><?php echo h($alert['title']); ?></strong>
                            <p><?php echo h($alert['message']); ?></p>
                            <?php if (!empty($alert['detail'])): ?><small><?php echo h($alert['detail']); ?></small><?php endif; ?>
                        </div>
                        <span class="diagnostic-badge"><?php echo h(diagnosticStatusLabel($status)); ?></span>
                    </article>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </section>

    <section class="diagnostic-section">
        <div class="section-heading">
            <div>
                <h2>장애 추적 로그 분류</h2>
                <p>stream, cover, API, PJAX, PWA, 인증, 스캔, 백업 관련 로그를 민감정보 없이 분류합니다.</p>
            </div>
        </div>
        <div class="operation-log-grid">
            <?php foreach ($logBreakdown as $row): ?>
                <article class="operation-log-card status-<?php echo h($row['status']); ?>">
                    <span><?php echo h($row['label']); ?></span>
                    <strong><?php echo number_format((int)$row['count']); ?></strong>
                    <small><?php echo h($row['detail']); ?></small>
                </article>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="diagnostic-section">
        <div class="section-heading">
            <div>
                <h2>자가진단 그룹</h2>
                <p>상태는 정상, 주의, 오류, 확인 필요로 구분합니다.</p>
            </div>
        </div>
        <div class="diagnostic-report-groups">
            <?php foreach ($report['groups'] as $group): ?>
                <?php $groupStatus = $group['summary']['overall'] ?? 'unknown'; ?>
                <article class="diagnostic-group-card status-<?php echo h($groupStatus); ?>">
                    <div class="diagnostic-group-head">
                        <div>
                            <h3><?php echo h($group['title']); ?></h3>
                            <p><?php echo h($group['message']); ?></p>
                        </div>
                        <span class="diagnostic-badge"><?php echo h(diagnosticStatusLabel($groupStatus)); ?></span>
                    </div>
                    <div class="diagnostic-group-items">
                        <?php foreach ($group['items'] as $item): ?>
                            <?php $itemStatus = $item['status'] ?? 'unknown'; ?>
                            <div class="diagnostic-mini-status status-<?php echo h($itemStatus); ?>">
                                <strong><?php echo h($item['title']); ?></strong>
                                <span><?php echo h(diagnosticStatusLabel($itemStatus)); ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="diagnostic-section diagnostic-two-column">
        <article class="diagnostic-card">
            <h2>최근 운영 로그</h2>
            <div class="diagnostic-timeline">
                <?php if (!$recentOperationalLogs): ?>
                    <p>최근 경고 / 오류 로그가 없습니다.</p>
                <?php else: ?>
                    <?php foreach ($recentOperationalLogs as $row): ?>
                        <div class="diagnostic-timeline-item">
                            <span class="log-level level-<?php echo h($row['log_level'] ?? 'info'); ?>"><?php echo h($row['log_level'] ?? 'info'); ?></span>
                            <strong><?php echo h($row['log_type'] ?? '-'); ?></strong>
                            <p><?php echo h($row['message'] ?? ''); ?></p>
                            <small><?php echo h($row['created_at'] ?? ''); ?></small>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </article>
        <article class="diagnostic-card">
            <h2>최근 감사 로그</h2>
            <div class="diagnostic-timeline">
                <?php if (!$recentAuditLogs): ?>
                    <p>최근 감사 로그가 없습니다.</p>
                <?php else: ?>
                    <?php foreach ($recentAuditLogs as $row): ?>
                        <div class="diagnostic-timeline-item">
                            <strong><?php echo h($row['action_type'] ?? '-'); ?></strong>
                            <p><?php echo h($row['message'] ?? ''); ?></p>
                            <small><?php echo h(($row['display_name'] ?? $row['username'] ?? '-') . ' · ' . ($row['created_at'] ?? '')); ?></small>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </article>
    </section>

    <section class="diagnostic-section">
        <div class="section-heading">
            <div>
                <h2>전체 점검 항목</h2>
                <p>세부 메시지는 실제 경로, 토큰, 세션값, 원본 SQL을 마스킹한 뒤 표시합니다.</p>
            </div>
        </div>
        <div class="diagnostic-grid">
            <?php foreach ($results as $result): ?>
                <?php $status = $result['status'] ?? 'unknown'; ?>
                <article class="diagnostic-card status-<?php echo h($status); ?>">
                    <div class="diagnostic-card-head">
                        <strong><?php echo h($result['title']); ?></strong>
                        <span class="diagnostic-badge"><?php echo h(diagnosticStatusLabel($status)); ?></span>
                    </div>
                    <p><?php echo h($result['message']); ?></p>
                    <?php if (!empty($result['detail'])): ?><small><?php echo h($result['detail']); ?></small><?php endif; ?>
                </article>
            <?php endforeach; ?>
        </div>
    </section>
</div>
<?php renderFooter(); ?>
