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

$filters = searchFilterState();
$query = $filters['q'];
$sortOptions = searchSortOptions();
$searchResult = ['songs' => [], 'total' => 0, 'page' => 1, 'page_size' => searchPageSize(), 'pages' => 1];
$categories = ['artists' => [], 'albums' => [], 'genres' => [], 'playlists' => [], 'tags' => []];
$recentFallback = [];
$popularFallback = [];
$availableTags = [];
$errorMessage = '';

try {
    ensureTagTables();
    $availableTags = getPopularTags(60);
    if ($query !== '' || $filters['tag_id'] > 0 || $filters['min_rating'] > 0 || $filters['liked'] !== '' || $filters['has_note'] !== '' || $filters['has_lyrics'] !== '' || $filters['artist'] !== '' || $filters['album'] !== '' || $filters['genre'] !== '' || $filters['playlist_id'] > 0 || $filters['popular_only'] || $filters['manual_only'] || $filters['hide_missing_meta']) {
        $searchResult = searchSongsAdvanced($filters);
        if ($query !== '') $categories = searchCategoryResults($query);
    } else {
        $recentFallback = searchRecentFallbackSongs(12);
        $popularFallback = searchPopularFallbackSongs(12);
    }
} catch (Throwable $e) {
    $errorMessage = '검색 중 오류가 발생했습니다.';
    if (function_exists('writeAppLog')) writeAppLog('error', 'search_error', 'Search page failed', ['error' => $e->getMessage(), 'query' => $query]);
}

function searchSelected($a, $b) {
    return (string)$a === (string)$b ? 'selected' : '';
}

function searchChecked($value) {
    return !empty($value) ? 'checked' : '';
}

function renderSearchPager($result) {
    if (($result['pages'] ?? 1) <= 1) return;
    $page = (int)$result['page'];
    $pages = (int)$result['pages'];
    $start = max(1, $page - 2);
    $end = min($pages, $page + 2);
    ?>
    <nav class="search-pagination" aria-label="검색 페이지">
        <?php if ($page > 1): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(searchUrlWith(['page' => $page - 1])); ?>">이전</a><?php endif; ?>
        <?php for ($i = $start; $i <= $end; $i++): ?>
            <a class="pager-link <?php echo $i === $page ? 'active' : ''; ?>" href="<?php echo h(searchUrlWith(['page' => $i])); ?>"><?php echo $i; ?></a>
        <?php endfor; ?>
        <?php if ($page < $pages): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(searchUrlWith(['page' => $page + 1])); ?>">다음</a><?php endif; ?>
    </nav>
    <?php
}

function renderFilterBadges($filters, $tags) {
    $badges = [];
    foreach (['artist' => '아티스트', 'album' => '앨범', 'genre' => '장르'] as $key => $label) {
        if ($filters[$key] !== '') $badges[] = [$label, $filters[$key], searchUrlWith([$key => null, 'page' => 1])];
    }
    if ($filters['tag_id'] > 0) {
        $name = '태그 #' . $filters['tag_id'];
        foreach ($tags as $tag) {
            if ((int)$tag['id'] === (int)$filters['tag_id']) {
                $name = $tag['name'];
                break;
            }
        }
        $badges[] = ['태그', $name, searchUrlWith(['tag_id' => null, 'page' => 1])];
    }
    if ($filters['min_rating'] > 0) $badges[] = ['별점', $filters['min_rating'] . '점 이상', searchUrlWith(['min_rating' => null, 'page' => 1])];
    if ($filters['liked'] !== '') $badges[] = ['좋아요', $filters['liked'] === '1' ? '좋아요만' : '좋아요 제외', searchUrlWith(['liked' => null, 'page' => 1])];
    if ($filters['has_note'] !== '') $badges[] = ['메모', $filters['has_note'] === '1' ? '있음' : '없음', searchUrlWith(['has_note' => null, 'page' => 1])];
    if ($filters['has_lyrics'] !== '') $badges[] = ['가사', $filters['has_lyrics'] === '1' ? '있음' : '없음', searchUrlWith(['has_lyrics' => null, 'page' => 1])];
    if ($filters['popular_only']) $badges[] = ['재생', '재생 기록 있음', searchUrlWith(['popular_only' => null, 'page' => 1])];
    if ($filters['manual_only']) $badges[] = ['수동 수정', '보호됨', searchUrlWith(['manual_only' => null, 'page' => 1])];
    if ($filters['hide_missing_meta']) $badges[] = ['메타데이터', '누락 제외', searchUrlWith(['hide_missing_meta' => null, 'page' => 1])];
    if (empty($badges)) return;
    ?>
    <div class="active-filter-badges">
        <?php foreach ($badges as $badge): ?>
            <a class="filter-badge" href="<?php echo h($badge[2]); ?>"><span><?php echo h($badge[0]); ?></span><?php echo h($badge[1]); ?><i class="fa-solid fa-xmark"></i></a>
        <?php endforeach; ?>
    </div>
    <?php
}

