<?php
/**
 * 많이 들은 곡 목록 페이지 (상위 100위 랭킹 리스트)
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/layout.php';

$pdo = getDBConnection();

// 검색 키워드 획득
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$params = [];

// 재생 횟수 역순 100곡 조회
$sql = "
    SELECT s.id, s.title, s.artist, s.album, s.genre, s.duration, s.extension, s.play_count, 
           IF(l.id IS NOT NULL, 1, 0) AS is_liked
    FROM songs s
    LEFT JOIN liked_songs l ON s.id = l.song_id
    WHERE s.is_missing = 0
      AND COALESCE(s.is_hidden, 0) = 0
";

if ($search !== '') {
    $sql .= " AND (s.title LIKE :search1 OR s.artist LIKE :search2 OR s.album LIKE :search3)";
    $params[':search1'] = '%' . $search . '%';
    $params[':search2'] = '%' . $search . '%';
    $params[':search3'] = '%' . $search . '%';
}

$sql .= "
    ORDER BY s.play_count DESC, s.title ASC
    LIMIT 100
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$songs = $stmt->fetchAll();

$pageTitle = $search !== '' ? '많이 들은 곡 검색 결과' : '많이 들은 곡';
$totalSongs = count($songs);
$totalPlays = 0;
$topPlayCount = 0;
foreach ($songs as $song) {
    $playCount = (int)($song['play_count'] ?? 0);
    $totalPlays += $playCount;
    $topPlayCount = max($topPlayCount, $playCount);
}
$showDownload = function_exists('hasPermission') ? hasPermission('music_manage') : false;

// 레이아웃 헤더 출력
renderHeader($pageTitle, 'popular');
?>

<div class="music-list-page popular-page">
    <div class="page-title-section popular-hero">
        <div class="popular-title-copy">
            <span class="page-eyebrow"><i class="fa-solid fa-fire"></i> TOP 100</span>
            <h1 class="page-main-title"><?php echo h($pageTitle); ?></h1>
            <p class="page-subtitle">
                <?php if ($search !== ''): ?>
                    “<?php echo h($search); ?>” 조건으로 많이 들은 곡을 찾았습니다.
                <?php else: ?>
                    재생 횟수가 높은 순으로 정렬한 나만의 TOP 100 음악 차트입니다.
                <?php endif; ?>
            </p>
        </div>
        <div class="popular-stat-row" aria-label="많이 들은 곡 요약">
            <span><b><?php echo number_format($totalSongs); ?></b><small>표시 곡</small></span>
            <span><b><?php echo number_format($topPlayCount); ?></b><small>최고 재생</small></span>
            <span><b><?php echo number_format($totalPlays); ?></b><small>합산 재생</small></span>
        </div>
    </div>

    <section class="settings-card popular-filter-card" aria-label="많이 들은 곡 검색">
        <form method="GET" action="popular.php" class="popular-filter-form">
            <label for="popular-search">차트 내 검색</label>
            <div class="popular-search-row">
                <input
                    type="search"
                    id="popular-search"
                    name="search"
                    value="<?php echo h($search); ?>"
                    placeholder="곡명, 아티스트, 앨범 검색"
                    autocomplete="off">
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-magnifying-glass"></i> 검색</button>
                <?php if ($search !== ''): ?>
                    <a href="popular.php" class="btn btn-secondary">초기화</a>
                <?php endif; ?>
            </div>
        </form>
    </section>

    <?php if (!empty($songs)) renderPageActions(); ?>

    <section class="popular-rank-list" aria-label="많이 들은 곡 순위">
        <div class="popular-rank-head" aria-hidden="true">
            <span>순위</span>
            <span>재생</span>
            <span>곡명</span>
            <span>아티스트</span>
            <span>앨범</span>
            <span>장르</span>
            <span>시간</span>
            <span>재생 수</span>
            <span>관리</span>
        </div>

        <?php if (empty($songs)): ?>
            <div class="empty-list-state popular-empty-state">
                <i class="fa-solid fa-compact-disc"></i>
                <p>조건에 맞는 많이 들은 곡이 없습니다.</p>
            </div>
        <?php else: ?>
            <?php $rank = 1; foreach ($songs as $song): ?>
                <?php
                    $isLiked = !empty($song['is_liked']);
                    $songId = (int)($song['id'] ?? 0);
                    $coverUrl = coverUrl($song);
                    $artist = artistName($song['artist'] ?? '');
                    $album = albumName($song['album'] ?? '');
                    $genre = genreName($song['genre'] ?? '');
                ?>
                <article
                    class="popular-rank-row song-item"
                    data-id="<?php echo h($songId); ?>"
                    data-title="<?php echo h($song['title'] ?? ''); ?>"
                    data-artist="<?php echo h($artist); ?>"
                    data-album="<?php echo h($album); ?>"
                    data-duration="<?php echo h($song['duration'] ?? 0); ?>"
                    data-cover-url="<?php echo h($coverUrl); ?>"
                    data-liked="<?php echo $isLiked ? '1' : '0'; ?>">
                    <div class="popular-rank-number"><?php echo $rank++; ?></div>
                    <div class="popular-rank-play">
                        <button type="button" class="play-row-btn" title="재생" aria-label="재생">
                            <i class="fas fa-play"></i>
                        </button>
                    </div>
                    <div class="popular-rank-track">
                        <img src="<?php echo h($coverUrl); ?>" alt="" class="list-cover" loading="lazy" width="44" height="44" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                        <div class="popular-rank-title-stack">
                            <a href="song.php?id=<?php echo h($songId); ?>" class="song-title-link"><?php echo h($song['title'] ?? ''); ?></a>
                            <span><?php echo h($artist); ?></span>
                        </div>
                    </div>
                    <div class="popular-rank-artist"><?php echo h($artist); ?></div>
                    <div class="popular-rank-album"><?php echo h($album); ?></div>
                    <div class="popular-rank-genre"><?php echo h($genre); ?></div>
                    <div class="popular-rank-duration"><?php echo h(formatDuration($song['duration'] ?? null)); ?></div>
                    <div class="popular-rank-count play-count-td"><?php echo number_format((int)($song['play_count'] ?? 0)); ?></div>
                    <div class="popular-rank-actions actions-cell">
                        <div class="song-action-group">
                            <button type="button" class="like-btn <?php echo $isLiked ? 'liked' : ''; ?>" title="<?php echo $isLiked ? '좋아요 취소' : '좋아요'; ?>" aria-pressed="<?php echo $isLiked ? 'true' : 'false'; ?>">
                                <i class="<?php echo $isLiked ? 'fas fa-heart' : 'far fa-heart'; ?>"></i>
                            </button>
                            <button type="button" class="add-playlist-btn" title="플레이리스트에 추가" aria-label="플레이리스트에 추가">
                                <i class="fas fa-plus"></i>
                            </button>
                            <?php if ($showDownload): ?>
                                <a href="download.php?id=<?php echo rawurlencode((string)$songId); ?>" class="download-song-btn" title="음원 다운로드" aria-label="음원 다운로드" data-no-pjax download>
                                    <i class="fas fa-download"></i>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </article>
            <?php endforeach; ?>
        <?php endif; ?>
    </section>
</div>

<?php
// 레이아웃 푸터 출력
renderFooter();
?>
