<?php

namespace EstatebudConnect\Controllers;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Plugin;
use EstatebudConnect\Configs\App;
use EstatebudConnect\Configs\Defaults;
use EstatebudConnect\Core\Log;
use EstatebudConnect\Core\Cache;
use EstatebudConnect\Core\Locale;
use EstatebudConnect\Utilities\Helper;
use EstatebudConnect\Traits\Singleton;
use EstatebudConnect\Services\Estatebud;
use EstatebudConnect\Models\Settings as SettingsModel;
use EstatebudConnect\Models\Property;
use EstatebudConnect\Models\Project;
use EstatebudConnect\Models\Forms as FormsModel;
use EstatebudConnect\Models\SearchExperience as SearchExperienceModel;
use EstatebudConnect\Models\Localizations;

class Admin
{
    use Singleton;

    private function __construct()
    {
        add_action('admin_menu', function () {
            $icon =
                'data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMzI0IDM2MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik05MC44Nzk5IDU3LjIyNjdDMTI1LjUyIDM3LjIyNjcgMTYxLjc2IDIwIDE2MS43NiAyMEMxNjEuNzYgMjAgMTk4IDM3LjIyNjcgMjMyLjY0IDU3LjIyNjdDMjY3LjI4IDc3LjIyNjcgMzAwLjMyIDEwMCAzMDAuMzIgMTAwQzMwMC4zMiAxMDAgMzAzLjUyIDE0MCAzMDMuNTIgMTgwQzMwMy41MiAyMjAgMzAwLjMyIDI2MCAzMDAuMzIgMjYwQzMwMC4zMiAyNjAgMjY3LjI4IDI4Mi43NzMgMjMyLjY0IDMwMi43NzNDMTk4IDMyMi43NzMgMTYxLjc2IDM0MCAxNjEuNzYgMzQwQzE2MS43NiAzNDAgMTI1LjUyIDMyMi43NzMgOTAuODc5OSAzMDIuNzczQzU2LjI0IDI4Mi43NzMgMjMuMiAyNjAgMjMuMiAyNjBDMjMuMiAyNjAgMjAgMjIwIDIwIDE4MEMyMCAxNDAgMjMuMiAxMDAgMjMuMiAxMDBDMjMuMiAxMDAgNTYuMjQgNzcuMjI2NyA5MC44Nzk5IDU3LjIyNjdaTTE2MS43NiAxOTkuMTczQzE4MS40NCAxOTkuMTczIDIwMS4yIDIwMC41MDcgMjE5LjM2IDIwMi40QzIxOS4zNiAyMTcuMTczIDIxMy43NiAyMzAuNTg3IDIwNC42MTQgMjQwLjhDMTk0LjA1MyAyNTIuNTMzIDE3OC43NzQgMjYwIDE2MS43NiAyNjBDMTQ0LjcyIDI2MCAxMjkuNDY3IDI1Mi41MzMgMTE4LjkwNyAyNDAuOEMxMDkuNzYgMjMwLjU4NyAxMDQuMTYgMjE3LjE3MyAxMDQuMTYgMjAyLjRDMTIyLjMyIDIwMC41MDcgMTQyLjA4IDE5OS4xNzMgMTYxLjc2IDE5OS4xNzNaTTI2NC4xMDcgMTM3Ljc1OUMyNjQuMzczIDE0My44OTMgMjY0LjYxMyAxNTAuNTA2IDI2NC44IDE1Ny4zODZDMjM4LjQ4IDE1My4wMTMgMTk5Ljk0NyAxNDcuOTk5IDE2MS43NiAxNDcuOTk5QzEyMy41NzMgMTQ3Ljk5OSA4NS4wNCAxNTMuMDEzIDU4LjcyIDE1Ny4zODZDNTguOTA2NyAxNTAuNTA2IDU5LjE0NjcgMTQzLjg2NiA1OS40MTMzIDEzNy43NTlDODYuMTg2NSAxMzMuNDM5IDEyMy43ODcgMTI4Ljc5OSAxNjEuNzYgMTI4Ljc5OUMxOTkuNzMzIDEyOC43OTkgMjM3LjMzMyAxMzMuNDM5IDI2NC4xMDcgMTM3Ljc1OVoiIGZpbGw9IiNBN0FBQUQiLz4KPC9zdmc+';

            add_menu_page('', 'Estatebud', 'manage_options', App::SLUG, [$this, 'menu_markup'], $icon, 99);
            add_submenu_page(App::SLUG, App::SLUG, 'Dashboard', 'manage_options', App::SLUG);
            add_submenu_page(App::SLUG, App::SLUG, 'Search experience', 'manage_options', App::SLUG);
            add_submenu_page(App::SLUG, App::SLUG, 'Property listing', 'manage_options', App::SLUG);
            add_submenu_page(App::SLUG, App::SLUG, 'Project listing', 'manage_options', App::SLUG);
            add_submenu_page(App::SLUG, App::SLUG, 'Forms', 'manage_options', App::SLUG);
            add_submenu_page(App::SLUG, App::SLUG, 'Localization', 'manage_options', App::SLUG);
            add_submenu_page(App::SLUG, App::SLUG, 'Settings', 'manage_options', App::SLUG);

            remove_filter('update_footer', 'core_update_footer');
        });

        add_action('admin_enqueue_scripts', [$this, 'scripts']);
        add_filter('admin_footer_text', '__return_false', 10);

        $this->ajax_Controllers();
    }

