<?php

namespace wpbel\classes\controllers;

defined('ABSPATH') || exit(); // Exit if accessed directly
use wpbel\classes\helpers\Render;
use wpbel\classes\helpers\Sanitizer;
use wpbel\classes\helpers\Filter_Helper;
use wpbel\classes\helpers\Meta_Fields;
use wpbel\classes\helpers\Taxonomy_Helper;
use wpbel\classes\repositories\Column;
use wpbel\classes\repositories\History;
use wpbel\classes\services\history\HistoryRedoService;
use wpbel\classes\services\history\HistoryUndoService;
use wpbel\classes\repositories\Meta_Field;
use wpbel\classes\repositories\Post;
use wpbel\classes\repositories\Search;
use wpbel\classes\repositories\Setting;
use WP_Post;
use wpbel\classes\helpers\Post_Helper;
use wpbel\classes\services\background_process\PostBackgroundProcess;
use wpbel\classes\services\filter\Post_Filter_Service;
use wpbel\classes\services\post_delete\PostDeleteService;
use wpbel\classes\services\post_duplicate\PostDuplicateService;
use wpbel\classes\services\update\WPBEL_Post_Update;
use wpbel\classes\repositories\meta_field\Meta_Field_Main;

class WPBEL_Ajax
{
    private static $instance;
    private $post_repository;
    private $history_repository;

    public static function register_callback()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    private function __construct()
    {
        $this->post_repository = new Post();
        $this->history_repository = new History();
        add_action('wp_ajax_wpbe_get_default_filter_profile_posts', [$this, 'get_default_filter_profile_posts']);
        add_action('wp_ajax_wpbe_get_post_tags', [$this, 'get_post_tags']);
        add_action('wp_ajax_wpbe_create_new_post', [$this, 'create_new_post']);
        add_action('wp_ajax_wpbe_posts_filter', [$this, 'posts_filter']);
        add_action('wp_ajax_wpbe_duplicate_post', [$this, 'duplicate_post']);
        add_action('wp_ajax_wpbe_delete_posts', [$this, 'delete_post']);
        add_action('wp_ajax_wpbe_untrash_posts', [$this, 'untrash_posts']);
        add_action('wp_ajax_wpbe_empty_trash', [$this, 'empty_trash']);
        add_action('wp_ajax_wpbe_filter_profile_change_use_always', [$this, 'filter_profile_change_use_always']);
        add_action('wp_ajax_wpbe_change_count_per_page', [$this, 'change_count_per_page']);
        add_action('wp_ajax_wpbe_column_manager_get_fields_for_edit', [$this, 'column_manager_get_fields_for_edit']);
        add_action('wp_ajax_wpbe_get_text_editor_content', [$this, 'get_text_editor_content']);
        add_action('wp_ajax_wpbe_history_filter', [$this, 'history_filter']);
        add_action('wp_ajax_wpbe_history_undo', [$this, 'history_undo']);
        add_action('wp_ajax_wpbe_history_redo', [$this, 'history_redo']);
        add_action('wp_ajax_wpbe_add_meta_keys_by_post_id', [$this, 'add_meta_keys_by_post_id']);
        add_action('wp_ajax_wpbe_update_post_taxonomy', [$this, 'update_post_taxonomy']);
        add_action('wp_ajax_wpbe_add_post_taxonomy', [$this, 'add_post_taxonomy']);
        add_action('wp_ajax_wpbe_post_edit', [$this, 'post_edit']);
        add_action('wp_ajax_wpbe_load_filter_profile', [$this, 'load_filter_profile']);
        add_action('wp_ajax_wpbe_save_filter_preset', [$this, 'save_filter_preset']);
        add_action('wp_ajax_wpbe_save_column_profile', [$this, 'save_column_profile']);
        add_action('wp_ajax_wpbe_sort_by_column', [$this, 'sort_by_column']);
        add_action('wp_ajax_wpbe_delete_filter_profile', [$this, 'delete_filter_profile']);
        add_action('wp_ajax_wpbe_get_taxonomy_parent_select_box', [$this, 'get_taxonomy_parent_select_box']);
        add_action('wp_ajax_wpbe_clear_filter_data', [$this, 'clear_filter_data']);
        add_action('wp_ajax_wpbe_get_post_by_id', [$this, 'get_post_by_id']);
        add_action('wp_ajax_wpbe_get_posts_by_name', [$this, 'get_posts_by_name']);
        add_action('wp_ajax_wpbe_history_change_page', [$this, 'history_change_page']);
        add_action('wp_ajax_wpbe_get_post_custom_field_files', [$this, 'get_post_custom_field_files']);
        add_action('wp_ajax_wpbe_add_custom_field_file_item', [$this, 'add_custom_field_file_item']);
        add_action('wp_ajax_wpbe_bulk_edit_add_custom_field_file_item', [$this, 'bulk_edit_add_custom_field_file_item']);
        add_action('wp_ajax_wpbe_get_users', [$this, 'get_users']);
        add_action('wp_ajax_wpbe_get_post_taxonomy_terms', [$this, 'get_post_taxonomy_terms']);
        add_action('wp_ajax_wpbe_is_processing', [$this, 'is_processing']);
        add_action('wp_ajax_wpbe_background_process_force_stop', [$this, 'background_process_force_stop']);
        add_action('wp_ajax_wpbe_background_process_clear_complete_message', [$this, 'background_process_clear_complete_message']);
        add_action('wp_ajax_wpbe_background_process_clear_tasks_count', [$this, 'background_process_clear_tasks_count']);
        add_action('wp_ajax_wpbe_column_manager_add_field', [$this, 'column_manager_add_field']);
        add_action('wp_ajax_wpbe_add_meta_keys_manual', [$this, 'add_meta_keys_manual']);
    }

