<?php
// File: includes/class-tx-ajax-search.php

namespace AvasElements;

use Elementor\Utils;
use AvasElements\TX_Helper;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class TX_Ajax_Search {

    public function __construct() {
        add_action( 'wp_ajax_tx_data_fetch',        [ $this, 'data_fetch' ] );
        add_action( 'wp_ajax_nopriv_tx_data_fetch', [ $this, 'data_fetch' ] );
    }

    public function data_fetch() {
        // Verify nonce (must match wp_create_nonce('tx-search-plus'))
        check_ajax_referer( 'tx-search-plus', 'nonce' );

        // Build list of searchable post types
        $all_post_types = [];
        if ( sanitize_text_field( $_POST['tx_show_attachments'] ?? '' ) === 'yes' ) {
            $all_post_types[] = 'attachment';
        }
        foreach ( TX_Helper::get_custom_types_of( 'post', false ) as $slug => $label ) {
            $all_post_types[] = $slug;
        }

        // Taxonomy filter, if any
        $tax_query = [];
        $cat = sanitize_text_field( $_POST['tx_category'] ?? '' );
        if ( $cat !== '' && $cat !== '0' ) {
            $tax_query[] = [
                'taxonomy' => sanitize_text_field( $_POST['tx_option_post_type'] ?? $_POST['tx_query_type'] . '_cat' ),
                'field'    => 'term_id',
                'terms'    => $cat,
            ];
        }

        // collect exclude IDs
        $exclude_ids = [];
        if ( ! empty( $_POST['tx_exclude_ids'] ) && is_array( $_POST['tx_exclude_ids'] ) ) {
            $exclude_ids = array_map( 'absint', $_POST['tx_exclude_ids'] );
        }

        // Main query arguments
        $args = [
            's'              => sanitize_text_field( $_POST['tx_keyword'] ?? '' ),
            'post_type'      => ( $_POST['tx_query_type'] ?? 'all' ) === 'all'
                ? $all_post_types
                : [ sanitize_text_field( $_POST['tx_query_type'] ) ],
            'posts_per_page' => intval( $_POST['tx_number_of_results'] ?? 5 ),
            'offset'         => intval( $_POST['tx_search_results_offset'] ?? 0 ),
            'post_status'    => in_array( 'attachment', $all_post_types, true )
                ? [ 'publish', 'inherit' ]
                : 'publish',
        ];

        if ( $exclude_ids ) {
            $args['post__not_in'] = $exclude_ids;
        }

        if ( ! empty( $tax_query ) ) {
            $args['tax_query'] = $tax_query;
        }
        if ( sanitize_text_field( $_POST['tx_exclude_without_thumb'] ?? '' ) === 'yes' ) {
            $args['meta_query'] = [
                [ 'key' => '_thumbnail_id' ],
            ];
        }

        $q = new \WP_Query( $args );

        // Output
        if ( $q->have_posts() ) {
            while ( $q->have_posts() ) {
                $q->the_post();

                // Determine thumbnail URL
                $thumb_url = '';
                if ( sanitize_text_field( $_POST['tx_show_ajax_thumbnail'] ?? '' ) === 'yes' ) {
                    $thumb_url = has_post_thumbnail()
                        ? get_the_post_thumbnail_url( get_the_ID(), 'medium' )
                        : Utils::get_placeholder_image_src();
                }
                ?>
                <li data-number-of-results="<?php echo esc_attr( $q->found_posts ); ?>">
                    <?php if ( $thumb_url ) : ?>
                        <a class="tx-ajax-img-wrap"
                           href="<?php echo esc_url( get_the_permalink() ); ?>"
                           target="<?php echo esc_attr( $_POST['tx_ajax_search_link_target'] ?? '_self' ); ?>">
                            <img src="<?php echo esc_url( $thumb_url ); ?>"
                                 alt="<?php echo esc_attr( get_the_title() ); ?>">
                        </a>
                    <?php endif; ?>

                    <div class="tx-ajax-search-content">
                        <a class="tx-ajax-title"
                           href="<?php echo esc_url( get_the_permalink() ); ?>"
                           target="<?php echo esc_attr( $_POST['tx_ajax_search_link_target'] ?? '_self' ); ?>">
                            <?php the_title(); ?>
                        </a>

                        <?php if ( sanitize_text_field( $_POST['tx_show_description'] ?? '' ) === 'yes' ) : ?>
                            <p class="tx-ajax-desc">
                                <a href="<?php echo esc_url( get_the_permalink() ); ?>"
                                   target="<?php echo esc_attr( $_POST['tx_ajax_search_link_target'] ?? '_self' ); ?>">
                                    <?php echo wp_trim_words(
                                        get_the_content(),
                                        intval( $_POST['tx_number_of_words'] ?? 30 )
                                    ); ?>
                                </a>
                            </p>
                        <?php endif; ?>

                        <?php if ( sanitize_text_field( $_POST['tx_show_view_result_btn'] ?? '' ) === 'yes' ) : ?>
                            <a class="tx-view-result"
                               href="<?php echo esc_url( get_the_permalink() ); ?>"
                               target="<?php echo esc_attr( $_POST['tx_ajax_search_link_target'] ?? '_self' ); ?>">
                                <?php echo esc_html( $_POST['tx_view_result_text'] ?? 'View Results' ); ?>
                            </a>
                        <?php endif; ?>
                    </div>
                </li>
                <?php
            }
            wp_reset_postdata();
        } else {
            echo '<p class="tx-no-results">'
                 . esc_html( sanitize_text_field( $_POST['tx_no_results'] ?? 'No results found.' ) )
                 . '</p>';
        }

        wp_die();
    }
}

new TX_Ajax_Search();