<?php
/**
 * AJAX Handlers
 *
 * @package HomeProz
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Handle AJAX property filter requests
 */
function homeproz_ajax_filter_properties() {
    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'homeproz_filter_nonce')) {
        wp_send_json_error('Invalid nonce');
    }

    // Get filter values
    $property_type = isset($_POST['property_type']) ? sanitize_text_field($_POST['property_type']) : '';
    $property_status = isset($_POST['property_status']) ? sanitize_text_field($_POST['property_status']) : '';
    $property_location = isset($_POST['property_location']) ? sanitize_text_field($_POST['property_location']) : '';
    $min_price = isset($_POST['min_price']) ? intval($_POST['min_price']) : '';
    $max_price = isset($_POST['max_price']) ? intval($_POST['max_price']) : '';
    $beds = isset($_POST['beds']) ? intval($_POST['beds']) : '';
    $sort = isset($_POST['sort']) ? sanitize_text_field($_POST['sort']) : 'newest';
    $paged = isset($_POST['paged']) ? intval($_POST['paged']) : 1;

    // Build query args
    $args = array(
        'post_type' => 'property',
        'posts_per_page' => 12,
        'paged' => $paged,
    );

    // Taxonomy filters
    $tax_query = array();

    if ($property_type) {
        $tax_query[] = array(
            'taxonomy' => 'property_type',
            'field' => 'slug',
            'terms' => $property_type,
        );
    }

    if ($property_status) {
        $tax_query[] = array(
            'taxonomy' => 'property_status',
            'field' => 'slug',
            'terms' => $property_status,
        );
    }

    if ($property_location) {
        $tax_query[] = array(
            'taxonomy' => 'property_location',
            'field' => 'slug',
            'terms' => $property_location,
        );
    }

    if (!empty($tax_query)) {
        $args['tax_query'] = $tax_query;
        if (count($tax_query) > 1) {
            $args['tax_query']['relation'] = 'AND';
        }
    }

    // Meta query for price and bedrooms
    $meta_query = array();

    if ($min_price) {
        $meta_query[] = array(
            'key' => 'property_price',
            'value' => $min_price,
            'type' => 'NUMERIC',
            'compare' => '>=',
        );
    }

    if ($max_price) {
        $meta_query[] = array(
            'key' => 'property_price',
            'value' => $max_price,
            'type' => 'NUMERIC',
            'compare' => '<=',
        );
    }

    if ($beds) {
        $meta_query[] = array(
            'key' => 'bedrooms',
            'value' => $beds,
            'type' => 'NUMERIC',
            'compare' => '>=',
        );
    }

    if (!empty($meta_query)) {
        $args['meta_query'] = $meta_query;
        if (count($meta_query) > 1) {
            $args['meta_query']['relation'] = 'AND';
        }
    }

    // Sorting
    switch ($sort) {
        case 'oldest':
            $args['orderby'] = 'date';
            $args['order'] = 'ASC';
            break;
        case 'price_low':
            $args['meta_key'] = 'property_price';
            $args['orderby'] = 'meta_value_num';
            $args['order'] = 'ASC';
            break;
        case 'price_high':
            $args['meta_key'] = 'property_price';
            $args['orderby'] = 'meta_value_num';
            $args['order'] = 'DESC';
            break;
        case 'newest':
        default:
            $args['orderby'] = 'date';
            $args['order'] = 'DESC';
            break;
    }

    $properties = new WP_Query($args);

    ob_start();

    // Results Meta
    ?>
    <div class="properties-meta">
        <p class="properties-count">
            <?php if ($properties->found_posts > 0) : ?>
                Showing <strong><?php echo esc_html($properties->found_posts); ?></strong>
                <?php echo $properties->found_posts === 1 ? 'property' : 'properties'; ?>
            <?php else : ?>
                No properties found
            <?php endif; ?>
        </p>
    </div>

    <?php if ($properties->have_posts()) : ?>
        <div class="properties-grid">
            <?php
            while ($properties->have_posts()) :
                $properties->the_post();
                get_template_part('template-parts/property/property-card');
            endwhile;
            ?>
        </div>

        <?php
        // Build pagination
        $big = 999999999;
        $base_url = get_post_type_archive_link('property');

        // Build URL with current filters
        $filter_args = array();
        if ($property_type) $filter_args['property_type'] = $property_type;
        if ($property_status) $filter_args['property_status'] = $property_status;
        if ($property_location) $filter_args['property_location'] = $property_location;
        if ($min_price) $filter_args['min_price'] = $min_price;
        if ($max_price) $filter_args['max_price'] = $max_price;
        if ($beds) $filter_args['beds'] = $beds;
        if ($sort && $sort !== 'newest') $filter_args['sort'] = $sort;

        $pagination = paginate_links(array(
            'base' => add_query_arg('paged', '%#%', $base_url),
            'format' => '',
            'current' => max(1, $paged),
            'total' => $properties->max_num_pages,
            'prev_text' => '&larr; Previous',
            'next_text' => 'Next &rarr;',
            'type' => 'array',
            'add_args' => $filter_args,
        ));

        if ($pagination) :
            ?>
            <nav class="pagination" aria-label="Property pagination">
                <div class="nav-links">
                    <?php foreach ($pagination as $link) : ?>
                        <?php echo $link; ?>
                    <?php endforeach; ?>
                </div>
            </nav>
        <?php endif; ?>

    <?php else : ?>
        <div class="no-properties">
            <h3>No Properties Found</h3>
            <p>We couldn't find any properties matching your criteria. Try adjusting your filters or browse all properties.</p>
            <a href="<?php echo esc_url(get_post_type_archive_link('property')); ?>" class="btn btn-primary">View All Properties</a>
        </div>
    <?php endif; ?>

    <?php
    wp_reset_postdata();

    $html = ob_get_clean();

    wp_send_json_success(array(
        'html' => $html,
        'found_posts' => $properties->found_posts,
        'max_pages' => $properties->max_num_pages,
    ));
}
add_action('wp_ajax_homeproz_filter_properties', 'homeproz_ajax_filter_properties');
add_action('wp_ajax_nopriv_homeproz_filter_properties', 'homeproz_ajax_filter_properties');

/**
 * Localize script data for AJAX
 */
function homeproz_localize_ajax_data() {
    if (is_post_type_archive('property') || is_tax('property_type') || is_tax('property_status') || is_tax('property_location')) {
        wp_localize_script('homeproz-main', 'homeprozAjax', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('homeproz_filter_nonce'),
            'archiveUrl' => get_post_type_archive_link('property'),
        ));
    }
}
add_action('wp_enqueue_scripts', 'homeproz_localize_ajax_data', 20);