    public function column_manager_add_field()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['field_name']) && is_array($_POST['field_name']) && !empty($_POST['field_name']) && !empty($_POST['field_action'])) {
            $output = '';
            $field_action = sanitize_text_field(wp_unslash($_POST['field_action']));
            for ($i = 0; $i < count($_POST['field_name']); $i++) {
                if (!empty($_POST['field_name'][$i])) {
                    $field_name = sanitize_text_field(wp_unslash($_POST['field_name'][$i]));
                    $field_label = (!empty($_POST['field_label'][$i])) ? sanitize_text_field(wp_unslash($_POST['field_label'][$i])) : $field_name;
                    $field_title = (!empty($_POST['field_label'][$i])) ? sanitize_text_field(wp_unslash($_POST['field_label'][$i])) : $field_name;
                    $output .= Render::html(WPBEL_VIEWS_DIR . "column_manager/field_item.php", compact('field_name', 'field_label', 'field_action', 'field_title'));
                }
            }
            $this->make_response($output);
        }

        return false;
    }

    public function add_meta_keys_manual()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['meta_key_name'])) {
            $meta_field['key'] = strtolower(str_replace(' ', '_', sanitize_text_field(wp_unslash($_POST['meta_key_name']))));
            $meta_fields_main_types = Meta_Field_Main::get_main_types();
            $meta_fields_sub_types = Meta_Field_Main::get_sub_types();
            $output = Render::html(WPBEL_VIEWS_DIR . "meta_field/meta_field_item.php", compact('meta_field', 'meta_fields_main_types', 'meta_fields_sub_types'));
            $this->make_response($output);
        }
        return false;
    }

    public function is_processing()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $background_process = PostBackgroundProcess::get_instance();
        $crashed = $background_process->crash_handler();

        $this->make_response([
            'is_processing' => $background_process->is_not_queue_empty(),
            'is_force_stopped' => $background_process->is_force_stopped(),
            'complete_message' => $background_process->get_complete_message(),
            'total_tasks' => $background_process->get_total_tasks(),
            'completed_tasks' => $background_process->get_completed_tasks_count(),
            'remaining_time' => $background_process->get_remaining_time(),
            'crashed' => $crashed
        ]);
    }

    public function background_process_clear_tasks_count()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $background_process = PostBackgroundProcess::get_instance();
        $background_process->clear_tasks_count();
        $this->make_response([
            'success' => true,
        ]);
    }

    public function background_process_clear_complete_message()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $background_process = PostBackgroundProcess::get_instance();
        $background_process->clear_complete_message();
        $this->make_response([
            'success' => true,
        ]);
    }

    public function background_process_force_stop()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $background_process = PostBackgroundProcess::get_instance();
        $background_process->stop_process();

        $this->make_response([
            'success' => true,
        ]);
    }

    public function get_post_tags()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $list = [];

        if (!empty($_POST['search'])) {
            $tags = get_terms([
                'taxonomy' => 'post_tag',
                'hide_empty' => false,
                'name__like' => sanitize_text_field(wp_unslash($_POST['search'])),
            ]);

            if (!empty($tags)) {
                foreach ($tags as $tag) {
                    $list['results'][] = [
                        'id' => $tag->term_id,
                        'text' => $tag->name,
                    ];
                }
            }
        }

        $this->make_response($list);
    }

    public function get_users()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $list['results'] = [];
        if (!empty($_POST['search'])) {
            $query = new \WP_User_Query([
                'search' => '*' . sanitize_text_field(wp_unslash($_POST['search'])) . '*',
                'search_columns' => [
                    'user_login',
                    'user_email',
                    'display_name',
                ],
            ]);

            $users = $query->get_results();
            if (!empty($users)) {
                foreach ($users as $user) {
                    if ($user instanceof \WP_User) {
                        $list['results'][] = [
                            'id' => $user->ID,
                            'text' => $user->user_login
                        ];
                    }
                }
            }
        }

        $this->make_response($list);
    }

    public function get_post_taxonomy_terms()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (empty($_POST['post_id']) || empty($_POST['taxonomy'])) {
            $this->make_response([
                'success' => true,
                'terms' => 'Empty !',
            ]);
        }

        $terms = get_terms([
            'taxonomy' => sanitize_text_field(wp_unslash($_POST['taxonomy'])),
            'hide_empty' => false,
        ]);

        $return_field = (in_array($_POST['taxonomy'], ['post_tag'])) ? 'slugs' : 'ids';
        $value_field = (in_array($_POST['taxonomy'], ['post_tag'])) ? 'slug' : 'term_id';

        $post_terms = wp_get_post_terms(intval($_POST['post_id']), sanitize_text_field(wp_unslash($_POST['taxonomy'])), [
            'fields' => $return_field
        ]);
        if (empty($post_terms)) {
            $post_terms = [];
        }

        $items = '';
        if (!empty($terms)) {
            foreach ($terms as $term) {
                if (!($term instanceof \WP_Term)) {
                    continue;
                }
                $items .= '<label><input type="checkbox" value="' . $term->{$value_field} . '" ' . ((in_array($term->{$value_field}, $post_terms)) ? 'checked="checked"' : '') . '> ' . $term->name . '</label>';
            }
        }

        $this->make_response([
            'success' => true,
            'terms' => $items,
        ]);
    }

    public function post_edit()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (empty($_POST['post_data']) || !is_array($_POST['post_data'])) {
            return false;
        }

        if (empty($_POST['post_ids'])) {
            return false;
        }

        if (is_array($_POST['post_ids'])) {
            $post_ids = array_map('intval', $_POST['post_ids']);
        } elseif ($_POST['post_ids'] == 'all_filtered' && !empty($_POST['filter_data'])) {
            $filter_service = Post_Filter_Service::get_instance();
            $posts = $filter_service->get_filtered_posts(Sanitizer::array($_POST['filter_data']), [ //phpcs:ignore
                'posts_per_page' => -1,
                'fields' => 'ids',
                'post_type' => [Post_Helper::get_active_post_type()],
            ]);
            $post_ids = $posts['post_ids'];
        }

        if (empty($post_ids)) {
            return false;
        }

        $update_service = WPBEL_Post_Update::get_instance();
        $update_service->set_update_data([
            'post_ids' => $post_ids,
            'post_data' => Sanitizer::array($_POST['post_data']), //phpcs:ignore
            'save_history' => true,
        ]);
        $update_result = $update_service->perform();

        if ($update_service->is_processing()) {
            $this->make_response([
                'success' => $update_result,
                'post_ids' => $post_ids,
                'is_processing' => $update_service->is_processing(),
                'total_tasks' => count($post_ids),
                'completed_tasks' => 0,
            ]);
        } else {
            $result = $this->post_repository->get_posts_rows($post_ids);
            $histories = $this->history_repository->get_histories();
            $history_count = $this->history_repository->get_history_count();
            $reverted = $this->history_repository->get_latest_reverted();
            $histories_rendered = Render::html(WPBEL_VIEWS_DIR . 'history/history_items.php', compact('histories'));
            $history_pagination = Render::html(WPBEL_VIEWS_DIR . 'history/history_pagination.php', compact('history_count'));

            $this->make_response([
                'success' => $update_result,
                'posts' => $result->post_rows,
                'post_statuses' => $result->post_statuses,
                'status_filters' => $result->status_filters,
                'history_items' => $histories_rendered,
                'history_pagination' => $history_pagination,
                'reverted' => !empty($reverted),
            ]);
        }

        return false;
    }

    private function save_history($post_ids, $fields, $new_value, $operation_type)
    {
        $create_history = $this->history_repository->create_history([
            'user_id' => intval(get_current_user_id()),
            'fields' => serialize($fields),
            'operation_type' => sanitize_text_field($operation_type),
            'operation_date' => gmdate('Y-m-d H:i:s'),
        ]);

        if (!$create_history) {
            return false;
        }

        foreach ($post_ids as $post_id) {
            $post_object = $this->post_repository->get_post(intval($post_id));
            if (!($post_object instanceof \WP_Post)) {
                return false;
            }
            $post_item = $this->post_repository->get_post_fields($post_object);
            if (!empty($fields)) {
                foreach ($fields as $field_type => $field) {
                    if (is_array($field)) {
                        $new_val = [];
                        $prev_val = [];
                        foreach ($field as $filed_name) {
                            $encoded_field = strtolower(urlencode($filed_name));
                            switch ($field_type) {
                                case 'custom_field':
                                    $new_val['custom_field'][$encoded_field] = $new_value[$encoded_field];
                                    $prev_val['custom_field'][$encoded_field] = (isset($post_item[$field_type][$encoded_field][0])) ? $post_item[$field_type][$encoded_field][0] : '';
                                    break;
                                case 'taxonomy':
                                    $new_val['taxonomy'][$encoded_field] = $new_value[$encoded_field];
                                    $prev_val['taxonomy'][$encoded_field] = ($encoded_field == 'post_tag') ? wp_get_post_terms($post_item['id'], $encoded_field, ['fields' => 'names']) : wp_get_post_terms($post_item['id'], $encoded_field, ['fields' => 'ids']);
                                    break;
                                default:
                                    break;
                            }
                        }
                        $new_val = serialize($new_val);
                        $prev_val = serialize($prev_val);
                    } else {
                        $prev_val = (isset($post_item[$field])) ? serialize($post_item[$field]) : '';
                        if ($field == '_thumbnail_id') {
                            $new_val = serialize([
                                'id' => intval($new_value),
                                'small' => wp_get_attachment_image_src(intval($new_value), [40, 40]),
                                'big' => wp_get_attachment_image_src(intval($new_value), [600, 600]),
                            ]);
                        } else {
                            $new_val = (!empty($new_value[$field])) ? serialize($new_value[$field]) : serialize($new_value);
                        }
                    }

                    $this->history_repository->create_history_item([
                        'history_id' => intval($create_history),
                        'historiable_id' => intval($post_id),
                        'field' => serialize([$field_type => $field]),
                        'prev_value' => $prev_val,
                        'new_value' => $new_val,
                    ]);
                }
            }
        }
        return true;
    }

    public function history_filter()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['filters'])) {
            $where = [];
            if (isset($_POST['filters']['operation']) && !empty($_POST['filters']['operation'])) {
                $where['operation_type'] = sanitize_text_field(wp_unslash($_POST['filters']['operation']));
            }
            if (isset($_POST['filters']['author']) && !empty($_POST['filters']['author'])) {
                $where['user_id'] = sanitize_text_field(wp_unslash($_POST['filters']['author']));
            }
            if (isset($_POST['filters']['fields']) && !empty($_POST['filters']['fields'])) {
                $where['fields'] = (is_array($_POST['filters']['fields'])) ? Sanitizer::array($_POST['filters']['fields']) : sanitize_text_field(wp_unslash($_POST['filters']['fields'])); //phpcs:ignore
            }
            if (isset($_POST['filters']['date'])) {
                $where['operation_date'] = sanitize_text_field(wp_unslash($_POST['filters']['date']));
            }

            $histories = $this->history_repository->get_histories($where);
            $history_count = $this->history_repository->get_history_count($where);
            $histories_rendered = Render::html(WPBEL_VIEWS_DIR . 'history/history_items.php', compact('histories'));
            $history_pagination = Render::html(WPBEL_VIEWS_DIR . 'history/history_pagination.php', compact('history_count'));
            $reverted = $this->history_repository->get_latest_reverted();

            $this->make_response([
                'success' => true,
                'history_items' => $histories_rendered,
                'history_pagination' => $history_pagination,
                'reverted' => !empty($reverted),
            ]);
        }
        return false;
    }

    public function history_undo()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $latest_history = $this->history_repository->get_latest_history();
        if (!empty($latest_history[0]) && !empty($latest_history[0]->id)) {
            $history_undo_service = new HistoryUndoService();
            $history_undo_service->set_data(['history_id' => intval($latest_history[0]->id)]);
            $history_undo_service->perform();

            $histories = $this->history_repository->get_histories();
            $history_count = $this->history_repository->get_history_count();
            $reverted = $this->history_repository->get_latest_reverted();
            $histories_rendered = Render::html(WPBEL_VIEWS_DIR . 'history/history_items.php', compact('histories'));
            $history_pagination = Render::html(WPBEL_VIEWS_DIR . 'history/history_pagination.php', compact('history_count'));

            $this->make_response([
                'success' => true,
                'is_processing' => $history_undo_service->is_processing(),
                'total_tasks' => $history_undo_service->get_total_tasks(),
                'completed_tasks' => 0,
                'post_ids' => $history_undo_service->get_post_ids(),
                'history_items' => $histories_rendered,
                'history_pagination' => $history_pagination,
                'reverted' => !empty($reverted),
            ]);
        }

        return false;
    }

    public function history_redo()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $latest_reverted = $this->history_repository->get_latest_reverted();
        if (!empty($latest_reverted[0]) && !empty($latest_reverted[0]->id)) {
            $history_redo_service = new HistoryRedoService();
            $history_redo_service->set_data(['history_id' => intval($latest_reverted[0]->id)]);
            $history_redo_service->perform();

            $histories = $this->history_repository->get_histories();
            $history_count = $this->history_repository->get_history_count();
            $reverted = $this->history_repository->get_latest_reverted();
            $histories_rendered = Render::html(WPBEL_VIEWS_DIR . 'history/history_items.php', compact('histories'));
            $history_pagination = Render::html(WPBEL_VIEWS_DIR . 'history/history_pagination.php', compact('history_count'));

            $this->make_response([
                'success' => true,
                'is_processing' => $history_redo_service->is_processing(),
                'total_tasks' => $history_redo_service->get_total_tasks(),
                'completed_tasks' => 0,
                'post_ids' => $history_redo_service->get_post_ids(),
                'history_items' => $histories_rendered,
                'history_pagination' => $history_pagination,
                'reverted' => !empty($reverted),
            ]);
        }

        return false;
    }

    public function get_text_editor_content()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['post_id']) && isset($_POST['field']) && !empty($_POST['field_type'])) {
            $field = sanitize_text_field(wp_unslash($_POST['field']));
            $field_type = sanitize_text_field(wp_unslash($_POST['field_type']));
            $post_object = $this->post_repository->get_post(intval($_POST['post_id']));
            if (!($post_object instanceof \WP_Post)) {
                return false;
            }
            $post = $this->post_repository->get_post_fields($post_object);
            if ($field_type == 'custom_field') {
                $value = (isset($post['custom_field'][$field])) ? $post['custom_field'][$field][0] : '';
            } else {
                $value = $post[$field];
            }
            $this->make_response([
                'success' => true,
                'content' => nl2br($value),
            ]);
        }
        return false;
    }

    public function get_default_filter_profile_posts()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $filter_data = Filter_Helper::get_active_filter_data();
        $search_repository = new Search();
        $use_always = $search_repository->get_use_always();
        if ($use_always != 'default') {
            $preset = $search_repository->get_preset($use_always);
            if (!empty($preset['filter_data'])) {
                $filter_data = $preset['filter_data'];
            }
        }
        $histories = $this->history_repository->get_histories([], 1, 0);
        $reverted = $this->history_repository->get_latest_reverted();
        $result = $this->post_repository->get_posts_list([Post_Helper::get_active_post_type()], $filter_data, 1);
        $this->make_response([
            'success' => true,
            'filter_data' => $filter_data,
            'posts_list' => $result->posts_list,
            'status_filters' => $result->status_filters,
            'pagination' => $result->pagination,
            'posts_count' => $result->count,
            'history' => !empty($histories),
            'reverted' => !empty($reverted),
        ]);
    }

    public function create_new_post()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (!empty($_POST['count'])) {
            if (Post_Helper::get_active_post_type() == 'custom_post' && empty($_POST['post_type'])) {
                return false;
            }

            $post_data = (!empty($_POST['postData'])) ? Sanitizer::array($_POST['postData']) : ''; //phpcs:ignore
            if (empty($post_data['post_type'])) {
                $post_data['post_type'] = Post_Helper::get_active_post_type();
            }
            if ($_POST['count'] > 100 && PostBackgroundProcess::is_enable()) {
                $max = 50;
                $background_process = PostBackgroundProcess::get_instance();
                if ($background_process->is_not_queue_empty()) {
                    $this->make_response([
                        'success' => false,
                        'message' => esc_html__('Another operation is running. It is not possible to edit the information at this moment. Please wait until it finishes or set a scheduled task.', 'ithemeland-bulk-posts-editing-lite'),
                    ]);
                }
                $round = ceil(intval($_POST['count']) / $max);
                for ($i = 1; $i <= intval($round); $i++) {
                    if ($i == $round) {
                        $count = intval($_POST['count']) - (($round - 1) * $max);
                    } else {
                        $count = $max;
                    }

                    $background_process->push_to_queue([
                        'handler' => 'post_create',
                        'count' => $count,
                        'post_data' => $post_data,
                    ]);
                    $background_process->save();
                }

                $background_process->set_total_tasks(intval($_POST['count']));
                $background_process->start();

                $this->make_response([
                    'success' => true,
                    'is_processing' => true,
                    'total_tasks' => intval($_POST['count']),
                    'completed_tasks' => 0,
                ]);
            } else {
                $posts = [];
                for ($i = 1; $i <= intval($_POST['count']); $i++) {
                    $posts[] = $this->post_repository->create($post_data);
                }
                $this->make_response([
                    'success' => true,
                    'post_ids' => $posts,
                ]);
            }
        }
    }

    public function posts_filter()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['filter_data'])) {
            $data = Sanitizer::array($_POST['filter_data']); //phpcs:ignore
            $current_page = !empty($_POST['current_page']) ? intval($_POST['current_page']) : 1;
            $filter_result = $this->post_repository->get_posts_list([Post_Helper::get_active_post_type()], $data, $current_page);
            if (!empty($_POST['option_values'])) {
                $search_repository = new Search();
                $search_repository->update_option_values(Sanitizer::array($_POST['option_values'])); //phpcs:ignore
            }
            $this->make_response([
                'success' => true,
                'posts_list' => $filter_result->posts_list,
                'status_filters' => $filter_result->status_filters,
                'pagination' => $filter_result->pagination,
                'posts_count' => $filter_result->count,
            ]);
        }

        return false;
    }

    public function load_filter_profile()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['preset_key'])) {
            $search_repository = new Search();
            $preset = $search_repository->get_preset(sanitize_text_field(wp_unslash($_POST['preset_key'])));
            if (!isset($preset['filter_data'])) {
                return false;
            }
            $search_repository->update_current_data([
                'last_filter_data' => $preset['filter_data'],
            ]);
            $result = $this->post_repository->get_posts_list([Post_Helper::get_active_post_type()], $preset['filter_data'], 1);
            $this->make_response([
                'success' => true,
                'filter_data' => $preset['filter_data'],
                'option_values' => $search_repository->get_option_values(),
                'posts_list' => $result->posts_list,
                'status_filters' => $result->status_filters,
                'pagination' => $result->pagination,
                'posts_count' => $result->count,
            ]);
        }
        return false;
    }

    public function save_filter_preset()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }
        $search_repository = new Search();

        if (!empty($_POST['option_values'])) {
            $search_repository->update_option_values(Sanitizer::array($_POST['option_values'])); //phpcs:ignore
        }

        if (!empty($_POST['preset_name'])) {
            $filter_item['name'] = sanitize_text_field(wp_unslash($_POST['preset_name']));
            $filter_item['date_modified'] = gmdate('Y-m-d H:i:s');
            $filter_item['key'] = 'preset-' . wp_rand(1000000, 9999999);
            $filter_item['filter_data'] = Sanitizer::array($_POST['filter_data']); //phpcs:ignore
            $save_result = $search_repository->update($filter_item);
            if (!$save_result) {
                return false;
            }
            $new_item = Render::html(WPBEL_VIEWS_DIR . 'modals/filter_profile_item.php', compact('filter_item'));
            $this->make_response([
                'success' => $save_result,
                'new_item' => $new_item,
            ]);
        }
        return false;
    }

    public function delete_filter_profile()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['preset_key'])) {
            $search_repository = new Search();
            $use_always = $search_repository->get_use_always();
            if ($use_always == $_POST['preset_key']) {
                $search_repository->update_use_always('default');
            }
            $delete_result = $search_repository->delete(sanitize_text_field(wp_unslash($_POST['preset_key'])));
            if (!$delete_result) {
                return false;
            }

            $this->make_response([
                'success' => true,
            ]);
        }
        return false;
    }

    public function get_taxonomy_parent_select_box()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['taxonomy'])) {
            $taxonomies = get_terms(['taxonomy' => sanitize_text_field(wp_unslash($_POST['taxonomy'])), 'hide_empty' => false]);
            $options = '<option value="-1">None</option>';
            if (!empty($taxonomies)) {
                foreach ($taxonomies as $taxonomy) {
                    $term_id = intval($taxonomy->term_id);
                    $taxonomy_name = sanitize_text_field(wp_unslash($taxonomy->name));
                    $options .= "<option value='{$term_id}'>{$taxonomy_name}</option>";
                }
            }
            $this->make_response([
                'success' => true,
                'options' => $options,
            ]);
        }
        return false;
    }

    public function duplicate_post()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (empty($_POST['post_ids']) || !is_array($_POST['post_ids']) || empty($_POST['duplicate_number'])) {
            $this->make_response([
                'success' => false,
            ]);
        }

        $post_duplicate_service = new PostDuplicateService();
        $post_duplicate_service->perform([
            'post_ids' => array_map('intval', $_POST['post_ids']),
            'count' => intval($_POST['duplicate_number']),
        ]);

        $this->make_response([
            'success' => esc_html__('Success !', 'ithemeland-bulk-posts-editing-lite'),
            'is_processing' => $post_duplicate_service->is_processing(),
            'total_tasks' => count($_POST['post_ids']) * intval($_POST['duplicate_number']),
            'completed_tasks' => 0,
        ]);
    }

    public function get_post_by_id()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (empty($_POST['post_id'])) {
            return false;
        }

        $post = get_post(intval($_POST['post_id']));
        if (!($post instanceof WP_Post)) {
            return false;
        }

        $this->make_response([
            'success' => true,
            'post_title' => $post->post_title,
        ]);
    }

    public function get_posts_by_name()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (empty($_POST['post_title'])) {
            return false;
        }

        $args['post_status'] = 'any';
        $args['wpbe_general_column_filter'] = [
            [
                'field' => 'post_title',
                'value' => sanitize_text_field(wp_unslash($_POST['post_title'])),
                'parent_only' => true,
                'operator' => 'like',
            ],
        ];

        $list = [];
        $query_result = $this->post_repository->get_posts($args);

        if (!empty($query_result->posts)) {
            foreach ($query_result->posts as $post) {
                if ($post instanceof \WP_Post) {
                    $list['results'][] = [
                        'id' => $post->ID,
                        'text' => $post->post_title,
                    ];
                }
            }
        }

        $this->make_response($list);
    }

    public function delete_post()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (empty($_POST['delete_type'])) {
            $this->make_response([
                'success' => false,
                'message' => esc_html__('Delete type is required', 'ithemeland-bulk-posts-editing-lite'),
            ]);
        }

        $post_ids = [];
        global $wpdb;

        $delete_type = sanitize_text_field(wp_unslash($_POST['delete_type']));
        $post_type = Post_Helper::get_active_post_type();
        $selected_post_ids = isset($_POST['post_ids']) ? array_map('intval', $_POST['post_ids']) : [];

        if ($delete_type == 'all' || ($selected_post_ids == 'all_filtered' && !is_array($_POST['post_ids']))) {
            $filter_service = Post_Filter_Service::get_instance();
            $posts = $filter_service->get_filtered_posts(Sanitizer::array($_POST['filter_data']), [ //phpcs:ignore
                'posts_per_page' => '-1',
                'fields' => 'ids',
                'post_type' => [$post_type],
            ]);
            $post_ids = $posts['post_ids'];
        }

        if (empty($post_ids)) {
            $post_ids = !empty($selected_post_ids) ? $selected_post_ids : [];
        }

        // Condition: If selected_post_ids exist, filter within them
        $post_filter = !empty($selected_post_ids) ? "AND ID IN (" . implode(',', $selected_post_ids) . ")" : "";
        $post = new Post;

        switch ($delete_type) {
            case 'dupoldest_title':
            case 'duplatest_title':
            case 'dupoldest_content':
            case 'duplatest_content':
            case 'dupoldest_title_content':
            case 'duplatest_title_content':
                $post_ids = $post->get_duplicates($wpdb, $post_type, $delete_type, $post_filter);
                break;
        }

        if (empty($post_ids)) {
            $this->make_response([
                'success' => false,
                'is_processing' => true,
                'message' => esc_html__('No duplicate posts found', 'ithemeland-bulk-posts-editing-lite'),
            ]);
        }

        $post_delete = new PostDeleteService();
        $post_delete->perform($post_ids, $delete_type);

        if ($post_delete->is_processing()) {
            $this->make_response([
                'success' => true,
                'is_processing' => true,
                'total_tasks' => count($post_ids),
                'completed_tasks' => 0,
            ]);
        } else {
            $histories = $this->history_repository->get_histories();
            $history_count = $this->history_repository->get_history_count();
            $reverted = $this->history_repository->get_latest_reverted();
            $histories_rendered = Render::html(WPBEL_VIEWS_DIR . 'history/history_items.php', compact('histories'));
            $history_pagination = Render::html(WPBEL_VIEWS_DIR . 'history/history_pagination.php', compact('history_count'));

            $this->make_response([
                'success' => true,
                'message' => esc_html__('Duplicate posts deleted successfully!', 'ithemeland-bulk-posts-editing-lite'),
                'history_items' => $histories_rendered,
                'history_pagination' => $history_pagination,
                'reverted' => !empty($reverted),
                'edited_ids' => $post_ids,
            ]);
        }
        return false;
    }

    public function untrash_posts()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $post_ids = (!empty($_POST['post_ids']) && is_array($_POST['post_ids'])) ? array_map('intval', $_POST['post_ids']) : $this->post_repository->get_trash();
        if (empty($post_ids) || !is_array($post_ids)) {
            $this->make_response([
                'success' => false,
                'message' => esc_html__('Product not found !', 'ithemeland-bulk-posts-editing-lite'),
            ]);
        }

        $max = 100;
        if (count($post_ids) > $max && PostBackgroundProcess::is_enable()) {
            $background_process = PostBackgroundProcess::get_instance();
            if ($background_process->is_not_queue_empty()) {
                $this->make_response([
                    'success' => false,
                    'message' => esc_html__('Another operation is running. It is not possible to edit the information at this moment. Please wait until it finishes or set a scheduled task.', 'ithemeland-bulk-posts-editing-lite'),
                ]);
            }

            $ids = array_chunk($post_ids, $max);
            foreach ($ids as $items) {
                if (empty($items) || !is_array($items)) {
                    continue;
                }
                $background_process->push_to_queue([
                    'handler' => 'post_restore',
                    'post_ids' => array_map('intval', $items),
                ]);
                $background_process->save();
            }

            $background_process->set_total_tasks(count($post_ids));
            $background_process->start();
            $this->make_response([
                'success' => true,
                'is_processing' => true,
                'total_tasks' => count($post_ids),
                'completed_tasks' => 0,
            ]);
        } else {
            foreach ($post_ids as $post_id) {
                wp_untrash_post(intval($post_id));
            }
            $this->make_response([
                'success' => true,
                'message' => esc_html__('Success !', 'ithemeland-bulk-posts-editing-lite'),
            ]);
        }
    }

    public function empty_trash()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $post_ids = $this->post_repository->get_trash();
        if (empty($post_ids)) {
            $this->make_response([
                'success' => false,
                'message' => esc_html__('Post not found !', 'ithemeland-bulk-posts-editing-lite'),
            ]);
        }

        $post_delete = new PostDeleteService();
        $post_delete->perform($post_ids, 'permanently');

        $this->make_response([
            'success' => true,
            'message' => esc_html__('Success !', 'ithemeland-bulk-posts-editing-lite'),
            'is_processing' => $post_delete->is_processing(),
            'total_tasks' => count($post_ids),
            'completed_tasks' => 0,
        ]);
    }

    public function filter_profile_change_use_always()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['preset_key'])) {
            (new Search())->update_use_always(sanitize_text_field(wp_unslash($_POST['preset_key'])));
            $this->make_response([
                'success' => true,
            ]);
        }
        return false;
    }

    public function change_count_per_page()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['count_per_page'])) {
            $setting_repository = new Setting();
            $setting_repository->update_current_settings([
                'count_per_page' => intval($_POST['count_per_page']),
            ]);
            $this->make_response([
                'success' => true,
            ]);
        }
        return false;
    }

    public function column_manager_get_fields_for_edit()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['preset_key'])) {
            $preset = (new Column())->get_preset(sanitize_text_field(wp_unslash($_POST['preset_key'])));
            if ($preset) {
                $output = '';
                $fields = [];
                if (isset($preset['fields'])) {
                    foreach ($preset['fields'] as $field) {
                        $field_info = [
                            'field_name' => $field['name'],
                            'field_label' => $field['label'],
                            'field_title' => $field['title'],
                            'field_background_color' => $field['background_color'],
                            'field_text_color' => $field['text_color'],
                            'field_action' => "edit",
                        ];
                        $fields[] = sanitize_text_field($field['name']);
                        $output .= Render::html(WPBEL_VIEWS_DIR . 'column_manager/field_item.php', $field_info);
                    }
                }

                $this->make_response([
                    'html' => $output,
                    'fields' => implode(',', $fields),
                ]);
            }
        }

        return false;
    }

    public function add_meta_keys_by_post_id()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (empty($_POST['post_id'])) {
            return false;
        }

        $post_id = intval($_POST['post_id']);
        $post = $this->post_repository->get_post($post_id);
        if (!($post instanceof \WP_Post)) {
            die();
        }
        $meta_keys = Meta_Fields::remove_default_meta_keys(array_keys(get_post_meta($post->ID)));
        $output = "";
        if (!empty($meta_keys)) {
            foreach ($meta_keys as $meta_key) {
                $meta_field['key'] = $meta_key;
                $meta_fields_main_types = Meta_Field::get_main_types();
                $meta_fields_sub_types = Meta_Field::get_sub_types();
                $output .= Render::html(WPBEL_VIEWS_DIR . "meta_field/meta_field_item.php", compact('meta_field', 'meta_fields_main_types', 'meta_fields_sub_types'));
            }
        }

        $this->make_response($output);
        return false;
    }

    public function update_post_taxonomy()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['post_ids']) && is_array($_POST['post_ids']) && !empty($_POST['field']) && !empty($_POST['values'])) {
            $post_ids = array_map('intval', $_POST['post_ids']);
            $field = sanitize_text_field(wp_unslash($_POST['field']));
            $this->save_history($post_ids, ['taxonomy' => $field], Sanitizer::array($_POST['values']), History::INLINE_OPERATION); //phpcs:ignore

            $result = $this->post_repository->update($post_ids, [
                'field_type' => 'taxonomy',
                'field' => $field,
                'value' => Sanitizer::array($_POST['values']), //phpcs:ignore
                'operator' => 'taxonomy_replace',
            ]);
            if (!$result) {
                return false;
            }

            $histories = $this->history_repository->get_histories();
            $history_count = $this->history_repository->get_history_count();
            $reverted = $this->history_repository->get_latest_reverted();
            $histories_rendered = Render::html(WPBEL_VIEWS_DIR . 'history/history_items.php', compact('histories'));
            $history_pagination = Render::html(WPBEL_VIEWS_DIR . 'history/history_pagination.php', compact('history_count'));

            $this->make_response([
                'success' => true,
                'message' => esc_html__('Success !', 'ithemeland-bulk-posts-editing-lite'),
                'history_items' => $histories_rendered,
                'history_pagination' => $history_pagination,
                'reverted' => !empty($reverted),
                'edited_ids' => $post_ids,
            ]);
        }
        return false;
    }

    public function add_post_taxonomy()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (!empty($_POST['taxonomy_info']) && !empty($_POST['taxonomy_name']) && !empty($_POST['taxonomy_info']['name']) && !empty($_POST['taxonomy_info']['post_id'])) {
            $result = wp_insert_category([
                'taxonomy' => sanitize_text_field(wp_unslash($_POST['taxonomy_name'])),
                'cat_name' => sanitize_text_field(wp_unslash($_POST['taxonomy_info']['name'])),
                'category_nicename' => (!empty($_POST['taxonomy_info']['slug'])) ?  sanitize_text_field(wp_unslash($_POST['taxonomy_info']['slug'])) : '',
                'category_description' => (!empty($_POST['taxonomy_info']['description'])) ? sanitize_text_field(wp_unslash($_POST['taxonomy_info']['description'])) : '',
                'category_parent' => (isset($_POST['taxonomy_info']['parent'])) ? intval($_POST['taxonomy_info']['parent']) : 0,
            ]);
            $checked = ($_POST['taxonomy_name'] == 'post_tag') ? wp_get_post_terms(intval($_POST['taxonomy_info']['post_id']), sanitize_text_field(wp_unslash($_POST['taxonomy_name'])), ['fields' => 'names']) : wp_get_post_terms(intval($_POST['taxonomy_info']['post_id']), sanitize_text_field(wp_unslash($_POST['taxonomy_name'])), ['fields' => 'ids']);
            if (!empty($result)) {
                $taxonomy_items = Taxonomy_Helper::get_post_taxonomy_list(sanitize_text_field(wp_unslash($_POST['taxonomy_name'])), $checked);
                $this->make_response([
                    'success' => true,
                    'post_id' => intval($_POST['taxonomy_info']['post_id']),
                    'taxonomy_items' => $taxonomy_items,
                ]);
            }
        }
    }

    public function save_column_profile()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (isset($_POST['preset_key']) && isset($_POST['type'])) {
            $column_repository = new Column();
            $fields = $column_repository->get_columns();
            $preset['date_modified'] = gmdate('Y-m-d H:i:s', time());

            switch ($_POST['type']) {
                case 'save_as_new':
                    $preset['name'] = "Preset " . wp_rand(100, 999);
                    $preset['key'] = 'preset-' . wp_rand(1000000, 9999999);
                    break;
                case 'update_changes':
                    $preset_item = $column_repository->get_preset(sanitize_text_field(wp_unslash($_POST['preset_key'])));
                    if (!$preset_item) {
                        return false;
                    }
                    $preset['name'] = sanitize_text_field($preset_item['name']);
                    $preset['key'] = sanitize_text_field($preset_item['key']);
                    break;
            }

            $preset['fields'] = [];
            if (!empty($_POST['items'])) {
                foreach ($_POST['items'] as $item) { //phpcs:ignore
                    if (isset($fields[$item])) {
                        $item = sanitize_text_field(wp_unslash($item));
                        $preset['fields'][$item] = [
                            'name' => $item,
                            'label' => $fields[$item]['label'],
                            'title' => $fields[$item]['label'],
                            'editable' => $fields[$item]['editable'],
                            'content_type' => $fields[$item]['content_type'],
                            'background_color' => '#fff',
                            'text_color' => '#444',
                        ];
                        if (isset($fields[$item]['sortable'])) {
                            $preset["fields"][$item]['sortable'] = $fields[$item]['sortable'];
                        }
                        if (isset($fields[$item]['options'])) {
                            $preset["fields"][$item]['options'] = $fields[$item]['options'];
                        }
                        if (isset($fields[$item]['field_type'])) {
                            $preset["fields"][$item]['field_type'] = $fields[$item]['field_type'];
                        }
                        $preset['checked'][] = $item;
                    }
                }
            }

            $column_repository->update($preset);
            $column_repository->set_active_columns($preset['key'], $preset['fields']);
            $this->make_response([
                'success' => true,
            ]);
        }
        return false;
    }

    public function sort_by_column()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (!empty($_POST['column_name']) && !empty($_POST['sort_type']) && !empty($_POST['filter_data'])) {
            $setting_repository = new Setting();
            $setting_repository->update_current_settings([
                'sort_by' => sanitize_text_field(wp_unslash($_POST['column_name'])),
                'sort_type' => sanitize_text_field(wp_unslash($_POST['sort_type'])),

            ]);
            $filter_data = Sanitizer::array($_POST['filter_data']); //phpcs:ignore
            $result = $this->post_repository->get_posts_list([Post_Helper::get_active_post_type()], $filter_data, 1);
            $this->make_response([
                'success' => true,
                'filter_data' => $filter_data,
                'posts_list' => $result->posts_list,
                'status_filters' => $result->status_filters,
                'pagination' => $result->pagination,
                'posts_count' => $result->count,
            ]);
        }
        return false;
    }

    public function history_change_page()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (empty($_POST['page'])) {
            return false;
        }

        $where = [];

        if (isset($_POST['filters'])) {
            if (isset($_POST['filters']['operation']) && !empty($_POST['filters']['operation'])) {
                $where['operation_type'] = sanitize_text_field(wp_unslash($_POST['filters']['operation']));
            }
            if (isset($_POST['filters']['author']) && !empty($_POST['filters']['author'])) {
                $where['user_id'] = sanitize_text_field(wp_unslash($_POST['filters']['author']));
            }
            if (isset($_POST['filters']['fields']) && !empty($_POST['filters']['fields'])) {
                $where['fields'] = (is_array($_POST['filters']['fields'])) ? Sanitizer::array($_POST['filters']['fields']) : sanitize_text_field(wp_unslash($_POST['filters']['fields'])); //phpcs:ignore
            }
            if (isset($_POST['filters']['date'])) {
                $where['operation_date'] = sanitize_text_field(wp_unslash($_POST['filters']['date']));
            }
        }
        $per_page = 10;
        $history_count = $this->history_repository->get_history_count($where);
        $current_page = intval($_POST['page']);
        $offset = intval($current_page - 1) * $per_page;
        $histories = $this->history_repository->get_histories($where, $per_page, $offset);
        $histories_rendered = Render::html(WPBEL_VIEWS_DIR . 'history/history_items.php', compact('histories'));
        $history_pagination = Render::html(WPBEL_VIEWS_DIR . 'history/history_pagination.php', compact('history_count', 'per_page', 'current_page'));

        $this->make_response([
            'success' => true,
            'history_items' => $histories_rendered,
            'history_pagination' => $history_pagination,
        ]);
    }

    public function clear_filter_data()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $search_repository = new Search();
        $search_repository->delete_current_data();
        $this->make_response([
            'success' => true,
        ]);
    }

    public function get_post_custom_field_files()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        if (empty($_POST['post_id']) || empty($_POST['field_name'])) {
            $this->make_response([
                'success' => false
            ]);
        }

        $files = get_post_meta(intval($_POST['post_id']), sanitize_text_field(wp_unslash($_POST['field_name'])), true);
        if (empty($files) || !is_array($files)) {
            $this->make_response([
                'success' => false
            ]);
        }

        $files_html = "";
        foreach ($files as $file) {
            $file_id = md5(time() . random_int(100, 999));
            $files_html .= Render::html(WPBEL_VIEWS_DIR . 'bulk_edit/columns_modal/custom_field_file_item.php', compact('file', 'file_id'));
        }

        $this->make_response([
            'success' => true,
            'files' => $files_html
        ]);
    }

    public function add_custom_field_file_item()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $file_id = md5(time() . random_int(100, 999));
        $output = Render::html(WPBEL_VIEWS_DIR . 'bulk_edit/columns_modal/custom_field_file_item.php', compact('file_id'));
        $this->make_response([
            'success' => true,
            'file_item' => $output,
        ]);

        return false;
    }

    public function bulk_edit_add_custom_field_file_item()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpbe_ajax_nonce')) {
            die();
        }

        $file_id = md5(time() . random_int(100, 999));
        $output = Render::html(WPBEL_VIEWS_DIR . 'bulk_edit/custom_field_file_item.php', compact('file_id'));
        $this->make_response([
            'success' => true,
            'file_item' => $output,
        ]);

        return false;
    }

    private function make_response($data)
    {
        echo (is_array($data)) ? wp_json_encode($data) : wp_kses($data, Sanitizer::allowed_html());
        die();
    }
}
