<?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();
$rawArtist = normalizeMetaParam($_GET['name'] ?? $_GET['id'] ?? '');
$unknownArtistLabel = artistName('');
$artistValue = ($rawArtist === $unknownArtistLabel || strcasecmp($rawArtist, 'unknown') === 0) ? '' : $rawArtist;
$artistLabel = artistName($artistValue);

$params = [];
$artistWhere = metaWhereSql('s.artist', ':artist', $artistValue, $params);
$baseWhere = "s.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND $artistWhere";

$songs = fetchSongs($baseWhere, $params, 's.album ASC, s.track_no IS NULL ASC, s.track_no ASC, s.title ASC', 500);

$summaryStmt = $pdo->prepare("
    SELECT COUNT(*) AS song_count,
           COUNT(DISTINCT COALESCE(NULLIF(TRIM(s.album), ''), '__unknown_album__')) AS album_count,
           COALESCE(SUM(s.play_count), 0) AS total_plays,
           MAX(s.id) AS cover_song_id,
           SUBSTRING_INDEX(GROUP_CONCAT(COALESCE(s.cover_hash, '') ORDER BY s.play_count DESC, s.id DESC SEPARATOR '||'), '||', 1) AS cover_hash,
           SUBSTRING_INDEX(GROUP_CONCAT(COALESCE(s.metadata_updated_at, '') ORDER BY s.play_count DESC, s.id DESC SEPARATOR '||'), '||', 1) AS metadata_updated_at,
           SUBSTRING_INDEX(GROUP_CONCAT(COALESCE(s.updated_at, '') ORDER BY s.play_count DESC, s.id DESC SEPARATOR '||'), '||', 1) AS updated_at
    FROM songs s
    WHERE $baseWhere
");
$summaryStmt->execute($params);
$summary = $summaryStmt->fetch() ?: [];

$albumsStmt = $pdo->prepare("
    SELECT COALESCE(NULLIF(TRIM(s.album), ''), :unknown_album) AS album_label,
           COUNT(*) AS song_count,
           COALESCE(SUM(s.play_count), 0) AS total_plays,
           MAX(s.year) AS year,
           MAX(s.updated_at) AS last_updated,
           SUBSTRING_INDEX(GROUP_CONCAT(s.id ORDER BY s.track_no IS NULL ASC, s.track_no ASC, s.id ASC SEPARATOR ','), ',', 1) AS cover_song_id,
           SUBSTRING_INDEX(GROUP_CONCAT(COALESCE(s.cover_hash, '') ORDER BY s.track_no IS NULL ASC, s.track_no ASC, s.id ASC SEPARATOR '||'), '||', 1) AS cover_hash,
           SUBSTRING_INDEX(GROUP_CONCAT(COALESCE(s.metadata_updated_at, '') ORDER BY s.track_no IS NULL ASC, s.track_no ASC, s.id ASC SEPARATOR '||'), '||', 1) AS metadata_updated_at,
           SUBSTRING_INDEX(GROUP_CONCAT(COALESCE(s.updated_at, '') ORDER BY s.track_no IS NULL ASC, s.track_no ASC, s.id ASC SEPARATOR '||'), '||', 1) AS updated_at
    FROM songs s
    WHERE $baseWhere
    GROUP BY album_label
    ORDER BY MIN(s.year) IS NULL ASC, MIN(s.year) DESC, album_label ASC
");
$albumParams = $params;
$albumParams[':unknown_album'] = albumName('');
$albumsStmt->execute($albumParams);
$albums = $albumsStmt->fetchAll();

$popularSongs = fetchSongs($baseWhere, $params, 's.play_count DESC, s.title ASC', 6);

$recentStmt = $pdo->prepare("
    " . baseSongSelectSql() . "
    INNER JOIN (
        SELECT song_id, MAX(played_at) AS last_played_at
        FROM play_history
        GROUP BY song_id
    ) recent ON recent.song_id = s.id
    WHERE $baseWhere
    ORDER BY recent.last_played_at DESC
    LIMIT 6
");
$recentStmt->execute($params);
$recentSongs = $recentStmt->fetchAll();

$likedCount = 0;
foreach ($songs as $song) {
    if (!empty($song['is_liked'])) {
        $likedCount++;
    }
}

$coverSong = [
    'id' => $summary['cover_song_id'] ?? null,
    'cover_hash' => $summary['cover_hash'] ?? '',
    'metadata_updated_at' => $summary['metadata_updated_at'] ?? '',
    'updated_at' => $summary['updated_at'] ?? '',
];
$coverSrc = !empty($summary['cover_song_id']) ? coverUrl($coverSong) : 'assets/img/default-cover.svg';
$totalDuration = array_sum(array_map(static function ($song) {
    return (int)($song['duration'] ?? 0);
}, $songs));

renderHeader($artistLabel, 'artists');
?>
<div class="artist-detail-page detail-page">
    <section class="artist-hero-card">
        <div class="artist-cover-stack" aria-hidden="true">
            <img src="<?php echo h($coverSrc); ?>" alt="" class="artist-hero-cover" width="220" height="220" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
        </div>
        <div class="artist-hero-copy">
            <span class="detail-kicker">아티스트</span>
            <h1 class="page-main-title"><?php echo h($artistLabel); ?></h1>
            <p class="page-subtitle">
                <?php echo number_format((int)($summary['song_count'] ?? 0)); ?>곡 ·
                <?php echo number_format((int)($summary['album_count'] ?? 0)); ?>앨범 ·
                <?php echo h(formatDuration($totalDuration)); ?>
            </p>
            <?php renderStatGrid([
                ['label' => '곡 수', 'value' => number_format((int)($summary['song_count'] ?? 0))],
                ['label' => '앨범 수', 'value' => number_format((int)($summary['album_count'] ?? 0))],
                ['label' => '총 재생', 'value' => number_format((int)($summary['total_plays'] ?? 0))],
                ['label' => '좋아요', 'value' => number_format($likedCount)],
            ]); ?>
            <?php if (!empty($songs)): ?>
                <div class="artist-action-row list-play-actions">
                    <button type="button" class="btn btn-primary btn-play-all"><i class="fas fa-play"></i> 전체 재생</button>
                    <button type="button" class="btn btn-secondary btn-shuffle-all"><i class="fas fa-random"></i> 셔플 재생</button>
                    <button type="button" class="btn btn-secondary btn-add-page-to-queue"><i class="fas fa-list"></i> 대기열 추가</button>
                    <?php if (function_exists('hasPermission') && hasPermission('metadata_bulk_edit')): ?>
                        <a class="btn btn-secondary" href="admin/bulk_edit.php?search=<?php echo rawurlencode($artistLabel); ?>"><i class="fa-solid fa-wand-magic-sparkles"></i> 표기 통합 확인</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </section>

    <?php if (empty($songs)): ?>
        <section class="home-section">
            <div class="detail-empty-state">
                <i class="fa-regular fa-user" aria-hidden="true"></i>
                <p>이 아티스트로 분류된 곡이 없습니다.</p>
                <a class="btn btn-secondary" href="artists.php">아티스트 목록으로 이동</a>
            </div>
        </section>
    <?php else: ?>
        <section class="home-section artist-album-section">
            <div class="section-heading-row">
                <h2 class="section-title">앨범</h2>
                <span class="settings-muted"><?php echo number_format(count($albums)); ?>개</span>
            </div>
            <?php if (empty($albums)): ?>
                <p class="empty-text">표시할 앨범 정보가 없습니다.</p>
            <?php else: ?>
                <div class="artist-album-grid">
                    <?php foreach ($albums as $album): ?>
                        <a class="artist-album-card" href="album.php?album=<?php echo rawurlencode($album['album_label']); ?>&artist=<?php echo rawurlencode($artistLabel); ?>">
                            <img src="<?php echo h(coverUrl([
                                'id' => $album['cover_song_id'],
                                'cover_hash' => $album['cover_hash'] ?? '',
                                'metadata_updated_at' => $album['metadata_updated_at'] ?? '',
                                'updated_at' => $album['updated_at'] ?? '',
                            ])); ?>" alt="" loading="lazy" width="96" height="96" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                            <span>
                                <strong><?php echo h($album['album_label']); ?></strong>
                                <small><?php echo number_format((int)$album['song_count']); ?>곡<?php echo !empty($album['year']) ? ' · ' . h($album['year']) : ''; ?></small>
                            </span>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>

        <div class="artist-insight-grid">
            <section class="home-section">
                <div class="section-heading-row">
                    <h2 class="section-title">많이 들은 곡</h2>
                </div>
                <?php if (empty($popularSongs)): ?>
                    <p class="empty-text">아직 재생 기록이 없습니다.</p>
                <?php else: ?>
                    <div class="artist-mini-list">
                        <?php foreach ($popularSongs as $index => $song): ?>
                            <a class="artist-mini-row" href="song.php?id=<?php echo h($song['id']); ?>">
                                <strong><?php echo number_format($index + 1); ?></strong>
                                <img src="<?php echo h(coverUrl($song)); ?>" alt="" loading="lazy" width="44" height="44" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                                <span><b><?php echo h($song['title']); ?></b><small><?php echo number_format((int)($song['play_count'] ?? 0)); ?>회 재생</small></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>

            <section class="home-section">
                <div class="section-heading-row">
                    <h2 class="section-title">최근 재생</h2>
                </div>
                <?php if (empty($recentSongs)): ?>
                    <p class="empty-text">최근 재생 기록이 없습니다.</p>
                <?php else: ?>
                    <div class="artist-mini-list">
                        <?php foreach ($recentSongs as $song): ?>
                            <a class="artist-mini-row artist-mini-row-compact" href="song.php?id=<?php echo h($song['id']); ?>">
                                <img src="<?php echo h(coverUrl($song)); ?>" alt="" loading="lazy" width="44" height="44" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                                <span><b><?php echo h($song['title']); ?></b><small><?php echo h(formatDuration($song['duration'] ?? null)); ?></small></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>
        </div>

        <section class="home-section artist-song-section">
            <div class="section-heading-row">
                <h2 class="section-title">전체 곡</h2>
                <span class="settings-muted"><?php echo number_format(count($songs)); ?>곡</span>
            </div>
            <?php renderSongList($songs, ['show_play_actions' => false]); ?>
        </section>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
