<?php
declare(strict_types=1);

/**
 * EnglishSpeak
 * File: teacher/flashcards/ajax/search.php
 *
 * Search the shared Word Library for Flashcard Set Editor.
 * Keeps the existing JSON contract used by flashcards.js:
 * {
 *   "success": true,
 *   "items": [...]
 * }
 */

require __DIR__ . '/../../partials/auth.php';
require_once __DIR__ . '/../../../config/database.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

function flashcardSearchResponse(
    bool $success,
    array $items = [],
    string $message = ''
): never {
    http_response_code($success ? 200 : 400);

    echo json_encode(
        [
            'success' => $success,
            'items' => $items,
            'message' => $message,
        ],
        JSON_UNESCAPED_UNICODE
        | JSON_UNESCAPED_SLASHES
        | JSON_INVALID_UTF8_SUBSTITUTE
    );

    exit;
}

try {
    $pdo = getDbConnection();

    $query = trim((string)($_GET['q'] ?? ''));
    $setId = max(
        0,
        (int)(filter_input(INPUT_GET, 'set_id', FILTER_VALIDATE_INT) ?: 0)
    );

    if (mb_strlen($query) > 120) {
        flashcardSearchResponse(
            false,
            [],
            'Search text is too long.'
        );
    }

    if ($setId > 0) {
        $setStmt = $pdo->prepare(
            'SELECT id
             FROM flashcard_sets
             WHERE id = ?
             LIMIT 1'
        );
        $setStmt->execute([$setId]);

        if (!$setStmt->fetchColumn()) {
            flashcardSearchResponse(
                false,
                [],
                'Flashcard Set not found.'
            );
        }
    }

    $where = ["w.status = 'active'"];
    $params = [$setId];

    if ($query !== '') {
        $like = '%' . $query . '%';

        $where[] = "(
            w.word LIKE ?
            OR w.meaning_vi LIKE ?
            OR w.phonetic LIKE ?
            OR w.part_of_speech LIKE ?
            OR EXISTS (
                SELECT 1
                FROM topic_words tw_search
                INNER JOIN topics t_search
                    ON t_search.id = tw_search.topic_id
                WHERE tw_search.word_id = w.id
                  AND t_search.name LIKE ?
            )
        )";

        array_push(
            $params,
            $like,
            $like,
            $like,
            $like,
            $like
        );
    }

    $sql = "
        SELECT
            w.id,
            w.word,
            w.meaning_vi,
            w.phonetic,
            w.image_path,
            w.audio_us_path,
            w.part_of_speech,
            w.difficulty_level,

            (
                SELECT we.example_en
                FROM word_examples we
                WHERE we.word_id = w.id
                  AND we.status = 'active'
                ORDER BY we.sort_order ASC, we.id ASC
                LIMIT 1
            ) AS example_en,

            (
                SELECT GROUP_CONCAT(
                    DISTINCT t.name
                    ORDER BY t.name
                    SEPARATOR ', '
                )
                FROM topic_words tw
                INNER JOIN topics t
                    ON t.id = tw.topic_id
                WHERE tw.word_id = w.id
            ) AS topics,

            EXISTS (
                SELECT 1
                FROM flashcard_set_words fsw
                WHERE fsw.set_id = ?
                  AND fsw.word_id = w.id
            ) AS is_selected

        FROM words w
        WHERE " . implode(' AND ', $where) . "
        ORDER BY
            CASE
                WHEN ? <> ''
                 AND LOWER(w.word) = LOWER(?) THEN 0
                WHEN ? <> ''
                 AND LOWER(w.word) LIKE LOWER(CONCAT(?, '%')) THEN 1
                ELSE 2
            END,
            w.word ASC,
            w.id ASC
        LIMIT 80
    ";

    array_push(
        $params,
        $query,
        $query,
        $query,
        $query
    );

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    $items = array_map(
        static function (array $word): array {
            return [
                'id' => (int)$word['id'],
                'word' => (string)$word['word'],
                'meaning' => (string)($word['meaning_vi'] ?? ''),
                'ipa' => (string)($word['phonetic'] ?? ''),
                'image' => !empty($word['image_path'])
                    ? es_url((string)$word['image_path'])
                    : '',
                'audio' => !empty($word['audio_us_path'])
                    ? es_url((string)$word['audio_us_path'])
                    : '',
                'partOfSpeech' => (string)($word['part_of_speech'] ?? ''),
                'level' => !empty($word['difficulty_level'])
                    ? 'Level ' . (int)$word['difficulty_level']
                    : '',
                'example' => (string)($word['example_en'] ?? ''),
                'topics' => (string)($word['topics'] ?? ''),
                'isSelected' => (bool)$word['is_selected'],
            ];
        },
        $stmt->fetchAll(PDO::FETCH_ASSOC)
    );

    flashcardSearchResponse(true, $items);
} catch (Throwable $e) {
    error_log(
        'EnglishSpeak flashcards/ajax/search.php: '
        . $e->getMessage()
    );

    flashcardSearchResponse(
        false,
        [],
        'Unable to search Word Library.'
    );
}
