<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/stats_functions.php';
require_once __DIR__ . '/includes/functions_tags.php';
require_once __DIR__ . '/includes/functions_notes.php';
require_once __DIR__ . '/includes/layout.php';

$pdo = getDBConnection();
$view = isset($_GET['view']) ? $_GET['view'] : 'home';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'recent';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$genreFilter = isset($_GET['genre']) ? trim($_GET['genre']) : '';
$extFilter = isset($_GET['ext']) ? trim($_GET['ext']) : '';
$onlyLiked = isset($_GET['only_liked']) ? intval($_GET['only_liked']) : 0;
$tagFilter = isset($_GET['tag']) ? (int)$_GET['tag'] : 0;
$popularTags = getPopularTags(18);

if ($view === 'home' && ($search !== '' || $genreFilter !== '' || $extFilter !== '' || $onlyLiked === 1 || $tagFilter > 0)) {
    $view = 'all';
}

if ($view === 'home') {
    $stats = getLibraryStats();
    $homeLimit = settingInt('home_section_limit', 8, 3, 20);
    $showStats = settingBool('home_show_stats', true);
    $showRecentAdded = settingBool('home_show_recent_added', true);
    $showRecentPlayed = settingBool('home_show_recent_played', true);
    $showPopular = settingBool('home_show_popular', true);
    $showLiked = settingBool('home_show_liked', true);
    $showRecommendations = settingBool('home_show_recommendations', true);
    $showAutoPlaylists = settingBool('home_show_auto_playlists', true);
    $topRatedHome = getListeningNoteSongs('top_rated', 6);
    $recentNoteHome = getListeningNoteSongs('recent_notes', 6);
    $timeContextHome = $showRecommendations ? getAutoPlaylistSongs('time_context', 6) : [];
    $hiddenGemHome = $showRecommendations ? getAutoPlaylistSongs('hidden_gems', 6) : [];
    $tagMixHome = $showRecommendations ? getAutoPlaylistSongs('tag_mix', 6) : [];

    $recentAdded = $showRecentAdded ? fetchSongs('s.is_missing = 0', [], 's.id DESC', $homeLimit) : [];
    $popularSongs = $showPopular ? fetchSongs('s.is_missing = 0', [], 's.play_count DESC, s.title ASC', $homeLimit) : [];
    $likedSongs = $showLiked ? fetchSongs('s.is_missing = 0 AND l.id IS NOT NULL', [], 'l.created_at DESC', $homeLimit) : [];
    $recommendedSongs = $showRecommendations ? getSmartRecommendedSongs(settingInt('recommendation_limit', $homeLimit, 3, 50)) : [];
    $personalHome = getHomePersonalizedData($homeLimit);
    $recentPlaylists = $pdo->query("
        SELECT p.id, p.name, p.description, p.updated_at, COUNT(ps.id) AS song_count
        FROM playlists p
        LEFT JOIN playlist_songs ps ON ps.playlist_id = p.id
        GROUP BY p.id, p.name, p.description, p.updated_at
        ORDER BY p.updated_at DESC, p.id DESC
        LIMIT 6
    ")->fetchAll();
    $recentPlayed = [];
    if ($showRecentPlayed) {
        $recentPlayedStmt = $pdo->query("
            SELECT s.id, s.title, s.artist, s.album, s.genre, s.duration, s.extension, s.play_count,
                   s.created_at, s.updated_at, IF(l.id IS NOT NULL, 1, 0) AS is_liked,
                   recent.last_played_at
            FROM (
                SELECT song_id, MAX(played_at) AS last_played_at
                FROM play_history
                GROUP BY song_id
            ) recent
            INNER JOIN songs s ON s.id = recent.song_id
            LEFT JOIN liked_songs l ON l.song_id = s.id
            WHERE s.is_missing = 0
            ORDER BY recent.last_played_at DESC
            LIMIT " . $homeLimit
        );
        $recentPlayed = $recentPlayedStmt->fetchAll();
    }

    renderHeader('홈', 'home');
    ?>
    <div class="home-dashboard">
        <div class="page-title-section">
            <h1 class="page-main-title">음악 보관함</h1>
            <p class="page-subtitle">스캔한 음악을 아티스트, 앨범, 장르 중심으로 빠르게 탐색합니다.</p>
        </div>

        <?php if ($showStats): ?>
            <?php renderStatGrid([
                ['label' => '전체 곡', 'value' => number_format($stats['songs'])],
                ['label' => '아티스트', 'value' => number_format($stats['artists'])],
                ['label' => '앨범', 'value' => number_format($stats['albums'])],
                ['label' => '장르', 'value' => number_format($stats['genres'])],
                ['label' => '플레이리스트', 'value' => number_format($stats['playlists'])],
                ['label' => '총 재생', 'value' => number_format($stats['plays'])],
            ]); ?>
        <?php endif; ?>

        <section class="home-section">
            <div class="section-heading-row">
                <h2 class="section-title">빠른 실행</h2>
            </div>
            <div class="dashboard-quick-actions">
                <a class="quick-action-card" href="index.php?view=all"><i class="fa-solid fa-music"></i><strong>전체 음악</strong><span>보관함 전체 목록으로 이동</span></a>
                <a class="quick-action-card" href="recent.php"><i class="fa-regular fa-clock"></i><strong>최근 재생 이어듣기</strong><span>최근에 들은 음악 확인</span></a>
                <a class="quick-action-card" href="recommend.php"><i class="fa-solid fa-star"></i><strong>추천 음악 보기</strong><span>취향 기반 추천 목록</span></a>
                <a class="quick-action-card" href="auto_playlists.php"><i class="fa-solid fa-wand-magic-sparkles"></i><strong>자동 플레이리스트</strong><span>조건 기반 믹스 바로가기</span></a>
                <a class="quick-action-card" href="playlist_create.php"><i class="fa-solid fa-plus"></i><strong>새 플레이리스트</strong><span>새 목록 만들기</span></a>
                <a class="quick-action-card" href="stats.php"><i class="fa-solid fa-chart-line"></i><strong>청취 리포트</strong><span>내 청취 흐름 확인</span></a>
                <?php if (isLoggedIn()): ?>
                    <a class="quick-action-card" href="admin/scan.php"><i class="fa-solid fa-rotate"></i><strong>스캔 관리</strong><span>관리 화면으로 이동</span></a>
                <?php endif; ?>
            </div>
        </section>

        <div class="home-quick-links">
            <a href="artists.php"><i class="fas fa-user"></i><span>아티스트별 탐색</span></a>
            <a href="albums.php"><i class="fas fa-compact-disc"></i><span>앨범별 탐색</span></a>
            <a href="genres.php"><i class="fas fa-tags"></i><span>장르별 탐색</span></a>
            <?php if (isLoggedIn()): ?><a href="admin/metadata.php"><i class="fas fa-triangle-exclamation"></i><span>메타데이터 누락 <?php echo number_format($stats['metadata_missing']); ?>곡</span></a><?php endif; ?>
        </div>

        <?php if (!empty($popularTags)): ?>
            <section class="home-section">
                <div class="section-heading-row">
                    <h2 class="section-title">자주 쓰는 태그</h2>
                    <a class="section-more-link" href="tags.php">더보기</a>
                </div>
                <div class="tag-cloud">
                    <?php foreach (array_slice($popularTags, 0, 12) as $tag): ?>
                        <a class="tag-badge" href="tag.php?id=<?php echo h($tag['id']); ?>"><?php echo h($tag['name']); ?> <small><?php echo number_format((int)$tag['song_count']); ?></small></a>
                    <?php endforeach; ?>
                </div>
            </section>
        <?php endif; ?>

        <div class="home-section-grid">
            <section class="home-section">
                <div class="section-heading-row">
                    <h2 class="section-title">오늘의 청취 요약</h2>
                    <a class="section-more-link" href="stats.php">리포트</a>
                </div>
                <div class="daily-summary-grid">
                    <div><span>오늘</span><strong><?php echo number_format($personalHome['summary']['today']); ?></strong></div>
                    <div><span>이번 주</span><strong><?php echo number_format($personalHome['summary']['week']); ?></strong></div>
                    <div><span>이번 달</span><strong><?php echo number_format($personalHome['summary']['month']); ?></strong></div>
                </div>
            </section>
            <?php if (isLoggedIn()): ?>
                <section class="home-section">
                    <div class="section-heading-row">
                        <h2 class="section-title">관리 알림</h2>
                        <a class="section-more-link" href="admin/index.php">관리 허브</a>
                    </div>
                    <div class="admin-alert-list">
                        <div class="admin-alert-row"><strong>메타데이터 누락</strong><span><?php echo number_format($stats['metadata_missing']); ?>곡</span></div>
                        <div class="admin-alert-row"><strong>파일 없음</strong><span><?php echo number_format($stats['missing']); ?>곡</span></div>
                        <div class="admin-alert-row"><strong>PWA 설치</strong><span>모바일 홈 화면에 추가하면 앱처럼 사용할 수 있습니다.</span></div>
                    </div>
                </section>
            <?php endif; ?>
            <?php renderMiniSongSection('최근 자주 듣는 곡', $personalHome['recent_frequent'], 'stats.php'); ?>
            <?php if ($showRecommendations) renderMiniSongSection('나를 위한 추천', $recommendedSongs, 'recommend.php'); ?>
            <?php if ($showRecommendations) renderMiniSongSection('지금 시간대 추천', $timeContextHome, 'auto_playlist.php?type=time_context'); ?>
            <?php if ($showRecommendations) renderMiniSongSection('숨은 명곡 다시 듣기', $hiddenGemHome, 'auto_playlist.php?type=hidden_gems'); ?>
            <?php if ($showRecommendations) renderMiniSongSection('자주 듣는 태그 믹스', $tagMixHome, 'auto_playlist.php?type=tag_mix'); ?>
            <?php renderMiniSongSection('오래 안 들은 좋아요 곡', $personalHome['old_liked'], 'liked.php'); ?>
            <?php renderMiniSongSection('재생한 적 없는 곡', $personalHome['never_played'], 'auto_playlist.php?type=never_played'); ?>
            <?php renderMiniSongSection('랜덤 추천 곡', $personalHome['random'], 'recommend.php'); ?>
            <?php renderMiniSongSection('내 별점 높은 곡', $topRatedHome, 'listening_notes.php?filter=top_rated'); ?>
            <?php renderMiniSongSection('최근 메모한 곡', $recentNoteHome, 'listening_notes.php?filter=recent_notes'); ?>
            <?php if (!empty($recentPlaylists)): ?>
                <section class="home-section">
                    <div class="section-heading-row">
                        <h2 class="section-title">최근 수정한 플레이리스트</h2>
                        <a class="section-more-link" href="playlists.php">더보기</a>
                    </div>
                    <div class="explore-card-grid">
                        <?php foreach ($recentPlaylists as $playlist): ?>
                            <a class="explore-card" href="playlist_view.php?id=<?php echo h($playlist['id']); ?>">
                                <strong><?php echo h($playlist['name']); ?></strong>
                                <span><?php echo number_format((int)$playlist['song_count']); ?>곡 · <?php echo h($playlist['description'] ?: '설명이 없습니다.'); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endif; ?>
            <?php if ($showAutoPlaylists): ?>
                <section class="home-section">
                    <div class="section-heading-row">
                        <h2 class="section-title">자동 플레이리스트</h2>
                        <a class="section-more-link" href="auto_playlists.php">더보기</a>
                    </div>
                    <div class="explore-card-grid">
                        <?php foreach (array_slice(getAutoPlaylistDefinitions(), 0, 4) as $type => $definition): ?>
                            <a class="explore-card" href="auto_playlist.php?type=<?php echo h($type); ?>">
                                <strong><?php echo h($definition['title']); ?></strong>
                                <span><?php echo h($definition['description']); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endif; ?>
            <?php if ($showRecentAdded) renderMiniSongSection('최근 추가된 음악', $recentAdded, 'new.php'); ?>
            <?php if ($showRecentPlayed) renderMiniSongSection('최근 재생한 음악', $recentPlayed, 'recent.php'); ?>
            <?php if ($showPopular) renderMiniSongSection('많이 들은 곡', $popularSongs, 'popular.php'); ?>
            <?php if ($showLiked) renderMiniSongSection('좋아요한 곡', $likedSongs, 'liked.php'); ?>
            <?php if (!$showRecentAdded && !$showRecentPlayed && !$showPopular && !$showLiked): ?>
                <section class="home-section">
                    <h2 class="section-title">홈 섹션이 꺼져 있습니다.</h2>
                    <p class="empty-text">설정 페이지에서 홈 화면 섹션을 다시 켤 수 있습니다.</p>
                </section>
            <?php endif; ?>
        </div>
    </div>
    <?php
    renderFooter();
    exit;
}

$genres = $pdo->query("
    SELECT DISTINCT genre FROM songs
    WHERE genre IS NOT NULL AND genre != '' AND is_missing = 0
    ORDER BY genre ASC
")->fetchAll(PDO::FETCH_COLUMN);

$where = ["s.is_missing = 0"];
$params = [];
if ($search !== '') {
    $where[] = "(s.title LIKE :search1 OR s.artist LIKE :search2 OR s.album LIKE :search3 OR s.genre LIKE :search4)";
    $params[':search1'] = '%' . $search . '%';
    $params[':search2'] = '%' . $search . '%';
    $params[':search3'] = '%' . $search . '%';
    $params[':search4'] = '%' . $search . '%';
}
if ($genreFilter !== '') {
    $where[] = "s.genre = :genre";
    $params[':genre'] = $genreFilter;
}
if ($extFilter !== '') {
    $where[] = "s.extension = :ext";
    $params[':ext'] = $extFilter;
}
if ($tagFilter > 0) {
    $where[] = "EXISTS (SELECT 1 FROM song_tags st WHERE st.song_id = s.id AND st.tag_id = :tag_id)";
    $params[':tag_id'] = $tagFilter;
}
if ($onlyLiked === 1 || $view === 'liked') {
    $where[] = "l.id IS NOT NULL";
}

switch ($sort) {
    case 'title':
        $orderBy = "s.title ASC";
        break;
    case 'artist':
        $orderBy = "s.artist ASC, s.title ASC";
        break;
    case 'album':
        $orderBy = "s.album ASC, s.track_no ASC, s.title ASC";
        break;
    case 'popular':
        $orderBy = "s.play_count DESC, s.title ASC";
        break;
    case 'recent':
    default:
        $orderBy = "s.id DESC";
        break;
}

$songs = fetchSongs(implode(" AND ", $where), $params, $orderBy);
$pageTitle = $search !== '' ? '"' . $search . '" 검색 결과' : '전체 음악';

renderHeader($pageTitle, 'all');
?>
<div class="music-list-page">
    <div class="page-title-section">
        <h1 class="page-main-title"><?php echo h($pageTitle); ?></h1>
        <p class="page-subtitle"><?php echo number_format(count($songs)); ?>곡을 표시합니다.</p>
    </div>

    <div class="list-filter-section">
        <div class="filter-left">
            <a href="index.php?view=all" class="filter-tab active">전체</a>
            <a href="new.php" class="filter-tab">최근 추가</a>
            <a href="popular.php" class="filter-tab">많이 들은 곡</a>
        </div>
        <div class="filter-right">
            <form action="index.php" method="GET" class="filter-sort-form" id="filter-form">
                <input type="hidden" name="view" value="all">
                <?php if ($search !== ''): ?><input type="hidden" name="search" value="<?php echo h($search); ?>"><?php endif; ?>
                <select name="genre" class="sort-select" onchange="document.getElementById('filter-form').submit();">
                    <option value="">모든 장르</option>
                    <?php foreach ($genres as $g): ?>
                        <option value="<?php echo h($g); ?>" <?php echo $genreFilter === $g ? 'selected' : ''; ?>><?php echo h($g); ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="tag" class="sort-select" onchange="document.getElementById('filter-form').submit();">
                    <option value="0">모든 태그</option>
                    <?php foreach ($popularTags as $tag): ?>
                        <option value="<?php echo h($tag['id']); ?>" <?php echo $tagFilter === (int)$tag['id'] ? 'selected' : ''; ?>><?php echo h($tag['name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="ext" class="sort-select" onchange="document.getElementById('filter-form').submit();">
                    <option value="">모든 형식</option>
                    <?php foreach (getAllowedExtensionsSetting() as $e): ?>
                        <option value="<?php echo h($e); ?>" <?php echo $extFilter === $e ? 'selected' : ''; ?>><?php echo h(strtoupper($e)); ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="only_liked" class="sort-select" onchange="document.getElementById('filter-form').submit();">
                    <option value="0" <?php echo $onlyLiked === 0 ? 'selected' : ''; ?>>모든 곡</option>
                    <option value="1" <?php echo $onlyLiked === 1 ? 'selected' : ''; ?>>좋아요한 곡</option>
                </select>
                <select name="sort" class="sort-select" onchange="document.getElementById('filter-form').submit();">
                    <option value="recent" <?php echo $sort === 'recent' ? 'selected' : ''; ?>>최근 등록순</option>
                    <option value="title" <?php echo $sort === 'title' ? 'selected' : ''; ?>>곡명순</option>
                    <option value="artist" <?php echo $sort === 'artist' ? 'selected' : ''; ?>>아티스트순</option>
                    <option value="album" <?php echo $sort === 'album' ? 'selected' : ''; ?>>앨범순</option>
                    <option value="popular" <?php echo $sort === 'popular' ? 'selected' : ''; ?>>많이 들은 순</option>
                </select>
            </form>
        </div>
    </div>
    <?php renderSongList($songs); ?>
</div>
<?php renderFooter(); ?>
