<?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/api.php';

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

function searchKeywordText($value, int $max = 80): string {
    $text = trim(ensureUtf8String((string)($value ?? '')));
    $text = preg_replace('/\s+/u', ' ', $text) ?: '';
    if ($text === '' || preg_match('/[A-Za-z]:[\\\\\/]/', $text)) return '';
    if (function_exists('mb_substr')) return mb_substr($text, 0, $max, 'UTF-8');
    return substr($text, 0, $max);
}

function searchKeywordPush(array &$items, string $label, string $type, string $reason = ''): void {
    $label = searchKeywordText($label);
    if ($label === '') return;
    $key = function_exists('mb_strtolower') ? mb_strtolower($label, 'UTF-8') : strtolower($label);
    if (isset($items[$key])) return;
    $items[$key] = [
        'label' => $label,
        'type' => $type,
        'reason' => searchKeywordText($reason, 100),
        'url' => 'search.php?q=' . rawurlencode($label),
    ];
}

try {
    $pdo = getDBConnection();
    $items = [];

    $stmt = $pdo->prepare("
        SELECT COALESCE(NULLIF(TRIM(s.artist), ''), '') AS keyword, COUNT(ph.id) AS score
        FROM play_history ph
        INNER JOIN songs s ON s.id = ph.song_id
        WHERE COALESCE(s.is_missing, 0) = 0
          AND COALESCE(s.is_hidden, 0) = 0
          AND ph.played_at >= DATE_SUB(NOW(), INTERVAL 60 DAY)
          AND TRIM(COALESCE(s.artist, '')) <> ''
        GROUP BY keyword
        ORDER BY score DESC, keyword ASC
        LIMIT 6
    ");
    $stmt->execute();
    foreach ($stmt->fetchAll() as $row) {
        searchKeywordPush($items, $row['keyword'] ?? '', 'artist', '최근 자주 들은 아티스트');
    }

    $stmt = $pdo->prepare("
        SELECT COALESCE(NULLIF(TRIM(genre), ''), '') AS keyword, COUNT(*) AS song_count, COALESCE(SUM(play_count), 0) AS total_plays
        FROM songs
        WHERE COALESCE(is_missing, 0) = 0
          AND COALESCE(is_hidden, 0) = 0
          AND TRIM(COALESCE(genre, '')) <> ''
          AND genre <> 'Unknown'
        GROUP BY keyword
        ORDER BY total_plays DESC, song_count DESC, keyword ASC
        LIMIT 8
    ");
    $stmt->execute();
    foreach ($stmt->fetchAll() as $row) {
        searchKeywordPush($items, $row['keyword'] ?? '', 'genre', '많이 재생된 장르');
    }

    $stmt = $pdo->prepare("
        SELECT COALESCE(NULLIF(TRIM(artist), ''), '') AS keyword, COUNT(*) AS song_count, COALESCE(SUM(play_count), 0) AS total_plays
        FROM songs
        WHERE COALESCE(is_missing, 0) = 0
          AND COALESCE(is_hidden, 0) = 0
          AND TRIM(COALESCE(artist, '')) <> ''
        GROUP BY keyword
        ORDER BY total_plays DESC, song_count DESC, keyword ASC
        LIMIT 8
    ");
    $stmt->execute();
    foreach ($stmt->fetchAll() as $row) {
        searchKeywordPush($items, $row['keyword'] ?? '', 'artist', '많이 들은 아티스트');
    }

    $stmt = $pdo->prepare("
        SELECT title AS keyword, play_count
        FROM songs
        WHERE COALESCE(is_missing, 0) = 0
          AND COALESCE(is_hidden, 0) = 0
          AND TRIM(COALESCE(title, '')) <> ''
        ORDER BY play_count DESC, title ASC
        LIMIT 6
    ");
    $stmt->execute();
    foreach ($stmt->fetchAll() as $row) {
        searchKeywordPush($items, $row['keyword'] ?? '', 'song', '많이 들은 곡');
    }

    $keywords = array_slice(array_values($items), 0, 16);
    apiSuccess(['items' => $keywords], '', ['count' => count($keywords)], ['items' => $keywords]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'search_error', 'Search keywords failed', ['error' => $e->getMessage()]);
    apiError('추천 검색어를 불러오지 못했습니다.', 'server_error', 500);
}
