<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/functions_search.php';

ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');

try {
    $query = normalizeSearchQuery($_GET['q'] ?? '');
    if (function_exists('mb_strlen') ? mb_strlen($query, 'UTF-8') < 2 : strlen($query) < 2) {
        echo json_encode(['success' => true, 'query' => $query, 'items' => []], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $pdo = getDBConnection();
    $like = '%' . $query . '%';
    $items = [];

    $stmt = $pdo->prepare("
        SELECT id, title, artist, album, duration
        FROM songs
        WHERE is_missing = 0 AND COALESCE(is_hidden, 0) = 0
          AND (title LIKE :song_title OR artist LIKE :song_artist OR album LIKE :song_album OR genre LIKE :song_genre)
        ORDER BY play_count DESC, title ASC
        LIMIT 8
    ");
    $stmt->execute([
        ':song_title' => $like,
        ':song_artist' => $like,
        ':song_album' => $like,
        ':song_genre' => $like,
    ]);
    foreach ($stmt->fetchAll() as $row) {
        $items[] = [
            'type' => 'song',
            'label' => (string)$row['title'],
            'sub' => artistName($row['artist'] ?? '') . (($row['album'] ?? '') ? ' · ' . albumName($row['album']) : ''),
            'url' => 'song.php?id=' . (int)$row['id'],
            'play_id' => (int)$row['id'],
            'title' => (string)$row['title'],
            'artist' => artistName($row['artist'] ?? ''),
            'album' => albumName($row['album'] ?? ''),
            'duration' => (int)($row['duration'] ?? 0),
        ];
    }

    $stmt = $pdo->prepare("
        SELECT COALESCE(NULLIF(TRIM(artist), ''), '알 수 없는 아티스트') AS artist_name, COUNT(*) AS song_count
        FROM songs
        WHERE is_missing = 0 AND artist LIKE :artist
        GROUP BY artist_name
        ORDER BY song_count DESC, artist_name ASC
        LIMIT 5
    ");
    $stmt->execute([':artist' => $like]);
    foreach ($stmt->fetchAll() as $row) {
        $items[] = [
            'type' => 'artist',
            'label' => (string)$row['artist_name'],
            'sub' => number_format((int)$row['song_count']) . '곡',
            'url' => 'artist.php?name=' . urlencode((string)$row['artist_name']),
        ];
    }

    $stmt = $pdo->prepare("
        SELECT COALESCE(NULLIF(TRIM(album), ''), '알 수 없는 앨범') AS album_name,
               COALESCE(NULLIF(TRIM(artist), ''), '알 수 없는 아티스트') AS artist_name,
               COUNT(*) AS song_count
        FROM songs
        WHERE is_missing = 0 AND (album LIKE :album OR artist LIKE :album_artist)
        GROUP BY album_name, artist_name
        ORDER BY song_count DESC, album_name ASC
        LIMIT 5
    ");
    $stmt->execute([':album' => $like, ':album_artist' => $like]);
    foreach ($stmt->fetchAll() as $row) {
        $items[] = [
            'type' => 'album',
            'label' => (string)$row['album_name'],
            'sub' => (string)$row['artist_name'] . ' · ' . number_format((int)$row['song_count']) . '곡',
            'url' => 'album.php?album=' . urlencode((string)$row['album_name']) . '&artist=' . urlencode((string)$row['artist_name']),
        ];
    }

    if (backupTableExistsSafe('tags')) {
        $stmt = $pdo->prepare("
            SELECT t.id, t.name, COUNT(st.id) AS song_count
            FROM tags t
            LEFT JOIN song_tags st ON st.tag_id = t.id
            WHERE t.name LIKE :tag
            GROUP BY t.id, t.name
            ORDER BY song_count DESC, t.name ASC
            LIMIT 5
        ");
        $stmt->execute([':tag' => $like]);
        foreach ($stmt->fetchAll() as $row) {
            $items[] = [
                'type' => 'tag',
                'label' => (string)$row['name'],
                'sub' => number_format((int)$row['song_count']) . '곡',
                'url' => 'tag.php?id=' . (int)$row['id'],
            ];
        }
    }

    $stmt = $pdo->prepare("
        SELECT p.id, p.name, COUNT(ps.id) AS song_count
        FROM playlists p
        LEFT JOIN playlist_songs ps ON ps.playlist_id = p.id
        WHERE p.name LIKE :playlist_name OR p.description LIKE :playlist_desc
        GROUP BY p.id, p.name
        ORDER BY p.name ASC
        LIMIT 5
    ");
    $stmt->execute([':playlist_name' => $like, ':playlist_desc' => $like]);
    foreach ($stmt->fetchAll() as $row) {
        $items[] = [
            'type' => 'playlist',
            'label' => (string)$row['name'],
            'sub' => number_format((int)$row['song_count']) . '곡',
            'url' => 'playlist_view.php?id=' . (int)$row['id'],
        ];
    }

    echo json_encode(['success' => true, 'query' => $query, 'items' => array_slice($items, 0, 20)], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'search_error', 'Search suggest failed', ['error' => $e->getMessage()]);
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => '검색 후보를 불러오지 못했습니다.'], JSON_UNESCAPED_UNICODE);
}

function backupTableExistsSafe($table) {
    try {
        $stmt = getDBConnection()->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :table_name");
        $stmt->execute([':table_name' => $table]);
        return ((int)$stmt->fetchColumn()) > 0;
    } catch (Throwable $e) {
        return false;
    }
}

