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

requirePermission('diagnostics_view');

$report = getAdminLibraryHealthReport(10);
$summary = $report['summary'] ?? ['overall' => 'ok', 'ok' => 0, 'warning' => 0, 'error' => 0, 'total_issues' => 0];
$items = $report['items'] ?? [];
$samples = $report['samples'] ?? [];

renderHeader('음악 라이브러리 건강검진', 'diagnostics');
?>
<div class="admin-dashboard library-health-page">
    <div class="page-title-section">
        <h1 class="page-main-title">음악 라이브러리 건강검진</h1>
        <p class="page-subtitle">음악 파일과 DB 상태를 기존 스캔 결과, 재생 실패 기록, 메타데이터 상태를 기준으로 요약합니다. 실제 파일 전체 경로는 표시하지 않습니다.</p>
    </div>

    <section class="diagnostic-report-hero library-health-hero status-<?php echo h($summary['overall'] ?? 'ok'); ?>">
        <div>
            <span class="diagnostic-kicker">라이브러리 상태</span>
            <h2><?php echo h($report['label'] ?? '정상'); ?></h2>
            <p><?php echo h($report['message'] ?? '현재 확인 필요한 라이브러리 문제가 없습니다.'); ?></p>
            <small>생성 시각 <?php echo h($report['generated_at'] ?? '-'); ?> · 최근 스캔 <?php echo h($report['latest_scan_at'] ?: '기록 없음'); ?></small>
        </div>
        <div class="diagnostic-summary-grid">
            <article class="diagnostic-summary-card status-ok">
                <span>정상</span>
                <strong><?php echo number_format((int)($summary['ok'] ?? 0)); ?></strong>
            </article>
            <article class="diagnostic-summary-card status-warning">
                <span>주의</span>
                <strong><?php echo number_format((int)($summary['warning'] ?? 0)); ?></strong>
            </article>
            <article class="diagnostic-summary-card status-error">
                <span>확인 필요</span>
                <strong><?php echo number_format((int)($summary['error'] ?? 0)); ?></strong>
            </article>
            <article class="diagnostic-summary-card status-unknown">
                <span>문제 항목</span>
                <strong><?php echo number_format((int)($summary['total_issues'] ?? 0)); ?></strong>
            </article>
        </div>
    </section>

    <section class="home-section library-health-action-section">
        <div class="section-heading-row">
            <div>
                <h2 class="section-title">빠른 점검</h2>
                <p class="settings-muted">대용량 라이브러리에서도 화면 로딩이 무거워지지 않도록 요약과 제한된 후보만 표시합니다.</p>
            </div>
            <div class="toolbar-actions">
                <?php if (hasPermission('music_scan')): ?><a class="btn btn-primary btn-sm" href="scan.php"><i class="fa-solid fa-rotate"></i> 스캔 관리</a><?php endif; ?>
                <?php if (hasPermission('missing_files_manage')): ?><a class="btn btn-secondary btn-sm" href="missing_files.php"><i class="fa-solid fa-file-circle-question"></i> 파일 없음</a><?php endif; ?>
                <?php if (hasPermission('metadata_view')): ?><a class="btn btn-secondary btn-sm" href="metadata_quality.php"><i class="fa-solid fa-tags"></i> 메타데이터 점검</a><?php endif; ?>
            </div>
        </div>
    </section>

    <section class="home-section library-health-summary-section">
        <div class="section-heading-row">
            <h2 class="section-title">점검 항목</h2>
            <a class="section-more-link" href="index.php">운영 센터</a>
        </div>
        <div class="library-health-grid">
            <?php foreach ($items as $item): ?>
                <a class="library-health-card status-<?php echo h($item['status'] ?? 'ok'); ?>" href="<?php echo h($item['href'] ?? 'library_health.php'); ?>">
                    <span class="library-health-card-icon"><i class="<?php echo h($item['icon'] ?? 'fa-solid fa-circle-info'); ?>"></i></span>
                    <span class="library-health-card-main">
                        <strong><?php echo h($item['title'] ?? '점검 항목'); ?></strong>
                        <small><?php echo h($item['detail'] ?? ''); ?></small>
                        <em>최근 확인: <?php echo h(trim((string)($item['last_checked'] ?? '')) !== '' ? $item['last_checked'] : '기록 없음'); ?></em>
                    </span>
                    <span class="library-health-card-count"><?php echo number_format((int)($item['count'] ?? 0)); ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="home-section library-health-sample-section">
        <div class="section-heading-row">
            <div>
                <h2 class="section-title">최근 확인 후보</h2>
                <p class="settings-muted">실제 파일 경로 대신 곡 ID와 표시 가능한 곡 정보만 보여줍니다.</p>
            </div>
        </div>
        <?php if (!$samples): ?>
            <p class="empty-text">현재 확인 필요한 라이브러리 문제가 없습니다.</p>
        <?php else: ?>
            <div class="table-container library-health-table-wrap">
                <table class="data-table library-health-table">
                    <thead>
                        <tr>
                            <th>문제 유형</th>
                            <th>곡 ID</th>
                            <th>곡명</th>
                            <th>아티스트</th>
                            <th>마지막 확인</th>
                            <th class="text-center">이동</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($samples as $row): ?>
                            <tr>
                                <td data-label="문제 유형"><?php echo h($row['issue'] ?? '-'); ?></td>
                                <td data-label="곡 ID">#<?php echo number_format((int)($row['song_id'] ?? 0)); ?></td>
                                <td data-label="곡명"><?php echo h($row['title'] ?? '제목 없음'); ?></td>
                                <td data-label="아티스트"><?php echo h($row['artist'] ?? '아티스트 없음'); ?></td>
                                <td data-label="마지막 확인"><?php echo h($row['checked_at'] ?: '-'); ?></td>
                                <td data-label="이동" class="text-center"><a class="btn btn-secondary btn-sm" href="<?php echo h($row['href'] ?? 'library_health.php'); ?>">확인</a></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>
</div>
<?php renderFooter(); ?>
