<?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();
$playlistId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$filter = trim((string)($_GET['q'] ?? ''));

if ($playlistId <= 0) {
    renderHeader('플레이리스트 오류', 'playlists');
    ?>
    <div class="alert-box alert-danger">
        <div class="alert-icon"><i class="fas fa-exclamation-triangle"></i></div>
        <div class="alert-content">
            <h3>잘못된 접근입니다</h3>
            <p>유효하지 않은 플레이리스트입니다.</p>
        </div>
    </div>
    <a href="playlists.php" class="btn btn-secondary">목록으로 돌아가기</a>
    <?php
    renderFooter();
    exit;
}

$playlistStmt = $pdo->prepare("SELECT * FROM playlists WHERE id = :id");
$playlistStmt->execute([':id' => $playlistId]);
$playlist = $playlistStmt->fetch();

if (!$playlist) {
    renderHeader('플레이리스트 오류', 'playlists');
    ?>
    <div class="alert-box alert-danger">
        <div class="alert-icon"><i class="fas fa-exclamation-triangle"></i></div>
        <div class="alert-content">
            <h3>플레이리스트를 찾을 수 없습니다</h3>
            <p>삭제되었거나 존재하지 않는 플레이리스트입니다.</p>
        </div>
    </div>
    <a href="playlists.php" class="btn btn-secondary">목록으로 돌아가기</a>
    <?php
    renderFooter();
    exit;
}

$where = 'ps.playlist_id = :playlist_id';
$params = [':playlist_id' => $playlistId];
if ($filter !== '') {
    $where .= ' AND (s.title LIKE :q_title OR s.artist LIKE :q_artist OR s.album LIKE :q_album OR s.genre LIKE :q_genre)';
    $like = '%' . $filter . '%';
    $params[':q_title'] = $like;
    $params[':q_artist'] = $like;
    $params[':q_album'] = $like;
    $params[':q_genre'] = $like;
}

