<?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';

$album = normalizeMetaParam($_GET['album'] ?? $_GET['id'] ?? '');
$artist = normalizeMetaParam($_GET['artist'] ?? '');
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'track';

$params = [];
$albumWhere = metaWhereSql('s.album', ':album', $album === '알 수 없는 앨범' ? '' : $album, $params);
$where = "s.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND $albumWhere";
if ($artist !== '') {
    $where .= " AND " . metaWhereSql('s.artist', ':artist', $artist === '알 수 없는 아티스트' ? '' : $artist, $params);
}

$orderMap = [
    'track' => 's.track_no IS NULL ASC, s.track_no ASC, s.title ASC',
    'title' => 's.title ASC',
    'plays' => 's.play_count DESC, s.title ASC',
];
$songs = fetchSongs($where, $params, $orderMap[$sort] ?? $orderMap['track'], 500);
$first = $songs[0] ?? null;
$albumLabel = albumName($album);
$artistLabel = $first ? artistName($first['artist'] ?? '') : artistName($artist);
$genreLabel = $first ? genreName($first['genre'] ?? '') : '알 수 없는 장르';
$yearLabel = $first ? metaValue($first['year'] ?? '', '-') : '-';
$songCount = count($songs);
$totalPlays = array_sum(array_map(static function ($song) {
    return (int)($song['play_count'] ?? 0);
}, $songs));
$totalDuration = array_sum(array_map(static function ($song) {
    return (int)($song['duration'] ?? 0);
}, $songs));
$albumGenres = [];
$albumYears = [];
foreach ($songs as $song) {
    $rawGenre = trim((string)($song['genre'] ?? ''));
    if ($rawGenre !== '') {
        $genreName = genreName($rawGenre);
        if ($genreName !== '' && !in_array($genreName, $albumGenres, true)) {
            $albumGenres[] = $genreName;
        }
    }
    $rawYear = trim((string)($song['year'] ?? ''));
    if ($rawYear !== '' && $rawYear !== '0' && !in_array($rawYear, $albumYears, true)) {
        $albumYears[] = $rawYear;
    }
}
$genreSummary = !empty($albumGenres) ? implode(', ', array_slice($albumGenres, 0, 3)) : $genreLabel;
$yearSummary = !empty($albumYears) ? implode(', ', array_slice($albumYears, 0, 3)) : $yearLabel;
$durationSummary = $totalDuration > 0 ? formatDuration($totalDuration) : '-';
$autoAlbumIntro = $songCount > 0
    ? sprintf('%s은(는) %s의 앨범으로, 보관함에 총 %s곡이 등록되어 있습니다.', $albumLabel, $artistLabel, number_format($songCount))
    : '이 앨범에 표시할 곡이 아직 없습니다.';
if ($songCount > 0 && $genreSummary !== '') {
    $autoAlbumIntro .= ' 장르는 ' . $genreSummary . ' 중심으로 정리되어 있습니다.';
}
if ($songCount > 0 && $yearSummary !== '-') {
    $autoAlbumIntro .= ' 대표 연도는 ' . $yearSummary . '입니다.';
}
$introTracks = array_slice($songs, 0, 4);
$albumDescription = fetchAlbumDescription($albumLabel, $artistLabel);
$customAlbumIntro = trim(ensureUtf8String($albumDescription['description'] ?? ''));
$albumIntro = $customAlbumIntro !== '' ? $customAlbumIntro : $autoAlbumIntro;
$albumIntroSource = $customAlbumIntro !== '' ? '관리자 작성' : '자동 생성';
$canEditAlbumIntro = isLoggedIn() && hasPermission('metadata_edit');
$canBulkEditAlbum = function_exists('hasPermission') && hasPermission('metadata_bulk_edit');
$returnUrl = currentRelativeUrl();

