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

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

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

$stmt = $pdo->prepare("
    SELECT COALESCE(NULLIF(TRIM(s.artist), ''), '알 수 없는 아티스트') AS artist_label,
           COUNT(*) AS song_count,
           COUNT(DISTINCT COALESCE(NULLIF(TRIM(s.album), ''), '알 수 없는 앨범')) AS album_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 artist_label
    ORDER BY $orderBy
");
$stmt->execute($params);
$artists = $stmt->fetchAll();

renderHeader('아티스트', 'artists');
?>
<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="name" <?php echo $sort === 'name' ? 'selected' : ''; ?>>이름순</option>
            <option value="songs" <?php echo $sort === 'songs' ? 'selected' : ''; ?>>곡 많은 순</option>
            <option value="plays" <?php echo $sort === 'plays' ? 'selected' : ''; ?>>많이 들은 순</option>
            <option value="recent" <?php echo $sort === 'recent' ? 'selected' : ''; ?>>최근 추가순</option>
        </select>
        <button type="submit" class="btn btn-secondary">검색</button>
    </form>

    <div class="entity-grid">
        <?php foreach ($artists as $artist): ?>
            <a class="entity-card" href="artist.php?name=<?php echo urlencode($artist['artist_label']); ?>">
                <img src="cover.php?id=<?php echo h($artist['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($artist['artist_label']); ?></h2>
                    <p><?php echo number_format($artist['song_count']); ?>곡 · <?php echo number_format($artist['album_count']); ?>앨범</p>
                    <span><?php echo number_format($artist['total_plays']); ?>회 재생</span>
                </div>
            </a>
        <?php endforeach; ?>
    </div>
</div>
<?php renderFooter(); ?>