    public function ajax_Controllers()
    {
        add_action('wp_ajax_estatebud_post_data', [$this, 'handle_request']);
        add_action('wp_ajax_estatebud_modal_form_data', [$this, 'handle_modal_form_request']);
        add_action('wp_ajax_estatebud_delete_item', [$this, 'handle_delete_form_items']);
        add_action('wp_ajax_estatebud_clone_item', [$this, 'handle_clone_item']);
        add_action('wp_ajax_estatebud_get_data', [$this, 'handle_get_form_create_markup']);
        add_action('wp_ajax_estatebud_get_field_option_data', [$this, 'handle_get_field_option_data']);
        add_action('wp_ajax_estatebud_get_search_exp_modal_markup', [$this, 'handle_get_search_exp_modal_markup']);
        add_action('wp_ajax_estatebud_get_shortcode_gen_modal_markup', [$this, 'get_shortcode_gen_modal_markup']);
        add_action('wp_ajax_estatebud_get_localizations', [$this, 'handle_get_localizations']);
        add_action('wp_ajax_estatebud_get_default_translations', [$this, 'handle_get_default_translations']);
        add_action('wp_ajax_estatebud_purge_cache', [$this, 'handle_purge_cache']);
    }

    public function menu_markup()
    {
        wp_enqueue_style(App::SLUG);
        wp_enqueue_script(App::SLUG);
        Helper::render_markup_from_views('Admin/menu.php', [], 'admin_menu_file_path');
    }

    public function scripts(): void
    {
        wp_register_style(App::SLUG . '-choices', Helper::get_url('assets/third-party/choices/choices.css'), [], App::VERSION);
        wp_register_script(
            App::SLUG . '-choices',
            Helper::get_url('assets/third-party/choices/choices.js'),
            [],
            App::VERSION,
            true,
        );
        wp_register_script(App::SLUG . '-ace', Helper::get_url('assets/third-party/ace/ace.js'), [], App::VERSION, true);
        wp_register_style(
            App::SLUG,
            Helper::get_url('dist/bundle-admin.css'),
            [App::SLUG . '-choices'],
            App::VERSION,
        );

        if (Plugin::has_build_tools()) {
            wp_register_script(
                App::SLUG,
                Helper::get_url('app/Javascript/admin/index.js'),
                [App::SLUG . '-choices', App::SLUG . '-ace'],
                uniqid(),
                true,
            );
        } else {
            wp_register_script(
                App::SLUG,
                Helper::get_url('dist/bundle-admin.js'),
                [App::SLUG . '-choices', App::SLUG . '-ace'],
                App::VERSION,
                true,
            );
        }

        $pipeline_options = $this->get_pipeline_options();
        $client_field_labels = $this->get_client_field_labels();

        ob_start();
        Helper::render_markup_from_views('Admin/partials/field-settings.php', [
            'accordion_title' => 'Name',
            'client_field_labels' => $client_field_labels,
        ]);
        $accordion_layout_two = ob_get_clean();

        ob_start();
        Helper::render_markup_from_views('Admin/partials/search-exp-field-settings.php', ['group_title' => 'Name']);
        $search_exp_field_group = ob_get_clean();

        ob_start();
        Helper::render_markup_from_views('Admin/modal/partials-modal-contact.php', [
            'accordion_title' => 'Name',
            'pipeline_options' => $pipeline_options,
        ]);
        $modal_contact = ob_get_clean();

        $settings_data = SettingsModel::instance()->get_data();

        $locale_service = \EstatebudConnect\Core\Locale::instance();
        $enabled_languages = $locale_service->get_enabled_languages();

        wp_localize_script(App::SLUG, str_replace('-', '_', App::SLUG), [
            'forms_modal_contact' => $modal_contact,
            'accordions' => [
                'layout-2' => $accordion_layout_two,
            ],
            'search_exp_field_group' => $search_exp_field_group,
            'admin_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('estatebud-nonce'),
            'settings_data' => $settings_data,
            'enabled_languages' => $enabled_languages,
        ]);
    }

