<?php

/* Panel Ajax */
function at_search_term()
{
    $nonce = sanitize_text_field($_POST['nonce']);

    if (!wp_verify_nonce($nonce, 'panel_nonce')) {
        return json_encode([
            'status' => 'error',
            'data' => [
                'message' => 'Khatam! Tata! Good Bye!',
            ],
        ]);
    }

    $query = $_POST['query'];

    $query_term = new WP_Term_Query(
        array(
            'taxonomy' => array('category', 'post_tag'),
            'hide_empty' => false,
            'name__like' => $query,
            'posts_per_page' => 50,
        )
    );

    if ($query_term->terms) {
        echo '<ul>';
        foreach ($query_term->terms as $term) {
            echo '<li data-term-id="' . $term->term_id . '">' . $term->name . '</li>';
        }
        echo '</ul>';
    } else {
        echo '<div class="no-result">No terms found...</div>';
    }

    wp_die();
}
add_action('wp_ajax_at_search_term', 'at_search_term');

function at_search_post()
{
    $nonce = sanitize_text_field($_POST['nonce']);

    if (!wp_verify_nonce($nonce, 'panel_nonce')) {
        return json_encode([
            'status' => 'error',
            'data' => [
                'message' => 'Khatam! Tata! Good Bye!',
            ],
        ]);
    }

    $query = $_POST['query'];

    $query_posts = new WP_Query(
        array(
            'post_status' => 'publish',
            'post_type' => 'post',
            's' => $query,
            'post_parent' => 0,
            'posts_per_page' => 50,
        )
    );
    if ($query_posts->have_posts()):
        echo '<ul>';
        while ($query_posts->have_posts()):
            $query_posts->the_post();
            echo '<li data-post-id="' . get_the_ID() . '">' . get_the_title() . '</li>';
        endwhile;
        echo '</ul>';
    else:
        echo '<div class="no-result">No posts found...</div>';
    endif;

    wp_die();
}
add_action('wp_ajax_at_search_post', 'at_search_post');