$songsStmt = $pdo->prepare("
    SELECT
        ps.id AS playlist_song_id,
        ps.sort_order,
        ps.created_at AS added_at,
        s.id,
        s.title,
        s.artist,
        s.album,
        s.genre,
        s.duration,
        s.extension,
        s.play_count,
        s.is_missing,
        IF(l.id IS NOT NULL, 1, 0) AS is_liked
    FROM playlist_songs ps
    JOIN songs s ON ps.song_id = s.id
    LEFT JOIN liked_songs l ON s.id = l.song_id
    WHERE $where
    ORDER BY ps.sort_order ASC, ps.id ASC
");
$songsStmt->execute($params);
$songs = $songsStmt->fetchAll();

$allCountStmt = $pdo->prepare("
    SELECT COUNT(*) AS song_count, COALESCE(SUM(s.duration), 0) AS total_duration
    FROM playlist_songs ps
    JOIN songs s ON ps.song_id = s.id
    WHERE ps.playlist_id = :playlist_id
");
$allCountStmt->execute([':playlist_id' => $playlistId]);
$summary = $allCountStmt->fetch() ?: ['song_count' => 0, 'total_duration' => 0];

$coverIdsStmt = $pdo->prepare("
    SELECT s.id
    FROM playlist_songs ps
    JOIN songs s ON ps.song_id = s.id
    WHERE ps.playlist_id = :playlist_id
    ORDER BY ps.sort_order ASC, ps.id ASC
    LIMIT 4
");
$coverIdsStmt->execute([':playlist_id' => $playlistId]);
$coverIds = array_map('intval', array_column($coverIdsStmt->fetchAll(), 'id'));

renderHeader($playlist['name'], 'playlists');
?>

<div class="playlist-detail-page playlist-polish-page" data-playlist-id="<?php echo h($playlistId); ?>">
    <section class="playlist-detail-hero">
        <div class="playlist-detail-cover">
            <?php if (empty($coverIds)): ?>
                <img src="assets/img/default-cover.svg" alt="" loading="lazy" width="180" height="180">
            <?php else: ?>
                <?php foreach ($coverIds as $coverId): ?>
                    <img src="cover.php?id=<?php echo h($coverId); ?>" alt="" loading="lazy" width="90" height="90" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <div class="playlist-detail-meta">
            <a href="playlists.php" class="breadcrumb-link"><i class="fas fa-arrow-left"></i> 플레이리스트</a>
            <h1 class="page-main-title"><?php echo h($playlist['name']); ?></h1>
            <p class="page-subtitle"><?php echo h($playlist['description'] ?: '설명이 없습니다.'); ?></p>
            <div class="playlist-summary-row">
                <span><?php echo number_format((int)$summary['song_count']); ?>곡</span>
                <span><?php echo h(formatDuration((int)$summary['total_duration'])); ?></span>
                <span>생성 <?php echo h(date('Y-m-d', strtotime($playlist['created_at']))); ?></span>
                <span>수정 <?php echo h(date('Y-m-d', strtotime($playlist['updated_at'] ?? $playlist['created_at']))); ?></span>
            </div>
            <div class="playlist-action-row">
                <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>
                <a href="playlist_edit.php?id=<?php echo h($playlistId); ?>" class="btn btn-secondary"><i class="fas fa-edit"></i> 수정</a>
            </div>
        </div>
    </section>

    <section class="playlist-toolbar">
        <form method="GET" action="playlist_view.php" class="playlist-filter-form">
            <input type="hidden" name="id" value="<?php echo h($playlistId); ?>">
            <input type="search" name="q" value="<?php echo h($filter); ?>" class="form-control" placeholder="이 플레이리스트에서 검색">
            <button type="submit" class="btn btn-secondary"><i class="fas fa-search"></i> 검색</button>
            <?php if ($filter !== ''): ?><a href="playlist_view.php?id=<?php echo h($playlistId); ?>" class="btn btn-secondary">초기화</a><?php endif; ?>
        </form>
        <button type="button" class="btn btn-secondary playlist-save-order-btn"><i class="fas fa-save"></i> 순서 저장</button>
    </section>

    <?php if (empty($songs)): ?>
        <section class="empty-list-state playlist-empty-state">
            <i class="fa-solid fa-compact-disc"></i>
            <h2><?php echo $filter === '' ? '아직 담긴 곡이 없습니다' : '검색 결과가 없습니다'; ?></h2>
            <p><?php echo $filter === '' ? '음악 목록에서 + 버튼을 눌러 곡을 담아 보세요.' : '다른 검색어로 다시 찾아보세요.'; ?></p>
            <a href="index.php?view=all" class="btn btn-primary">음악 목록에서 추가</a>
        </section>
    <?php else: ?>
        <div class="playlist-song-list" id="playlist-song-list">
            <?php foreach ($songs as $index => $song): ?>
                <?php $isLiked = !empty($song['is_liked']); ?>
                <article class="playlist-song-item song-item <?php echo !empty($song['is_missing']) ? 'is-missing' : ''; ?>"
                         data-playlist-song-id="<?php echo h($song['playlist_song_id']); ?>"
                         data-id="<?php echo h($song['id']); ?>"
                         data-title="<?php echo h($song['title']); ?>"
                         data-artist="<?php echo h(artistName($song['artist'] ?? '')); ?>"
                         data-album="<?php echo h(albumName($song['album'] ?? '')); ?>"
                         data-duration="<?php echo h($song['duration'] ?? 0); ?>"
                         data-liked="<?php echo $isLiked ? '1' : '0'; ?>">
                    <div class="playlist-song-order">
                        <span class="playlist-order-number"><?php echo number_format($index + 1); ?></span>
                        <div class="playlist-order-buttons">
                            <button type="button" class="playlist-move-btn" data-direction="up" title="위로"><i class="fas fa-chevron-up"></i></button>
                            <button type="button" class="playlist-move-btn" data-direction="down" title="아래로"><i class="fas fa-chevron-down"></i></button>
                        </div>
                    </div>
                    <button type="button" class="play-row-btn playlist-row-play" title="재생"><i class="fas fa-play"></i></button>
                    <img src="cover.php?id=<?php echo h($song['id']); ?>" alt="" class="list-cover" loading="lazy" width="52" height="52" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                    <div class="playlist-song-main">
                        <a href="song.php?id=<?php echo h($song['id']); ?>" class="song-title-link"><?php echo h($song['title']); ?></a>
                        <span><?php echo h(artistName($song['artist'] ?? '')); ?> · <?php echo h(albumName($song['album'] ?? '')); ?></span>
                        <?php if (!empty($song['is_missing'])): ?><small class="missing-badge">파일 없음</small><?php endif; ?>
                    </div>
                    <div class="playlist-song-sub">
                        <span><?php echo h(genreName($song['genre'] ?? '')); ?></span>
                        <span><?php echo h(formatDuration($song['duration'] ?? null)); ?></span>
                        <span><?php echo number_format((int)($song['play_count'] ?? 0)); ?>회</span>
                    </div>
                    <div class="song-action-group playlist-song-actions">
                        <button type="button" class="like-btn <?php echo $isLiked ? 'liked' : ''; ?>" title="좋아요">
                            <i class="<?php echo $isLiked ? 'fas fa-heart' : 'far fa-heart'; ?>"></i>
                        </button>
                        <button type="button" class="add-playlist-btn" title="다른 플레이리스트에 추가"><i class="fas fa-plus"></i></button>
                        <button type="button" class="remove-playlist-song-btn btn-danger" data-playlist-id="<?php echo h($playlistId); ?>" title="플레이리스트에서 제거">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<?php renderFooter(); ?>
