<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/stats_functions.php';
require_once __DIR__ . '/includes/functions_notes.php';
require_once __DIR__ . '/includes/layout.php';

$summary = getListeningSummary();
$trend7 = getListeningTrend(7);
$trend30 = getListeningTrend(30);
$topSongs = getTopSongsByHistory(10);
$topArtists = getTopFieldByHistory('artist', 10);
$topAlbums = getTopFieldByHistory('album', 10);
$topGenres = getTopFieldByHistory('genre', 10);
$recentFrequent = getRecentlyFrequentSongs(10);
$hourPattern = getPatternStats('hour');
$weekdayPattern = getPatternStats('weekday');
$recentAddedTop = getRecentAddedTopSongs(10);
$likedTop = getLikedTopSongs(10);
$noteStats = getListeningNoteStats();
$topRatedSongs = getListeningNoteSongs('top_rated', 10);
$unratedPopular = getListeningNoteSongs('popular_no_notes', 10);
$hasHistory = $summary['total'] > 0;
$reportPeriod = normalizeListeningReportPeriod($_GET['report_period'] ?? 'week');
$reportOptions = listeningReportPeriodOptions();
$reportSummary = getListeningReportSummary($reportPeriod);
$reportTopSong = $reportSummary['top_song'];

renderHeader('청취 리포트', 'stats');
?>
<div class="stats-page">
    <div class="page-title-section">
        <h1 class="page-main-title">청취 리포트</h1>
        <p class="page-subtitle">최근 청취 흐름과 자주 듣는 음악을 한눈에 봅니다.</p>
    </div>

    <section class="home-section listening-report-card" aria-labelledby="weekly-listening-report-title">
        <div class="listening-report-head">
            <div>
                <span class="section-kicker">청취 요약</span>
                <h2 class="section-title" id="weekly-listening-report-title">
                    <?php echo h($reportOptions[$reportPeriod]['label'] ?? '이번 주'); ?> 음악 리포트
                </h2>
                <p class="section-description">기간별 재생 흐름, 많이 들은 곡, 아티스트, 장르를 요약합니다.</p>
            </div>
            <nav class="report-period-tabs" aria-label="청취 리포트 기간">
                <?php foreach ($reportOptions as $periodKey => $periodMeta): ?>
                    <a class="<?php echo $reportPeriod === $periodKey ? 'active' : ''; ?>"
                       href="stats.php?report_period=<?php echo h($periodKey); ?>">
                        <?php echo h($periodMeta['label']); ?>
                    </a>
                <?php endforeach; ?>
            </nav>
        </div>

        <?php if ((int)$reportSummary['play_events'] <= 0): ?>
            <div class="report-empty-state">
                <i class="fa-solid fa-headphones-simple" aria-hidden="true"></i>
                <strong>아직 이 기간의 청취 기록이 부족합니다.</strong>
                <span>음악을 조금 더 들으면 많이 들은 곡과 장르가 자동으로 정리됩니다.</span>
                <div class="report-action-row">
                    <a class="btn btn-primary btn-sm" href="index.php?view=all"><i class="fa-solid fa-music"></i> 음악 보관함 열기</a>
                    <a class="btn btn-secondary btn-sm" href="recommend.php"><i class="fa-solid fa-star"></i> 추천 음악 보기</a>
                </div>
            </div>
        <?php else: ?>
            <div class="listening-report-layout">
                <div class="report-metric-grid" aria-label="기간별 청취 지표">
                    <div><span>재생 기록</span><strong><?php echo number_format((int)$reportSummary['play_events']); ?></strong><em>회</em></div>
                    <div><span>들은 곡</span><strong><?php echo number_format((int)$reportSummary['unique_songs']); ?></strong><em>곡</em></div>
                    <div><span>예상 청취 시간</span><strong><?php echo h(formatListeningSeconds($reportSummary['total_seconds'])); ?></strong><em>기록 기준</em></div>
                </div>

                <?php if ($reportTopSong): ?>
                    <?php $reportTopSongLiked = !empty($reportTopSong['is_liked']); ?>
                    <article class="report-top-song song-item"
                             data-id="<?php echo h($reportTopSong['id']); ?>"
                             data-title="<?php echo h($reportTopSong['title']); ?>"
                             data-artist="<?php echo h(artistName($reportTopSong['artist'] ?? '')); ?>"
                             data-album="<?php echo h(albumName($reportTopSong['album'] ?? '')); ?>"
                             data-duration="<?php echo h($reportTopSong['duration'] ?? 0); ?>"
                             data-cover-url="<?php echo h(coverUrl($reportTopSong)); ?>"
                             data-liked="<?php echo $reportTopSongLiked ? '1' : '0'; ?>">
                        <img src="<?php echo h(coverUrl($reportTopSong)); ?>" alt="" loading="lazy" width="92" height="92" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                        <div class="report-top-song-meta">
                            <span>가장 많이 들은 곡</span>
                            <a href="song.php?id=<?php echo h($reportTopSong['id']); ?>"><?php echo h($reportTopSong['title']); ?></a>
                            <p><?php echo h(artistName($reportTopSong['artist'] ?? '')); ?><?php echo !empty($reportTopSong['genre']) ? ' · ' . h(genreName($reportTopSong['genre'])) : ''; ?></p>
                        </div>
                        <div class="report-action-row">
                            <button type="button" class="btn btn-primary btn-sm play-row-btn"><i class="fa-solid fa-play"></i> 바로 재생</button>
                            <a class="btn btn-secondary btn-sm" href="song.php?id=<?php echo h($reportTopSong['id']); ?>"><i class="fa-solid fa-circle-info"></i> 상세</a>
                        </div>
                    </article>
                <?php endif; ?>

                <div class="report-rank-grid">
                    <div class="report-rank-box">
                        <strong>많이 들은 아티스트</strong>
                        <?php if (empty($reportSummary['top_artists'])): ?>
                            <span class="empty-text">집계할 아티스트가 없습니다.</span>
                        <?php else: ?>
                            <?php foreach ($reportSummary['top_artists'] as $artist): ?>
                                <a href="artist.php?name=<?php echo urlencode((string)$artist['name']); ?>">
                                    <span><?php echo h($artist['name']); ?></span><em><?php echo number_format((int)$artist['plays']); ?>회</em>
                                </a>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    <div class="report-rank-box">
                        <strong>많이 들은 장르</strong>
                        <?php if (empty($reportSummary['top_genres'])): ?>
                            <span class="empty-text">집계할 장르가 없습니다.</span>
                        <?php else: ?>
                            <?php foreach ($reportSummary['top_genres'] as $genre): ?>
                                <a href="genre.php?name=<?php echo urlencode((string)$genre['name']); ?>">
                                    <span><?php echo h($genre['name']); ?></span><em><?php echo number_format((int)$genre['plays']); ?>회</em>
                                </a>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="report-action-row report-footer-actions">
                    <button type="button" class="btn btn-primary btn-auto-mix" data-auto-mix-action="play" data-limit="24">
                        <i class="fa-solid fa-wand-magic-sparkles"></i> 자동 믹스 재생
                    </button>
                    <a class="btn btn-secondary" href="liked.php"><i class="fa-regular fa-heart"></i> 좋아요한 곡</a>
                    <a class="btn btn-secondary" href="listening_notes.php?filter=top_rated"><i class="fa-solid fa-star"></i> 별점 높은 곡</a>
                </div>
            </div>
        <?php endif; ?>
    </section>

    <?php renderStatGrid([
        ['label' => '오늘 들은 곡', 'value' => number_format($summary['today'])],
        ['label' => '최근 7일', 'value' => number_format($summary['week'])],
        ['label' => '최근 30일', 'value' => number_format($summary['month'])],
        ['label' => '전체 재생 기록', 'value' => number_format($summary['total'])],
    ]); ?>

    <?php renderStatGrid([
        ['label' => '별점 있는 곡', 'value' => number_format($noteStats['rated'])],
        ['label' => '5점 곡', 'value' => number_format($noteStats['five_star'])],
        ['label' => '메모 있는 곡', 'value' => number_format($noteStats['notes'])],
        ['label' => '가사 있는 곡', 'value' => number_format($noteStats['lyrics'])],
    ]); ?>

    <?php if (!$hasHistory): ?>
        <section class="home-section">
            <h2 class="section-title">아직 청취 기록이 없습니다.</h2>
            <p class="empty-text">음악을 재생하면 오늘의 요약, TOP 곡, 시간대별 패턴이 이곳에 쌓입니다.</p>
        </section>
    <?php endif; ?>

    <div class="stats-grid">
        <section class="home-section stats-card-wide">
            <div class="section-heading-row"><h2 class="section-title">최근 7일 청취 추이</h2></div>
            <?php renderMiniBarChart($trend7); ?>
        </section>
        <section class="home-section stats-card-wide">
            <div class="section-heading-row"><h2 class="section-title">최근 30일 청취 추이</h2></div>
            <?php renderMiniBarChart($trend30); ?>
        </section>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">많이 들은 아티스트 TOP 10</h2></div>
            <?php renderMiniBarChart($topArtists, 'name', 'plays'); ?>
        </section>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">많이 들은 앨범 TOP 10</h2></div>
            <?php renderMiniBarChart($topAlbums, 'name', 'plays'); ?>
        </section>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">많이 들은 장르 TOP 10</h2></div>
            <?php renderMiniBarChart($topGenres, 'name', 'plays'); ?>
        </section>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">시간대별 청취 패턴</h2></div>
            <?php renderMiniBarChart($hourPattern); ?>
        </section>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">요일별 청취 패턴</h2></div>
            <?php renderMiniBarChart($weekdayPattern); ?>
        </section>
    </div>

    <div class="home-section-grid">
        <?php renderMiniSongSection('가장 많이 들은 곡 TOP 10', $topSongs, 'popular.php'); ?>
        <?php renderMiniSongSection('최근 자주 들은 곡', $recentFrequent, 'recent.php'); ?>
        <?php renderMiniSongSection('최근 추가곡 중 많이 들은 곡', $recentAddedTop, 'new.php'); ?>
        <?php renderMiniSongSection('좋아요한 곡 중 많이 들은 곡', $likedTop, 'liked.php'); ?>
        <?php renderMiniSongSection('별점 높은 곡 중 다시 듣기', $topRatedSongs, 'listening_notes.php?filter=top_rated'); ?>
        <?php renderMiniSongSection('많이 들었지만 메모 없는 곡', $unratedPopular, 'listening_notes.php?filter=popular_no_notes'); ?>
    </div>
</div>
<?php renderFooter(); ?>
