<?php

declare(strict_types=1);

namespace PrettyLinks\Pro\Search;

/**
 * Contributes category- and tag-name matches to the link list free-text
 * search via the shared `prli_links_search_clauses` filter.
 *
 * Category/tag tables live in Pro, so the SQL fragments that join against
 * `prli_categories` / `prli_tags` also live here. Wired from Bootstrap.
 */
class TermSearchFilter
{
    /**
     * Add category- and tag-name match clauses to the link search.
     *
     * @param  array{0: array<int, string>, 1: array<int, mixed>} $clauses The accumulated search clause parts and params.
     * @param  string                                             $search  The raw user search term.
     * @param  string                                             $like    The escaped LIKE pattern for the search term.
     * @return array{0: array<int, string>, 1: array<int, mixed>}
     */
    public function apply(array $clauses, string $search, string $like): array
    {
        global $wpdb;
        [$parts, $params] = $clauses;

        $linkTerms  = $wpdb->prefix . 'prli_link_terms';
        $categories = $wpdb->prefix . 'prli_categories';
        $tags       = $wpdb->prefix . 'prli_tags';

        $parts[]  = "id IN (
            SELECT lt.link_id FROM {$linkTerms} lt
            INNER JOIN {$categories} c ON c.id = lt.term_id
            WHERE lt.taxonomy = 'category' AND c.name LIKE %s
        )";
        $params[] = $like;

        $parts[]  = "id IN (
            SELECT lt.link_id FROM {$linkTerms} lt
            INNER JOIN {$tags} t ON t.id = lt.term_id
            WHERE lt.taxonomy = 'tag' AND t.name LIKE %s
        )";
        $params[] = $like;

        return [$parts, $params];
    }
}
