<?php
// AJAX handler
function rswpthemes_awt_filerable_posts_ajax_handler() {
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
    $posts_per_page = isset($_POST['posts_per_page']) ? intval($_POST['posts_per_page']) : 5;
    $categories = isset($_POST['categories']) ? sanitize_text_field($_POST['categories']) : '';
    $posts_per_row = isset($_POST['posts_per_row']) ? intval($_POST['posts_per_row']) : 2;
    $selected_category = isset($_POST['category']) ? intval($_POST['category']) : '';
    $selected_author = isset($_POST['author']) ? intval($_POST['author']) : '';
    $sort_order = isset($_POST['sort_order']) ? sanitize_text_field($_POST['sort_order']) : ''; // Get the sort order
    $layout = isset($_POST['layout']) ? sanitize_text_field($_POST['layout']) : '1';

    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $posts_per_page,
        'paged' => $page,
        'post_status' => 'publish',
    );

    // Add category filter
    if (!empty($categories)) {
        $args['cat'] = $categories;
    } elseif (!empty($selected_category)) {
        $args['cat'] = $selected_category;
    }

    // Add author filter
    if (!empty($selected_author)) {
        $args['author'] = $selected_author;
    }

    // Add search filter
    if (!empty($search)) {
        $args['s'] = '';
        add_filter('posts_where', function ($where) use ($search) {
            global $wpdb;
            $search_term = $wpdb->esc_like($search);
            $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_title LIKE %s", "%{$search_term}%");
            return $where;
        });
    }

    // Add sorting
    if (!empty($sort_order)) {
        if ($sort_order === 'title_asc') {
            $args['orderby'] = 'title';
            $args['order'] = 'ASC';
        } elseif ($sort_order === 'title_desc') {
            $args['orderby'] = 'title';
            $args['order'] = 'DESC';
        } elseif ($sort_order === 'date_asc') {
            $args['orderby'] = 'date';
            $args['order'] = 'ASC';
        } elseif ($sort_order === 'date_desc') {
            $args['orderby'] = 'date';
            $args['order'] = 'DESC';
        }
    }

    $result = get_rswpthemes_awt_filerable_posts_markup($args, $posts_per_row, $layout);
    wp_send_json_success($result);

    if (!empty($search)) {
        remove_filter('posts_where', function () {}, 10);
    }

    wp_die();
}
add_action('wp_ajax_rswpthemes_awt_filerable_posts_load', 'rswpthemes_awt_filerable_posts_ajax_handler');
add_action('wp_ajax_nopriv_rswpthemes_awt_filerable_posts_load', 'rswpthemes_awt_filerable_posts_ajax_handler');