<?php
declare(strict_types=1);

namespace KbMarkdownImporter\Frontend;

use KbMarkdownImporter\Access\AccessController;

final class SearchController
{
    public static function shortcodeSearch(array $atts = []): string
    {
        if (! (new AccessController())->canView()) {
            return '';
        }

        $query = sanitize_text_field(wp_unslash((string) ($_GET['kbq'] ?? '')));
        $results = $query ? self::search($query, sanitize_text_field(wp_unslash((string) ($_GET['product'] ?? ''))), sanitize_text_field(wp_unslash((string) ($_GET['version'] ?? '')))) : [];

        return (new TemplateLoader())->capture('search', [
            'title' => __('Dokumentation durchsuchen', 'kb-markdown-importer'),
            'query' => $query,
            'results' => $results,
        ]);
    }

    public static function restSearch(\WP_REST_Request $request): \WP_REST_Response
    {
        if (! (new AccessController())->canView()) {
            return new \WP_REST_Response(['results' => []], 403);
        }

        $query = sanitize_text_field((string) $request->get_param('q'));
        $product = sanitize_title((string) $request->get_param('product'));
        $version = sanitize_title((string) $request->get_param('version'));

        return new \WP_REST_Response(['results' => self::search($query, $product, $version)]);
    }

    private static function search(string $query, string $productSlug = '', string $versionSlug = ''): array
    {
        if ('' === $query) {
            return [];
        }

        $taxQuery = [];
        if ($productSlug) {
            $taxQuery[] = ['taxonomy' => 'kb_product', 'field' => 'slug', 'terms' => $productSlug];
        }
        if ($versionSlug) {
            $taxQuery[] = ['taxonomy' => 'kb_version', 'field' => 'slug', 'terms' => $versionSlug];
        }
        if (count($taxQuery) > 1) {
            $taxQuery['relation'] = 'AND';
        }

        $args = [
            'post_type' => 'kb_doc_page',
            'post_status' => 'publish',
            's' => $query,
            'posts_per_page' => 20,
        ];

        if ($taxQuery) {
            $args['tax_query'] = $taxQuery;
        }

        return (new \WP_Query($args))->posts;
    }
}
