<?php get_header(); ?>

<div itemscope itemtype="https://schema.org/WebSite" class="content-middle articles-wrapper">
    <link itemprop="url" content="<?php echo home_url(); ?>"/>
    <?php get_template_part('partials/rubrics-mobile'); ?>
    <div class="section-title">
        <h1 class="section-title__title">Поиск</h1>
    </div>
    <form itemprop="potentialAction" itemscope itemtype="https://schema.org/SearchAction" class="search-form" id="search-form" role="search" method="get" action="">
        <meta itemprop="target" content="https://agroexpert.press/search?q={query}"/>
        <div class="search-form__wrapper">
            <div class="search-form__input-wrapper">
                <input itemprop="query" type="text" class="input search-form__input" placeholder="Введите ваш запрос" value="<?php echo get_search_query() ?>" name="s" id="s" />
                <div class="search-form__clear">
                    <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect x="2.00391" y="15.1746" width="18.6256" height="1.1641" rx="0.582051" transform="rotate(-45 2.00391 15.1746)" fill="#2F2F2F" />
                        <rect x="2.82812" y="2.00339" width="18.6256" height="1.1641" rx="0.582051" transform="rotate(45 2.82812 2.00339)" fill="#2F2F2F" />
                    </svg>
                </div>
            </div>
            <button class="button search-form__button desktop">
                Найти
            </button>
        </div>
        <? if (get_search_query()) : ?>
            <p class="search-form__text">
                <?php
                $resultsForms = array('результат', 'результата', 'результатов');
                $foundForms = array('найден', 'найдено');
                ?>
                По запросу «<?php the_search_query(); ?>» <?= plural_form_extended($wp_query->found_posts, $resultsForms, $foundForms); ?>
            </p>

        <? endif; ?>
        <div class="search-form__selects">
            <select id="selectSort" name="orderby">
                <option value="" <?php echo empty($_GET['orderby']) ? 'selected' : ''; ?>>По релевантности</option>
                <option data-html="По дате <img src='<?= get_asset("/icons/sort_top.svg") ?>' alt />" value="date_asc" <?php echo isset($_GET['order']) && $_GET['order'] == 'asc' ? 'selected' : ''; ?>>По дате &uarr;</option>
                <option data-html="По дате <img src='<?= get_asset("/icons/sort_bottom.svg") ?>' alt />" value="date_desc" <?php echo isset($_GET['order']) && $_GET['order'] == 'desc' ? 'selected' : ''; ?>>По дате &darr;</option>
            </select>

            <select id="selectDate" name="by_date">
                <option value="" <?php echo empty($_GET['by_date']) ? 'selected' : ''; ?>>За всё время</option>
                <option value="1w" <?php echo isset($_GET['by_date']) && $_GET['by_date'] == '1w' ? 'selected' : ''; ?>>За неделю</option>
                <option value="1m" <?php echo isset($_GET['by_date']) && $_GET['by_date'] == '1m' ? 'selected' : ''; ?>>За месяц</option>
                <option value="1y" <?php echo isset($_GET['by_date']) && $_GET['by_date'] == '1y' ? 'selected' : ''; ?>>За год</option>
            </select>

            <select id="selectCategory" name="cat">
                <option value="" <?php echo empty($_GET['cat']) ? 'selected' : ''; ?>>Все категории</option>
                <?php
                $categories = get_categories(array(
                    'orderby' => 'name',
                    'order'   => 'ASC',
                    'hide_empty' => true,
                ));
                foreach ($categories as $category) {
                    $selected = isset($_GET['cat']) && $_GET['cat'] == $category->term_id ? 'selected' : '';
                    printf(
                        '<option value="%s" %s>%s</option>',
                        esc_attr($category->term_id),
                        $selected,
                        esc_html($category->name),
                    );
                }
                ?>
            </select>

        </div>
        <button class="button search-form__button mobile " id="searchsubmit">Найти</button>
    </form>
    <div class="articles-preview search-preview">
        <? if (have_posts()) :
            while (have_posts()) :
                the_post();
        ?>
                <div class="article-item article-item--<?= has_post_thumbnail() ? 'horizontal' : 'inline' ?>">
                    <a href="<? the_permalink(); ?>" class="article-item__image-container">
                        <?php if (has_post_thumbnail()) : ?>
                            <?= show_post_image(); ?>
                        <?php endif; ?>
                        <div class="tag article-item__tag"><?= get_category_name() ?></div>
                    </a>
                    <div class="article-item__text">
                        <div class="article-time">
                            <img src="<?= get_asset('/icons/time.svg'); ?>" alt="" />
                            <time><?= format_event_date(); ?></time>
                        </div>
                        <a href="<? the_permalink() ?>" class="subtitle-16 article-item__link"><?= the_title() ?></a>
                        <p class="article-item__descr text-13"><? the_excerpt() ?></p>
                    </div>
                </div>
            <? endwhile; ?>
        <? endif; ?>
    </div>
    <? custom_pagination(); ?>
    <div class="articles__spacer-container">
        <div class="articles__spacer"></div>
        <div class="articles__spacer"></div>
    </div>
</div>

<script>
    document.getElementById('search-form').addEventListener('submit', function(e) {
        e.preventDefault(); // Предотвращаем стандартное поведение формы

        var searchValue = document.getElementById('s').value; // Получаем значение поля поиска
        var searchQuery = encodeURIComponent(searchValue); // Кодируем значение для URL

        // Получаем значения полей select
        var orderByValue = document.getElementById('selectSort').value;
        var byDateValue = document.getElementById('selectDate').value;
        var catValue = document.getElementById('selectCategory').value;

        // Строим URL с учетом выбранных параметров
        var params = [];

        // Обрабатываем значение orderBy
        if (orderByValue === 'date_asc') {
            params.push('orderby=post_date&order=asc');
        } else if (orderByValue === 'date_desc') {
            params.push('orderby=post_date&order=desc');
        }

        // Добавляем параметры, если они не пусты
        if (byDateValue) {
            params.push('by_date=' + byDateValue);
        }
        if (catValue) {
            params.push('cat=' + catValue);
        }

        // Формируем конечный URL
        var actionUrl = '/search/' + searchQuery + '/?' + params.join('&');

        window.location.href = actionUrl; // Перенаправляем пользователя на новый URL
    });
</script>

<?php get_footer(); ?>