<?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();
$stmt = $pdo->query("
    SELECT
        MD5(COALESCE(folder_path, '')) AS folder_key,
        COALESCE(NULLIF(folder_name, ''), '알 수 없는 폴더') AS folder_name,
        COUNT(*) AS song_count,
        MAX(created_at) AS recent_added,
        COUNT(DISTINCT SUBSTRING_INDEX(relative_path, '/', 1)) AS child_hint
    FROM songs
    WHERE is_missing = 0 AND COALESCE(is_hidden, 0) = 0
    GROUP BY folder_key, folder_name
    ORDER BY folder_name ASC
");
$folders = $stmt->fetchAll();

renderHeader('폴더별 보기', 'folders');
?>
<div class="explore-page">
    <div class="page-title-section">
        <h1 class="page-main-title">폴더별 보기</h1>
        <p class="page-subtitle">스캔된 음악을 저장 폴더 기준으로 탐색합니다. 실제 전체 경로는 표시하지 않습니다.</p>
    </div>

    <?php if (empty($folders)): ?>
        <section class="home-section"><p class="empty-text">표시할 폴더가 없습니다.</p></section>
    <?php else: ?>
        <div class="explore-card-grid folder-card-grid">
            <?php foreach ($folders as $folder): ?>
                <a class="explore-card folder-card" href="folder.php?key=<?php echo h($folder['folder_key']); ?>">
                    <i class="fa-solid fa-folder"></i>
                    <strong><?php echo h($folder['folder_name']); ?></strong>
                    <span><?php echo number_format((int)$folder['song_count']); ?>곡 · 최근 추가 <?php echo h($folder['recent_added'] ?: '-'); ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
