<?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();
$message = '';
$messageType = 'success';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    if (!verifyCsrfToken()) {
        $message = '요청을 확인할 수 없습니다. 새로고침 후 다시 시도해 주세요.';
        $messageType = 'danger';
    } else {
        $name = trim((string)($_POST['name'] ?? ''));
        $description = trim((string)($_POST['description'] ?? ''));
        $displayScope = normalizePlaylistDisplayScope18($_POST['display_scope'] ?? 'private');

        if ($name === '') {
            $message = '플레이리스트 이름을 입력해 주세요.';
            $messageType = 'danger';
        } else {
            try {
                $stmt = $pdo->prepare("INSERT INTO playlists (name, description, display_scope) VALUES (:name, :description, :display_scope)");
                $stmt->execute([
                    ':name' => function_exists('mb_substr') ? mb_substr($name, 0, 255, 'UTF-8') : substr($name, 0, 255),
                    ':description' => $description !== '' ? $description : null,
                    ':display_scope' => $displayScope,
                ]);
                $message = '새 플레이리스트를 만들었습니다.';
            } catch (Throwable $e) {
                if (function_exists('writeAppLog')) {
                    writeAppLog('error', 'playlist_error', 'Playlist create failed', ['error' => $e->getMessage()]);
                }
                $message = '플레이리스트를 만들지 못했습니다.';
                $messageType = 'danger';
            }
        }
    }
}

$playlistsStmt = $pdo->query("
    SELECT
        p.id,
        p.name,
        p.description,
        p.display_scope,
        p.created_at,
        p.updated_at,
        COUNT(ps.id) AS song_count,
        COALESCE(SUM(s.duration), 0) AS total_duration,
        SUBSTRING_INDEX(GROUP_CONCAT(s.id ORDER BY ps.sort_order ASC SEPARATOR ','), ',', 4) AS cover_ids
    FROM playlists p
    LEFT JOIN playlist_songs ps ON p.id = ps.playlist_id
    LEFT JOIN songs s ON ps.song_id = s.id AND COALESCE(s.is_missing, 0) = 0 AND COALESCE(s.is_hidden, 0) = 0
    GROUP BY p.id, p.name, p.description, p.display_scope, p.created_at, p.updated_at
    ORDER BY (p.display_scope = 'home') DESC, p.updated_at DESC, p.id DESC
");
$playlists = $playlistsStmt->fetchAll();

renderHeader('내 플레이리스트', 'playlists');
?>

<div class="playlists-page playlist-polish-page">
    <div class="page-title-section playlist-hero">
        <div>
            <h1 class="page-main-title"><i class="fas fa-list-alt"></i> 내 플레이리스트</h1>
            <p class="page-subtitle">자주 듣는 곡을 묶고, 순서를 다듬고, 바로 대기열로 이어 들을 수 있습니다.</p>
        </div>
        <a href="playlist_create.php" class="btn btn-primary"><i class="fas fa-plus"></i> 새 플레이리스트</a>
    </div>

    <?php if ($message !== ''): ?>
        <div class="alert-box alert-<?php echo h($messageType); ?>">
            <div class="alert-icon"><i class="fas <?php echo $messageType === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?>"></i></div>
            <div class="alert-content"><p><?php echo h($message); ?></p></div>
        </div>
    <?php endif; ?>

    <section class="playlist-create-card">
        <h2><i class="fas fa-plus-circle"></i> 빠른 생성</h2>
        <form action="playlists.php" method="POST" class="playlist-inline-form">
            <?php echo csrfInput(); ?>
            <input type="hidden" name="action" value="create">
            <input type="text" name="name" class="form-control" placeholder="플레이리스트 이름" maxlength="255" required>
            <input type="text" name="description" class="form-control" placeholder="설명, 분위기, 용도" maxlength="1000">
            <select name="display_scope" class="form-control" aria-label="표시 옵션">
                <?php foreach (playlistDisplayScopeOptions18() as $scopeValue => $scopeLabel): ?>
                    <option value="<?php echo h($scopeValue); ?>"><?php echo h($scopeLabel); ?></option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="btn btn-primary">생성</button>
        </form>
    </section>

    <?php if (empty($playlists)): ?>
        <section class="empty-list-state playlist-empty-state">
            <i class="fa-solid fa-music"></i>
            <h2>아직 만든 플레이리스트가 없습니다</h2>
            <p>좋아하는 곡을 하나씩 담아 나만의 음악 흐름을 만들어 보세요.</p>
            <a href="playlist_create.php" class="btn btn-primary">첫 플레이리스트 만들기</a>
        </section>
    <?php else: ?>
        <section class="playlist-card-grid">
            <?php foreach ($playlists as $playlist): ?>
                <?php
                $coverIds = array_values(array_filter(array_map('intval', explode(',', (string)($playlist['cover_ids'] ?? '')))));
                $durationText = formatDuration((int)($playlist['total_duration'] ?? 0));
                $displayScope = normalizePlaylistDisplayScope18($playlist['display_scope'] ?? 'private');
                ?>
                <article class="playlist-card">
                    <a class="playlist-card-cover" href="playlist_view.php?id=<?php echo h($playlist['id']); ?>" aria-label="<?php echo h($playlist['name']); ?>">
                        <?php if (empty($coverIds)): ?>
                            <img src="assets/img/default-cover.svg" alt="" loading="lazy" width="160" height="160">
                        <?php else: ?>
                            <?php foreach (array_slice($coverIds, 0, 4) as $coverId): ?>
                                <img src="<?php echo h(coverUrl($coverId)); ?>" alt="" loading="lazy" width="80" height="80" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </a>
                    <div class="playlist-card-body">
                        <span class="playlist-scope-badge scope-<?php echo h($displayScope); ?>"><?php echo h(playlistDisplayScopeLabel18($displayScope)); ?></span>
                        <a class="playlist-card-title" href="playlist_view.php?id=<?php echo h($playlist['id']); ?>"><?php echo h($playlist['name']); ?></a>
                        <p><?php echo h($playlist['description'] ?: '설명이 없습니다.'); ?></p>
                        <div class="playlist-card-meta">
                            <span><?php echo number_format((int)$playlist['song_count']); ?>곡</span>
                            <span><?php echo h($durationText); ?></span>
                            <span>수정 <?php echo h(date('Y-m-d', strtotime($playlist['updated_at'] ?? $playlist['created_at']))); ?></span>
                        </div>
                        <div class="playlist-card-actions">
                            <a href="playlist_view.php?id=<?php echo h($playlist['id']); ?>" class="btn btn-primary btn-sm"><i class="fas fa-play"></i> 열기</a>
                            <a href="playlist_edit.php?id=<?php echo h($playlist['id']); ?>" class="btn btn-secondary btn-sm"><i class="fas fa-edit"></i> 수정</a>
                            <form action="playlist_delete.php" method="POST" onsubmit="return confirm('이 플레이리스트를 삭제할까요? 수록곡 연결 정보도 함께 삭제됩니다.');">
                                <?php echo csrfInput(); ?>
                                <input type="hidden" name="id" value="<?php echo h($playlist['id']); ?>">
                                <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-trash-alt"></i></button>
                            </form>
                        </div>
                    </div>
                </article>
            <?php endforeach; ?>
        </section>
    <?php endif; ?>
</div>

<?php renderFooter(); ?>