renderHeader('통합 검색', 'search');
?>
<div class="search-page enhanced-search-page" data-search-page>
    <div class="page-title-section">
        <h1 class="page-main-title">통합 검색</h1>
        <p class="page-subtitle">곡, 아티스트, 앨범, 장르, 태그, 가사, 메모, 플레이리스트를 한 번에 찾습니다.</p>
    </div>

    <?php if ($errorMessage !== ''): ?>
        <div class="notice notice-danger"><?php echo h($errorMessage); ?></div>
    <?php endif; ?>

    <form action="search.php" method="GET" class="search-page-form enhanced-search-form" data-search-form>
        <i class="fas fa-search"></i>
        <input type="text" name="q" value="<?php echo h($query); ?>" maxlength="120" autocomplete="off" placeholder="곡, 아티스트, 태그, 가사, 메모 검색">
        <button type="submit" class="btn btn-primary">검색</button>
    </form>

    <div class="search-recent-panel" data-recent-search-panel hidden>
        <div class="section-heading-row">
            <h2 class="section-title">최근 검색어</h2>
            <button type="button" class="btn btn-secondary btn-sm" data-clear-recent-searches>전체 삭제</button>
        </div>
        <div class="recent-search-list" data-recent-search-list></div>
    </div>

    <details class="advanced-filter-panel" <?php echo $query !== '' || $searchResult['total'] > 0 ? 'open' : ''; ?>>
        <summary><i class="fa-solid fa-sliders"></i> 고급 필터 / 정렬</summary>
        <form action="search.php" method="GET" class="advanced-filter-form">
            <input type="hidden" name="q" value="<?php echo h($query); ?>">
            <div class="filter-grid">
                <label>아티스트<input class="form-control" type="text" name="artist" value="<?php echo h($filters['artist']); ?>"></label>
                <label>앨범<input class="form-control" type="text" name="album" value="<?php echo h($filters['album']); ?>"></label>
                <label>장르<input class="form-control" type="text" name="genre" value="<?php echo h($filters['genre']); ?>"></label>
                <label>태그
                    <select class="form-control" name="tag_id">
                        <option value="">전체 태그</option>
                        <?php foreach ($availableTags as $tag): ?>
                            <option value="<?php echo h($tag['id']); ?>" <?php echo searchSelected($filters['tag_id'], $tag['id']); ?>><?php echo h($tag['name']); ?> (<?php echo number_format((int)$tag['song_count']); ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>별점
                    <select class="form-control" name="min_rating">
                        <option value="">전체</option>
                        <?php for ($i = 1; $i <= 5; $i++): ?><option value="<?php echo $i; ?>" <?php echo searchSelected($filters['min_rating'], $i); ?>><?php echo $i; ?>점 이상</option><?php endfor; ?>
                    </select>
                </label>
                <label>좋아요
                    <select class="form-control" name="liked">
                        <option value="">전체</option>
                        <option value="1" <?php echo searchSelected($filters['liked'], '1'); ?>>좋아요만</option>
                        <option value="0" <?php echo searchSelected($filters['liked'], '0'); ?>>좋아요 제외</option>
                    </select>
                </label>
                <label>메모
                    <select class="form-control" name="has_note">
                        <option value="">전체</option>
                        <option value="1" <?php echo searchSelected($filters['has_note'], '1'); ?>>메모 있음</option>
                        <option value="0" <?php echo searchSelected($filters['has_note'], '0'); ?>>메모 없음</option>
                    </select>
                </label>
                <label>가사
                    <select class="form-control" name="has_lyrics">
                        <option value="">전체</option>
                        <option value="1" <?php echo searchSelected($filters['has_lyrics'], '1'); ?>>가사 있음</option>
                        <option value="0" <?php echo searchSelected($filters['has_lyrics'], '0'); ?>>가사 없음</option>
                    </select>
                </label>
                <label>정렬
                    <select class="form-control" name="sort">
                        <?php foreach ($sortOptions as $key => $label): ?><option value="<?php echo h($key); ?>" <?php echo searchSelected($filters['sort'], $key); ?>><?php echo h($label); ?></option><?php endforeach; ?>
                    </select>
                </label>
            </div>
            <div class="filter-check-row">
                <label><input type="checkbox" name="recent_played" value="1" <?php echo searchChecked($filters['recent_played'] === '1'); ?>> 최근 재생 있음</label>
                <label><input type="checkbox" name="popular_only" value="1" <?php echo searchChecked($filters['popular_only']); ?>> 재생 기록 있음</label>
                <label><input type="checkbox" name="manual_only" value="1" <?php echo searchChecked($filters['manual_only']); ?>> 수동 수정 보호</label>
                <label><input type="checkbox" name="hide_missing_meta" value="1" <?php echo searchChecked($filters['hide_missing_meta']); ?>> 메타데이터 누락 제외</label>
            </div>
            <div class="filter-actions">
                <button type="submit" class="btn btn-primary">필터 적용</button>
                <a href="search.php<?php echo $query !== '' ? '?q=' . urlencode($query) : ''; ?>" class="btn btn-secondary">필터 초기화</a>
            </div>
        </form>
    </details>

    <?php renderFilterBadges($filters, $availableTags); ?>

    <?php if ($query === '' && $searchResult['total'] === 0): ?>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">최근 추가 음악</h2></div>
            <?php renderSongList($recentFallback, ['show_play_actions' => false]); ?>
        </section>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">많이 들은 곡</h2></div>
            <?php renderSongList($popularFallback, ['show_play_actions' => false]); ?>
        </section>
    <?php else: ?>
        <section class="home-section">
            <div class="section-heading-row">
                <h2 class="section-title">곡 검색 결과</h2>
                <span class="settings-muted"><?php echo number_format((int)$searchResult['total']); ?>곡 · <?php echo number_format((int)$searchResult['page']); ?>/<?php echo number_format((int)$searchResult['pages']); ?>페이지</span>
            </div>
            <?php renderSongList($searchResult['songs']); ?>
            <?php renderSearchPager($searchResult); ?>
        </section>

        <?php if ($query !== ''): ?>
            <div class="search-category-grid">
                <section class="home-section">
                    <h2 class="section-title">아티스트</h2>
                    <div class="explore-card-grid">
                        <?php foreach ($categories['artists'] as $artist): ?>
                            <a class="explore-card media-explore-card" href="artist.php?name=<?php echo urlencode($artist['artist_name']); ?>">
                                <img src="cover.php?id=<?php echo h($artist['cover_song_id']); ?>" alt="" loading="lazy" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                                <strong><?php echo h($artist['artist_name']); ?></strong>
                                <span><?php echo number_format((int)$artist['song_count']); ?>곡 · <?php echo number_format((int)$artist['album_count']); ?>앨범</span>
                            </a>
                        <?php endforeach; ?>
                        <?php if (empty($categories['artists'])): ?><p class="empty-text">아티스트 결과가 없습니다.</p><?php endif; ?>
                    </div>
                </section>

                <section class="home-section">
                    <h2 class="section-title">앨범</h2>
                    <div class="album-card-grid">
                        <?php foreach ($categories['albums'] as $album): ?>
                            <a class="album-card" href="album.php?album=<?php echo urlencode($album['album_name']); ?>&artist=<?php echo urlencode($album['artist_name']); ?>">
                                <img src="cover.php?id=<?php echo h($album['cover_song_id']); ?>" alt="" class="album-card-cover" loading="lazy" width="120" height="120" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
                                <strong><?php echo h($album['album_name']); ?></strong>
                                <span><?php echo h($album['artist_name']); ?> · <?php echo number_format((int)$album['song_count']); ?>곡</span>
                            </a>
                        <?php endforeach; ?>
                        <?php if (empty($categories['albums'])): ?><p class="empty-text">앨범 결과가 없습니다.</p><?php endif; ?>
                    </div>
                </section>

                <section class="home-section">
                    <h2 class="section-title">장르 / 태그</h2>
                    <div class="tag-cloud">
                        <?php foreach ($categories['genres'] as $genre): ?>
                            <a class="tag-badge" href="search.php?genre=<?php echo urlencode($genre['genre_name']); ?>"><?php echo h($genre['genre_name']); ?> <small><?php echo number_format((int)$genre['song_count']); ?></small></a>
                        <?php endforeach; ?>
                        <?php foreach ($categories['tags'] 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; ?>
                        <?php if (empty($categories['genres']) && empty($categories['tags'])): ?><p class="empty-text">장르/태그 결과가 없습니다.</p><?php endif; ?>
                    </div>
                </section>

                <section class="home-section">
                    <h2 class="section-title">플레이리스트</h2>
                    <div class="explore-card-grid">
                        <?php foreach ($categories['playlists'] 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']); ?>곡</span>
                            </a>
                        <?php endforeach; ?>
                        <?php if (empty($categories['playlists'])): ?><p class="empty-text">플레이리스트 결과가 없습니다.</p><?php endif; ?>
                    </div>
                </section>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>

