<?php

namespace FleekDash\Controllers\Post;

/**
 * Extends WordPress post search to include slug (post_name) and ID.
 *
 * @package FleekDash\Controllers\Post
 */
class PostSearchFilter
{
    /**
     * Extend WordPress search WHERE clause to include post slug and optional ID.
     *
     * @param string $where SQL WHERE clause
     * @param \WP_Query $query The WP_Query object
     * @return string Modified WHERE clause
     */
    public static function extendSearchToIncludeSlug(string $where, \WP_Query $query): string
    {
        global $wpdb;

        if (empty($query->query_vars['s'])) {
            return $where;
        }

        $searchTerm = $query->query_vars['s'];
        $escapedTerm = $wpdb->esc_like($searchTerm);
        $escapedTerm = '%' . $escapedTerm . '%';

        $idCondition = '';
        if (is_numeric($searchTerm)) {
            $postId = (int) $searchTerm;
            $idCondition = "({$wpdb->posts}.ID = $postId)";
        }

        $postNameCondition = "({$wpdb->posts}.post_name LIKE '$escapedTerm')";
        $additionalConditions = " OR $postNameCondition";
        if ($idCondition !== '') {
            $additionalConditions .= " OR $idCondition";
        }

        // Two separate patterns to stay under Sonar regex complexity limit (no optional group)
        $patternWithExcerpt = '/\(\([^)]+post_title[^)]+\)\s+OR\s+\([^)]+post_content[^)]+\)\s+OR\s+\([^)]+post_excerpt[^)]+\)\)/';
        $patternWithoutExcerpt = '/\(\([^)]+post_title[^)]+\)\s+OR\s+\([^)]+post_content[^)]+\)\)/';
        $matched = preg_match($patternWithExcerpt, $where);
        if ($matched) {
            $where = preg_replace($patternWithExcerpt, '$0' . $additionalConditions, $where, 1);
        } elseif (preg_match($patternWithoutExcerpt, $where)) {
            $where = preg_replace($patternWithoutExcerpt, '$0' . $additionalConditions, $where, 1);
        } elseif (strpos($where, 'post_title') !== false) {
            $fallbackPattern = '/(\(\([^)]+post_title[^)]+\)[^)]*\))/';
            $where = preg_replace($fallbackPattern, '$1' . $additionalConditions, $where, 1);
        }

        return $where;
    }
}
