<?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();
$key = isset($_GET['key']) ? preg_replace('/[^a-f0-9]/i', '', (string)$_GET['key']) : '';

$folderStmt = $pdo->prepare("
    SELECT COALESCE(NULLIF(folder_name, ''), '알 수 없는 폴더') AS folder_name
    FROM songs
    WHERE MD5(COALESCE(folder_path, '')) = :folder_key
    LIMIT 1
");
$folderStmt->execute([':folder_key' => $key]);
$folder = $folderStmt->fetch();

$songs = [];
if ($folder) {
    $songs = fetchSongs("s.is_missing = 0 AND COALESCE(s.is_hidden, 0) = 0 AND MD5(COALESCE(s.folder_path, '')) = :folder_key", [':folder_key' => $key], 's.track_no IS NULL ASC, s.track_no ASC, s.title ASC', 200);
}

renderHeader($folder ? $folder['folder_name'] : '폴더 없음', 'folders');
?>
<div class="music-list-page">
    <div class="page-title-section">
        <h1 class="page-main-title"><?php echo h($folder['folder_name'] ?? '폴더를 찾을 수 없습니다'); ?></h1>
        <p class="page-subtitle"><?php echo number_format(count($songs)); ?>곡을 표시합니다.</p>
    </div>

    <?php if (!$folder): ?>
        <div class="alert-box alert-danger">
            <div class="alert-icon"><i class="fas fa-exclamation-triangle"></i></div>
            <div class="alert-content"><p>요청한 폴더를 찾을 수 없습니다.</p></div>
        </div>
        <a href="folders.php" class="btn btn-secondary">폴더 목록으로</a>
    <?php else: ?>
        <?php renderSongList($songs); ?>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
