<?php
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();
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'recent';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

$orderMap = [
    'recent' => 'last_added DESC',
    'album' => 'album_label ASC',
    'artist' => 'artist_label ASC, album_label ASC',
    'year' => 'year DESC, album_label ASC',
    'songs' => 'song_count DESC, album_label ASC',
    'plays' => 'total_plays DESC, album_label ASC',
];
$orderBy = $orderMap[$sort] ?? $orderMap['recent'];

$where = 's.is_missing = 0';
$params = [];
if ($search !== '') {
    $where .= " AND (COALESCE(NULLIF(TRIM(s.album), ''), '알 수 없는 앨범') LIKE :search1 OR COALESCE(NULLIF(TRIM(s.artist), ''), '알 수 없는 아티스트') LIKE :search2)";
    $params[':search1'] = '%' . $search . '%';
    $params[':search2'] = '%' . $search . '%';
}

$stmt = $pdo->prepare("
    SELECT COALESCE(NULLIF(TRIM(s.album), ''), '알 수 없는 앨범') AS album_label,
           COALESCE(NULLIF(TRIM(s.artist), ''), '알 수 없는 아티스트') AS artist_label,
           MIN(COALESCE(NULLIF(TRIM(s.genre), ''), '알 수 없는 장르')) AS genre_label,
           MAX(s.year) AS year,
           COUNT(*) AS song_count,
           COALESCE(SUM(s.play_count), 0) AS total_plays,
           MAX(s.id) AS cover_song_id,
           MAX(s.created_at) AS last_added
    FROM songs s
    WHERE $where
    GROUP BY album_label, artist_label
    ORDER BY $orderBy
");
$stmt->execute($params);
$albums = $stmt->fetchAll();

renderHeader('앨범', 'albums');
?>
<div class="library-page">
    <div class="page-title-section">
        <h1 class="page-main-title">앨범</h1>
        <p class="page-subtitle">같은 앨범명이라도 아티스트가 다르면 별도로 표시합니다.</p>
    </div>
    <form class="library-toolbar" method="GET">
        <input type="text" name="search" value="<?php echo h($search); ?>" placeholder="앨범명 또는 아티스트명 검색">
        <select name="sort" onchange="this.form.submit()">
            <option value="recent" <?php echo $sort === 'recent' ? 'selected' : ''; ?>>최근 추가순</option>
            <option value="album" <?php echo $sort === 'album' ? 'selected' : ''; ?>>앨범명순</option>
            <option value="artist" <?php echo $sort === 'artist' ? 'selected' : ''; ?>>아티스트순</option>
            <option value="year" <?php echo $sort === 'year' ? 'selected' : ''; ?>>연도순</option>
            <option value="songs" <?php echo $sort === 'songs' ? 'selected' : ''; ?>>곡 많은 순</option>
            <option value="plays" <?php echo $sort === 'plays' ? 'selected' : ''; ?>>많이 들은 순</option>
        </select>
        <button type="submit" class="btn btn-secondary">검색</button>
    </form>
    <div class="entity-grid">
        <?php foreach ($albums as $album): ?>
            <a class="entity-card" href="album.php?album=<?php echo urlencode($album['album_label']); ?>&artist=<?php echo urlencode($album['artist_label']); ?>">
                <img src="cover.php?id=<?php echo h($album['cover_song_id']); ?>" alt="" class="entity-cover" loading="lazy" width="96" height="96" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                <div class="entity-info">
                    <h2><?php echo h($album['album_label']); ?></h2>
                    <p><?php echo h($album['artist_label']); ?></p>
                    <span><?php echo number_format($album['song_count']); ?>곡 · <?php echo h($album['genre_label']); ?><?php echo $album['year'] ? ' · ' . h($album['year']) : ''; ?> · <?php echo number_format($album['total_plays']); ?>회</span>
                </div>
            </a>
        <?php endforeach; ?>
    </div>
</div>
<?php renderFooter(); ?>