    public function handle_request()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $screen = sanitize_text_field(wp_unslash($_POST['screen'] ?? ''));

        switch ($screen) {
            case 'settings':
                $response = SettingsModel::instance()->save_data($_POST);
                break;
            case 'property-listing':
                $property = new Property();
                $response = $property->save_settings($_POST);
                break;
            case 'project-listing':
                $project = new Project();
                $response = $project->save_settings($_POST);
                break;
            case 'localization':
                $language = sanitize_text_field(wp_unslash($_POST['language'] ?? ''));
                $response = Localizations::instance()->save_localizations($language, $_POST['localizations'] ?? []);
                break;
            default:
                $response = false;
                break;
        }

        if ($response) {
            wp_send_json_success(
                [
                    'message' => 'Saved successfully',
                    'code' => 200,
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Saving failed',
                    'code' => 400,
                ],
                400,
            );
        }
    }

    public function handle_modal_form_request()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $request_type = sanitize_text_field(wp_unslash($_POST['formId'] ?? ''));
        $item_id = sanitize_text_field(wp_unslash($_POST['id'] ?? ''));

        switch ($request_type) {
            case 'modal-general-form':
                if (!empty($item_id)) {
                    $response = FormsModel::instance()->update_form($item_id, $_POST);
                } else {
                    $response = FormsModel::instance()->add_form($_POST);
                }
                break;
            case 'search-exp-modal-form':
                if (!empty($item_id)) {
                    $response = SearchExperienceModel::instance()->update_search_exp($item_id, $_POST);
                } else {
                    $response = SearchExperienceModel::instance()->add_search_exp($_POST);
                }
                break;
            default:
                break;
        }

        if ($response) {
            if ($request_type === 'modal-general-form') {
                $allData = FormsModel::instance()->get_all_forms();
            } else {
                $allData = SearchExperienceModel::instance()->get_all_search_exps();
            }
            wp_send_json_success(
                [
                    'message' => 'Form saved',
                    'code' => 200,
                    'data' => json_encode($allData),
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to save form',
                    'code' => 400,
                ],
                400,
            );
        }
    }

    public function handle_delete_form_items()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $form_id = sanitize_text_field(wp_unslash($_POST['formId'] ?? ''));
        $target = sanitize_text_field(wp_unslash($_POST['target'] ?? ''));

        switch ($form_id) {
            case 'forms':
                $ids = explode(',', $target);
                $response = FormsModel::instance()->delete_form($ids);
                break;
            case 'search_exp':
                $ids = explode(',', $target);
                $response = SearchExperienceModel::instance()->delete_search_exp($ids);
                break;
            default:
                break;
        }

        if ($response) {
            if ($form_id === 'forms') {
                $allData = FormsModel::instance()->get_all_forms();
            } else {
                $allData = SearchExperienceModel::instance()->get_all_search_exps();
            }
            wp_send_json_success(
                [
                    'message' => 'Item deleted successfully',
                    'code' => 200,
                    'data' => json_encode($allData),
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to delete item',
                    'code' => 400,
                ],
                400,
            );
        }
    }

    public function handle_clone_item()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $type = sanitize_text_field(wp_unslash($_POST['type'] ?? ''));
        $id = sanitize_text_field(wp_unslash($_POST['id'] ?? ''));

        if (empty($type) || empty($id)) {
            wp_send_json_error(
                [
                    'message' => 'Failed to clone: invalid parameters',
                    'code' => 400,
                ],
                400,
            );
            return;
        }

        switch ($type) {
            case 'form':
                $response = FormsModel::instance()->clone_form($id);
                break;
            case 'search_exp':
                $response = SearchExperienceModel::instance()->clone_search_exp($id);
                break;
            default:
                wp_send_json_error(
                    [
                        'message' => 'Failed to clone: invalid type',
                        'code' => 400,
                    ],
                    400,
                );
                return;
        }

        if ($response) {
            wp_send_json_success(
                [
                    'message' => 'Item cloned successfully',
                    'code' => 200,
                    'data' => json_encode($response),
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to clone item',
                    'code' => 400,
                ],
                400,
            );
        }
    }

    private function get_pipeline_options()
    {
        $pipeline_options = [
            ['value' => '', 'disabled' => false, 'selected' => false, 'label' => 'None'],
        ];

        try {
            $pipelines = Estatebud::instance()->get_pipelines();

            if (!empty($pipelines) && is_array($pipelines)) {
                foreach ($pipelines as $pipeline) {
                    if (isset($pipeline['stages']) && is_array($pipeline['stages']) && !empty($pipeline['stages'])) {
                        $stages = [];
                        foreach ($pipeline['stages'] as $stage) {
                            $stages[] = [
                                'value' => $stage['id'] ?? '',
                                'disabled' => false,
                                'selected' => false,
                                'label' => $stage['name'] ?? 'Stage',
                            ];
                        }

                        $pipeline_options[] = [
                            'is_optgroup' => true,
                            'label' => $pipeline['name'] ?? 'Pipeline',
                            'options' => $stages,
                        ];
                    }
                }
            }
        } catch (\Exception $e) {
            Log::write('Error fetching pipelines: ' . $e->getMessage());
        }

        return $pipeline_options;
    }

    private function get_client_field_labels()
    {
        $client_field_labels = [];
        try {
            $client_fields_raw = Estatebud::instance()->cache(Cache::TTL_1MO)->get_fields(['component' => 'client']);
            $needed_fields = ['first_name', 'last_name', 'name', 'email', 'phone', 'mobile'];
            
            if (!empty($client_fields_raw) && is_array($client_fields_raw)) {
                foreach ($client_fields_raw as $client_field) {
                    if (isset($client_field['name']) && in_array($client_field['name'], $needed_fields) && isset($client_field['label'])) {
                        $client_field_labels[$client_field['name']] = $client_field['label'];
                    }
                }
            }
        } catch (\Exception $e) {
            Log::write('Error fetching client fields: ' . $e->getMessage());
        }
        
        return $client_field_labels;
    }

    public function handle_get_form_create_markup()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $form_id = sanitize_text_field(wp_unslash($_POST['dataId'] ?? ''));
        $response = FormsModel::instance()->get_form($form_id);

        if (!empty($form_id) && !empty($response) && is_array($response)) {
            extract($response);
        } else {
            extract(Defaults::FORM);
        }

        $project_options = [];
        $property_options = [];

        if ($type == 'project-search') {
            $project_options = Estatebud::instance()->cache(Cache::TTL_1MO)->get_fields(['component' => 'project']);
            extract(['options' => $project_options]);
        } else {
            $property_options = Estatebud::instance()->cache(Cache::TTL_1MO)->get_fields(['component' => 'property']);
            extract(['options' => $property_options]);
        }

        $pipeline_options = $this->get_pipeline_options();

        $client_field_labels = $this->get_client_field_labels();

        ob_start();

        include __DIR__ . '/../Views/Admin/modal/form-create-modal.php';

        $html = ob_get_clean();

        if ($html) {
            wp_send_json_success(
                [
                    'message' => 'Form saved',
                    'code' => 200,
                    'data' => $html,
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to save form',
                    'code' => 400,
                ],
                400,
            );
        }
    }

    public function handle_get_search_exp_modal_markup()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $search_experience_id = sanitize_text_field(wp_unslash($_POST['dataId'] ?? ''));
        $response = SearchExperienceModel::instance()->get_search_exp($search_experience_id);

        if (!empty($search_experience_id) && !empty($response) && is_array($response)) {
            extract($response);
        } else {
            extract(Defaults::SEARCH_EXPERIENCE);
        }

        $project_options = [];
        $property_options = [];

        if ($type == 'project-search') {
            $project_options = Estatebud::instance()->cache(Cache::TTL_1MO)->get_fields(['component' => 'project']);
            extract(['options' => $project_options]);
        } else {
            $property_options = Estatebud::instance()->cache(Cache::TTL_1MO)->get_fields(['component' => 'property']);
            extract(['options' => $property_options]);
        }

        ob_start();

        include __DIR__ . '/../Views/Admin/modal/search-experience-modal.php';

        $html = ob_get_clean();

        if ($html) {
            wp_send_json_success(
                [
                    'message' => 'Form saved',
                    'code' => 200,
                    'data' => $html,
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to save form',
                    'code' => 400,
                ],
                400,
            );
        }
    }

    public function get_shortcode_gen_modal_markup()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        ob_start();

        $markup = Helper::render_markup_from_views('Admin/modal/shortcode-gen-modal.php', [
            'modal_position' => sanitize_text_field(wp_unslash($_POST['modalPosition'] ?? '')),
            'id' => sanitize_text_field(wp_unslash($_POST['id'] ?? '')),
        ]);

        $html = ob_get_clean();

        if ($html) {
            wp_send_json_success(
                [
                    'message' => 'Form saved',
                    'code' => 200,
                    'data' => $html,
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to save form',
                    'code' => 400,
                ],
                400,
            );
        }
    }

    public function handle_get_field_option_data()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $property_options = Estatebud::instance()->cache(Cache::TTL_1MO)->get_fields(['component' => 'property']);
        $project_options = Estatebud::instance()->cache(Cache::TTL_1MO)->get_fields(['component' => 'project']);
        $area_options = Estatebud::instance()->cache(Cache::TTL_5M)->get_property_areas();

        if (!is_array($property_options)) {
            $property_options = [];
        }
        if (!is_array($project_options)) {
            $project_options = [];
        }
        if (!is_array($area_options)) {
            $area_options = [];
        }

        $field_options = [
            'property' => $property_options,
            'project' => $project_options,
            'area' => $area_options,
        ];

        if ($field_options) {
            wp_send_json_success(
                [
                    'message' => 'Form saved',
                    'code' => 200,
                    'data' => $field_options,
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to save form',
                    'code' => 400,
                ],
                400,
            );
        }
    }

    public function handle_get_localizations()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $language = sanitize_text_field(wp_unslash($_POST['language'] ?? 'en'));

        $localizations = Localizations::instance()->get_localizations($language);

        $existing_translations = [];
        foreach ($localizations as $term) {
            $existing_translations[$term['key']] = $term['text'];
        }

        wp_send_json_success(
            [
                'message' => 'Fetched localizations',
                'code' => 200,
                'data' => $existing_translations,
            ],
            200,
        );
    }

    public function handle_get_default_translations()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $language = sanitize_text_field(wp_unslash($_POST['language'] ?? 'en'));

        $dynamic_terms = Helper::get_translatable_form_terms();
        $locale_terms = Locale::instance()->get_terms($language);

        foreach ($locale_terms as $key => &$term) {
            if (isset($term['value']) && is_array($term['value'])) {
                if (isset($term['value']['one'])) {
                    $term['text']['singular'] = $term['value']['one'];
                }

                if (isset($term['value']['other'])) {
                    $term['text']['plural'] = $term['value']['other'];
                }
            } else {
                $term['text'] = $term['value'];
            }
        }

        $translatable_terms = array_merge($dynamic_terms, $locale_terms);

        $default_translations = [];
        foreach ($translatable_terms as $term) {
            $default_translations[$term['key']] = $term['text'];
        }

        wp_send_json_success(
            [
                'message' => 'Fetched default translations',
                'code' => 200,
                'data' => $default_translations,
            ],
            200,
        );
    }

    public function handle_purge_cache()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'estatebud-nonce')) {
            wp_send_json_error(
                [
                    'message' => 'Nonce verification failed',
                    'code' => 403,
                ],
                403,
            );
        }

        $deleted = Cache::instance()->flush();

        if ($deleted !== false) {
            wp_send_json_success(
                [
                    'message' => sprintf('Purged %d  items from cache.', $deleted),
                    'code' => 200,
                    'deleted' => $deleted,
                ],
                200,
            );
        } else {
            wp_send_json_error(
                [
                    'message' => 'Failed to purge cache',
                    'code' => 400,
                ],
                400,
            );
        }
    }
}