renderHeader($albumLabel, 'albums');
?>
<div class="detail-page album-detail-page">
    <div class="detail-hero album-hero-card">
        <div class="album-cover-stack">
            <img src="<?php echo h($first ? coverUrl($first) : 'assets/img/default-cover.svg'); ?>" alt="" class="detail-cover album-hero-cover" width="220" height="220" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
        </div>
        <div class="album-hero-copy">
            <span class="detail-kicker">앨범</span>
            <h1 class="page-main-title"><?php echo h($albumLabel); ?></h1>
            <p class="page-subtitle">
                <a class="song-meta-link artist-meta-link" href="artist.php?name=<?php echo rawurlencode($artistLabel); ?>"><?php echo h($artistLabel); ?></a>
                · <?php echo h($genreLabel); ?> · <?php echo h($yearLabel); ?>
            </p>
            <?php renderStatGrid([
                ['label' => '곡 수', 'value' => number_format($songCount)],
                ['label' => '총 재생시간', 'value' => $durationSummary],
                ['label' => '총 재생', 'value' => number_format($totalPlays)],
            ]); ?>
            <div class="list-play-actions album-action-row">
                <?php if (!empty($songs)): ?>
                    <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 else: ?>
                    <a class="btn btn-secondary" href="albums.php"><i class="fa-solid fa-compact-disc"></i> 앨범 목록으로 이동</a>
                <?php endif; ?>
                <?php if ($canBulkEditAlbum): ?>
                    <a class="btn btn-secondary" href="admin/bulk_edit.php?search=<?php echo rawurlencode($albumLabel); ?>"><i class="fa-solid fa-wand-magic-sparkles"></i> 표기 통합 확인</a>
                <?php endif; ?>
                <?php if ($first): ?>
                    <button type="button"
                            class="btn btn-secondary metadata-request-btn"
                            data-no-pjax
                            data-song-id="<?php echo h($first['id']); ?>"
                            data-song-title="<?php echo h($first['title']); ?>"
                            data-song-artist="<?php echo h(artistName($first['artist'] ?? '')); ?>"
                            data-song-album="<?php echo h(albumName($first['album'] ?? '')); ?>">
                        <i class="fa-solid fa-pen-to-square"></i> 정보 수정 요청
                    </button>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <section class="album-intro-section" aria-labelledby="album-intro-title">
        <div class="album-intro-header">
            <div>
                <span class="detail-kicker">앨범 노트</span>
                <h2 id="album-intro-title">앨범 소개</h2>
            </div>
            <span class="album-intro-source" data-album-intro-source><?php echo h($albumIntroSource); ?></span>
        </div>
        <p class="album-intro-text" data-album-intro-text><?php echo h($albumIntro); ?></p>
        <div class="album-intro-meta" aria-label="앨범 요약 정보">
            <span><strong>아티스트</strong><?php echo h($artistLabel); ?></span>
            <span><strong>장르</strong><?php echo h($genreSummary); ?></span>
            <span><strong>연도</strong><?php echo h($yearSummary); ?></span>
            <span><strong>총 재생시간</strong><?php echo h($durationSummary); ?></span>
        </div>
        <?php if (!empty($introTracks)): ?>
            <div class="album-intro-tracks">
                <strong>수록곡</strong>
                <div>
                    <?php foreach ($introTracks as $track): ?>
                        <a href="song.php?id=<?php echo h($track['id']); ?>"><?php echo h(metaValue($track['title'] ?? '', '제목 없음')); ?></a>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
        <?php if ($canEditAlbumIntro): ?>
            <details class="album-intro-editor">
                <summary><i class="fa-solid fa-pen-to-square"></i> 앨범 소개 수정</summary>
                <form action="album_description_save.php" method="POST" class="album-intro-edit-form" data-album-intro-form data-auto-intro="<?php echo h($autoAlbumIntro); ?>">
                    <?php echo csrfInput(); ?>
                    <input type="hidden" name="album" value="<?php echo h($albumLabel); ?>">
                    <input type="hidden" name="artist" value="<?php echo h($artistLabel); ?>">
                    <input type="hidden" name="return_url" value="<?php echo h($returnUrl); ?>">
                    <label for="album-description-editor">소개글</label>
                    <textarea id="album-description-editor" name="description" rows="6" maxlength="12000" placeholder="<?php echo h($autoAlbumIntro); ?>"><?php echo h($customAlbumIntro); ?></textarea>
                    <p class="album-intro-editor-help">비워서 저장하면 관리자 소개를 삭제하고 자동 생성 소개로 돌아갑니다.</p>
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i> 소개 저장</button>
                    </div>
                </form>
            </details>
        <?php endif; ?>
    </section>
    <form class="library-toolbar filter-sort-form" method="GET">
        <input type="hidden" name="album" value="<?php echo h($albumLabel); ?>">
        <input type="hidden" name="artist" value="<?php echo h($artistLabel); ?>">
        <select name="sort">
            <option value="track" <?php echo $sort === 'track' ? 'selected' : ''; ?>>트랙번호순</option>
            <option value="title" <?php echo $sort === 'title' ? 'selected' : ''; ?>>제목순</option>
            <option value="plays" <?php echo $sort === 'plays' ? 'selected' : ''; ?>>재생횟수순</option>
        </select>
    </form>
    <section class="home-section album-track-section">
        <div class="section-heading-row">
            <div>
                <h2 class="section-title">수록곡</h2>
                <p class="section-subtitle">트랙 번호가 있으면 수록 순서대로 정렬합니다.</p>
            </div>
            <span class="settings-muted"><?php echo number_format($songCount); ?>곡</span>
        </div>
        <?php renderSongList($songs, ['show_play_actions' => false]); ?>
    </section>
</div>
<script>
(function () {
    if (window.__MELON_LITE_ALBUM_INTRO_EDITOR) return;
    window.__MELON_LITE_ALBUM_INTRO_EDITOR = true;

    document.addEventListener('submit', async function (event) {
        const form = event.target && event.target.closest ? event.target.closest('[data-album-intro-form]') : null;
        if (!form) return;
        event.preventDefault();

        const button = form.querySelector('button[type="submit"]');
        const autoIntro = form.getAttribute('data-auto-intro') || '';
        if (button) button.disabled = true;

        try {
            const response = await fetch(form.action, {
                method: 'POST',
                body: new FormData(form),
                credentials: 'same-origin',
                cache: 'no-store',
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
            const data = await response.json();
            if (!response.ok || !data.success) {
                throw new Error(data && data.message ? data.message : '앨범 소개를 저장하지 못했습니다.');
            }

            const description = data.data && data.data.has_custom ? data.data.description : autoIntro;
            document.querySelectorAll('[data-album-intro-text]').forEach(function (node) {
                node.textContent = description;
            });
            document.querySelectorAll('[data-album-intro-source]').forEach(function (node) {
                node.textContent = data.data && data.data.has_custom ? '관리자 작성' : '자동 생성';
            });
            const textarea = form.querySelector('textarea[name="description"]');
            if (textarea && data.data && !data.data.has_custom) textarea.value = '';
            if (window.showToast) window.showToast(data.message || '앨범 소개를 저장했습니다.', 'success');
        } catch (err) {
            if (window.showToast) window.showToast(err.message || '앨범 소개를 저장하지 못했습니다.', 'error');
            else alert(err.message || '앨범 소개를 저장하지 못했습니다.');
        } finally {
            if (button) button.disabled = false;
        }
    });
})();
</script>
<?php renderFooter(); ?>
