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

$pdo = getDBConnection();
$library = getLibraryStats();
$adminStats = getAdminListeningStats();
$summary = $adminStats['summary'];
$topSongs = $adminStats['top_songs'];
$recentStreamErrors = $adminStats['recent_stream_errors'];
$getId3Installed = is_file(dirname(__DIR__) . '/includes/getid3/getid3.php');

renderHeader('청취 통계 요약', 'admin_listening_stats');
?>
<div class="admin-dashboard stats-page">
    <div class="page-title-section">
        <h1 class="page-main-title">청취 통계 요약</h1>
        <p class="page-subtitle">관리자 기준으로 전체 재생 흐름과 운영 상태를 함께 확인합니다.</p>
    </div>

    <?php renderStatGrid([
        ['label' => '전체 등록 곡', 'value' => number_format($library['songs'])],
        ['label' => '전체 재생 기록', 'value' => number_format($summary['total'])],
        ['label' => '최근 7일 재생', 'value' => number_format($summary['week'])],
        ['label' => '최근 30일 재생', 'value' => number_format($summary['month'])],
        ['label' => '파일 없음 곡', 'value' => number_format($library['missing'])],
        ['label' => '메타데이터 누락', 'value' => number_format($library['metadata_missing'])],
        ['label' => '스캔 후 미재생', 'value' => number_format($adminStats['unplayed_after_scan'])],
        ['label' => 'getID3', 'value' => $getId3Installed ? '설치됨' : '미설치'],
    ]); ?>

    <div class="home-section-grid">
        <?php renderMiniSongSection('가장 많이 재생된 곡 TOP 10', $topSongs, '../popular.php'); ?>
        <section class="home-section">
            <div class="section-heading-row">
                <h2 class="section-title">최근 스트리밍 오류</h2>
                <a class="section-more-link" href="logs.php?type=stream_error">오류 로그</a>
            </div>
            <div class="admin-log-list">
                <?php if (empty($recentStreamErrors)): ?>
                    <p class="empty-text">최근 스트리밍 오류 로그가 없습니다.</p>
                <?php else: ?>
                    <?php foreach ($recentStreamErrors as $log): ?>
                        <div class="admin-log-row">
                            <strong><?php echo h($log['created_at']); ?></strong>
                            <span><?php echo h($log['log_level']); ?></span>
                            <p><?php echo h(maskInternalPathText($log['message'] ?? '')); ?></p>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">운영 메모</h2></div>
            <div class="admin-alert-list">
                <div class="admin-alert-row"><strong>getID3 상태</strong><span><?php echo $getId3Installed ? '내부 태그 분석 가능' : '미설치로 내부 태그 분석 제한됨'; ?></span></div>
                <div class="admin-alert-row"><strong>파일 없음</strong><span><?php echo number_format($library['missing']); ?>곡</span></div>
                <div class="admin-alert-row"><strong>메타데이터 누락</strong><span><?php echo number_format($library['metadata_missing']); ?>곡</span></div>
            </div>
        </section>
    </div>
</div>
<?php renderFooter(); ?>
