<?php

/**
 * Functions for the tools status page.
 *
 * @package northmill-online-shared
 *
 * @phpcs:disable Squiz.Commenting.FunctionComment.MissingParamTag
 */
declare (strict_types=1);
namespace Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Admin\Pages\Page;

use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts\Invalid_Hub_Accounts;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts\Hub_Account_Setup;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts\WP_Repository;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Abstracts\Hub_API\Sync\Ajax\Ajax_Syncers;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Abstracts\Hub_API\Sync\Cron\Cron_Syncers;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Admin\Pages\Abstract_Tabbed_Admin_Page;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Cron\Locks;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Cron\Models\Lock_Model;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Loggers\Log_Level_Enum;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Sync\Bookkeeping\Article_Account_Codes\Article_Account_Codes;
defined('ABSPATH') || exit;
/**
 * Class Admin_Status
 */
class Admin_Status extends Abstract_Tabbed_Admin_Page
{
    const LOG_TEST_AJAX_KEY = 'log_test';
    const UPDATE_LAST_SYNCED_TIME_AJAX_KEY = 'update_last_synced_time';
    const REMOVE_CRON_LOCK_AJAX_KEY = 'remove_cron_lock';
    const REMOVE_UPDATE_TRANSIENT_AJAX_KEY = 'remove_update_transient';
    const EMPTY_WC_TAX_RATES_TABLE_AJAX_KEY = 'empty_wc_tax_rates_table';
    const REMOVE_WC_TAX_RATES_MF_ROWS_AJAX_KEY = 'remove_wc_tax_rates_mf_rows';
    /**
     * {@inheritDoc}
     */
    protected function get_page_script_dependencies(): array
    {
        return array('ajax-script-shared');
    }
    /**
     * {@inheritDoc}
     */
    public function get_script_localization(bool $is_shared): array
    {
        $loc = parent::get_script_localization($is_shared);
        $ajax_module = $this->shared->ajax;
        $loc['log_test_ajax'] = $ajax_module->get_action(self::LOG_TEST_AJAX_KEY)->get_data_for_js();
        $loc['update_last_synced_ajax'] = $ajax_module->get_action(self::UPDATE_LAST_SYNCED_TIME_AJAX_KEY)->get_data_for_js();
        $loc['remove_cron_lock_ajax'] = $ajax_module->get_action(self::REMOVE_CRON_LOCK_AJAX_KEY)->get_data_for_js();
        $loc['remove_update_transient_ajax'] = $ajax_module->get_action(self::REMOVE_UPDATE_TRANSIENT_AJAX_KEY)->get_data_for_js();
        $loc['empty_wc_tax_rates_table_ajax'] = $ajax_module->get_action(self::EMPTY_WC_TAX_RATES_TABLE_AJAX_KEY)->get_data_for_js();
        $loc['remove_wc_tax_rates_mf_rows'] = $ajax_module->get_action(self::REMOVE_WC_TAX_RATES_MF_ROWS_AJAX_KEY)->get_data_for_js();
        $loc['l10n']['confirm'] = __('Are you sure?', 'northmill-online-shared');
        return $loc;
    }
    /**
     * {@inheritDoc}
     */
    public function register_ajax_actions(): void
    {
        parent::register_ajax_actions();
        $this->shared->ajax->add_action(self::LOG_TEST_AJAX_KEY, array($this, 'ajax_log_test'));
        $this->shared->ajax->add_action(self::UPDATE_LAST_SYNCED_TIME_AJAX_KEY, array($this, 'ajax_update_latest_sync_time'));
        $this->shared->ajax->add_action(self::REMOVE_CRON_LOCK_AJAX_KEY, array($this, 'ajax_remove_lock'));
        $this->shared->ajax->add_action(self::REMOVE_UPDATE_TRANSIENT_AJAX_KEY, array($this, 'ajax_remove_plugin_update_transient'));
        $this->shared->ajax->add_action(self::EMPTY_WC_TAX_RATES_TABLE_AJAX_KEY, array($this, 'ajax_empty_wc_tax_rates_table'));
        $this->shared->ajax->add_action(self::REMOVE_WC_TAX_RATES_MF_ROWS_AJAX_KEY, array($this, 'ajax_remove_wc_tax_rates_nm_rows'));
    }
    /**
     * Get all shared tabs.
     *
     * @return array[]
     */
    protected function get_shared_tabs(): array
    {
        $shared = $this->shared;
        $main_settings = apply_filters('northmill_online_shared_admin_status_main_settings_' . $shared->package_info->get_service_name_underscored(), $shared->admin->settings->get_settings());
        $found_active = \false;
        $sections = array();
        if (!empty($main_settings)) {
            $sections['main_settings'] = array('title' => __('Main settings', 'northmill-online-shared'), 'template_part' => 'main-settings', 'view_params' => function () use ($main_settings) {
                return array('main_settings' => $main_settings);
            }, 'active' => \true);
            $found_active = \true;
        }
        $sections['logging'] = array('title' => __('Logging', 'northmill-online-shared'), 'template_part' => 'logging', 'view_params' => function () {
            return array('log_levels' => Log_Level_Enum::cases());
        }, 'active' => !$found_active);
        $sections['cron'] = array('title' => __('Cron', 'northmill-online-shared'), 'template_part' => 'cron', 'view_params' => function () use ($shared) {
            return array('cron_events' => $shared->cron->get_all_cron_events(), 'locks' => Locks::get_all());
        }, 'toc' => array(array('id' => 'cron-events', 'title' => __('Cron Events', 'northmill-online-shared')), array('id' => 'active-cron-locks', 'title' => __('Active cron locks', 'northmill-online-shared'))));
        $sections['i18n'] = array('title' => __('Translations', 'northmill-online-shared'), 'template_part' => 'i18n', 'view_params' => function () use ($shared) {
            return array('translations' => $shared->i18n->get_translations());
        }, 'active' => !$found_active);
        if ($shared->updater->should_setup()) {
            $sections['plugin-updates'] = array('title' => __('Plugin updates', 'northmill-online-shared'), 'template_part' => 'plugin-updates', 'view_params' => function () use ($shared) {
                $update_transients = $shared->updater->get_all_transients();
                $update_transients_values = array();
                foreach ($update_transients as $transient_key => $transient_name) {
                    $update_transients_values[$transient_key] = $shared->updater->get_transient($transient_key);
                }
                return array('transients' => $shared->updater->get_all_transients(), 'transient_values' => $update_transients_values);
            });
        }
        if (Hub_Account_Setup::is_setting_up_hub_accounts()) {
            $sections['latest-syncs'] = array('title' => __('Latest syncs', 'northmill-online-shared'), 'template_part' => 'latest-syncs', 'view_params' => function () {
                return array('ajax_syncers' => Ajax_Syncers::get_all());
            });
            $sections['hub-accounts'] = array('title' => __('Hub Accounts', 'northmill-online-shared'), 'template_part' => 'hub-accounts', 'view_params' => function () {
                return array('is_multiple_stocks_enabled' => Hub_Account_Setup::is_multiple_stocks_enabled(), 'all_hub_accounts' => WP_Repository::get_all(), 'all_invalid_accounts' => Invalid_Hub_Accounts::get_invalid_accounts());
            }, 'toc' => array(array('id' => 'mas-sync-status', 'title' => __('Multi-account sync status', 'northmill-online-shared')), array('id' => 'hub-account-list', 'title' => __('Accounts', 'northmill-online-shared')), array('id' => 'invalid-hub-accounts', 'title' => __('Invalid Hub Accounts', 'northmill-online-shared'))));
            $sections['bookkeeping'] = array('title' => __('Bookkeeping', 'northmill-online-shared'), 'template_part' => 'bookkeeping', 'view_params' => function () {
                return array('all_hub_accounts' => WP_Repository::get_all(), 'tax_rates_prefix' => Article_Account_Codes::get_tax_class_slug_prefix());
            }, 'toc' => array(array('id' => 'income-account-codes', 'title' => __('Income Account Codes', 'northmill-online-shared')), array('id' => 'vat-account-codes', 'title' => __('VAT Account Codes', 'northmill-online-shared')), array('id' => 'article-account-codes', 'title' => __('Article Account Codes', 'northmill-online-shared'), 'sub' => array(array('id' => 'table-wc_tax_rate_classes', 'title' => 'Table wc_tax_rate_classes'), array('id' => 'table-woocommerce_tax_rates', 'title' => 'Table woocommerce_tax_rates')))));
        }
        return $sections;
    }
    /**
     * Determines if the page should be shown in the menu.
     *
     * @return bool
     */
    public function show_in_menu(): bool
    {
        if (!parent::show_in_menu()) {
            return \false;
        }
        return ($this->shared->debug->is_on() || $this->shared->nm_hosting) && current_user_can('manage_options');
    }
    /**
     * Log test.
     *
     * @return void
     */
    public function ajax_log_test(): void
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }
        $log_level = htmlspecialchars($_POST['level_name'] ?? '');
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $log_level = Log_Level_Enum::tryFrom($log_level);
        if (!$log_level) {
            wp_send_json_error('Invalid log level', 400);
        }
        $this->shared->logger->log('logger', 'Test log', null, $log_level);
        wp_send_json_success('Log sent');
    }
    /**
     * Manually update latest sync time via status page ajax.
     *
     * @return void
     */
    public static function ajax_update_latest_sync_time(): void
    {
        // @phpcs:disable WordPress.Security.NonceVerification.Missing
        $syncer_name = htmlspecialchars($_POST['syncer']);
        $new_value = htmlspecialchars($_POST['latest_sync']);
        // @phpcs:enable
        if (!$syncer_name || !$new_value) {
            wp_send_json_error('Missing option or new value');
        }
        $cron_syncer = Cron_Syncers::get_cron_syncer($syncer_name);
        $cron_syncer->syncer->set_last_synced_wp_option($new_value, null);
        wp_send_json_success('Updated');
    }
    /**
     * Remove lock from DB.
     *
     * @return void
     */
    public static function ajax_remove_lock(): void
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }
        $slug = htmlspecialchars($_POST['lock_name'] ?? '');
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (!$slug) {
            wp_send_json_error('Invalid lock name', 400);
        }
        $lock = new Lock_Model($slug);
        $lock->clear_lock();
        if ($lock->is_any_lock()) {
            wp_send_json_error('Lock still exists', 500);
        } else {
            wp_send_json_success();
        }
    }
    /**
     * Remove plugin update transient
     *
     * @return void
     */
    public function ajax_remove_plugin_update_transient(): void
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $transient_key = htmlspecialchars($_POST['transient_key'] ?? '');
        $all_transients = $this->shared->updater->get_all_transients();
        if (!$transient_key || !isset($all_transients[$transient_key])) {
            wp_send_json_error('Invalid transient name', 400);
        }
        $deleted = $this->shared->updater->delete_transient($transient_key);
        if (!$deleted) {
            wp_send_json_error('Failed to delete transient', 500);
        } else {
            wp_send_json_success();
        }
    }
    /**
     * Empty WooCommerce tax rates table.
     *
     * @return void
     */
    public function ajax_empty_wc_tax_rates_table(): void
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }
        if (Article_Account_Codes::truncate_tax_rates_table()) {
            wp_send_json_success('Table emptied');
        } else {
            wp_send_json_error('Failed to empty table', 500);
        }
    }
    /**
     * Empty WooCommerce tax rates table.
     *
     * @return void
     */
    public function ajax_remove_wc_tax_rates_nm_rows(): void
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }
        $deleted = Article_Account_Codes::remove_prefixed_tax_rates();
        if ($deleted && $deleted > 0) {
            wp_send_json_success('Rows deleted');
        } else {
            wp_send_json_error('Failed to delete rows', 500);
        }
    }
}
