<?php

/**
 * Admin page for handling syncing settings from Hub.
 *
 * @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 Closure;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Helpers\Hook_Helpers;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Admin\Pages\Abstract_Admin_Page;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Sync_Settings\Abstract_Online_Solution_Settings_Sync;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Sync_Settings\Online_Solution_Customizations;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Sync_Settings\Online_Solution_Shortcodes;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Cron_Module;
defined('ABSPATH') || exit;
/**
 * Class Admin_Sync_Settings
 */
class Admin_Sync_Settings extends Abstract_Admin_Page
{
    private const AJAX_ENABLE_SYNC = 'nms_admin_sync_settings_enable';
    private const AJAX_DISABLE_SYNC = 'nms_admin_sync_settings_disable';
    private const AJAX_SYNC_NOW = 'nms_admin_sync_settings_now';
    /**
     * The syncer instance.
     *
     * @var Abstract_Online_Solution_Settings_Sync $syncer
     */
    public Abstract_Online_Solution_Settings_Sync $syncer;
    /**
     * Get the syncer class.
     *
     * @return string|null
     */
    public static function get_syncer_class(): ?string
    {
        $syncer_class = Hook_Helpers::apply_scoped_filters('northmill_online_shared_online_solution_settings_syncer', null);
        if (is_string($syncer_class) && class_exists($syncer_class) && is_subclass_of($syncer_class, Abstract_Online_Solution_Settings_Sync::class)) {
            return $syncer_class;
        }
        return null;
    }
    /**
     * {@inheritDoc}
     */
    public function __construct(string $page_collection_key, string $page_id, array|Closure $page_title, array|Closure $page_menu_title = null, bool $is_main_page = \false, array|Closure|null $script_localization_callback = null, array|Closure|null $script_dependencies_callback = null)
    {
        parent::__construct($page_collection_key, $page_id, $page_title, $page_menu_title, $is_main_page, $script_localization_callback, $script_dependencies_callback);
        $syncer_class = self::get_syncer_class();
        $this->syncer = new $syncer_class();
        new Online_Solution_Customizations($this->syncer);
        new Online_Solution_Shortcodes($this->syncer);
    }
    /**
     * {@inheritDoc}
     */
    public function register_ajax_actions(): void
    {
        parent::register_ajax_actions();
        $this->shared->ajax->add_action(self::AJAX_ENABLE_SYNC, array($this, 'ajax_enable_sync'));
        $this->shared->ajax->add_action(self::AJAX_DISABLE_SYNC, array($this, 'ajax_disable_sync'));
        $this->shared->ajax->add_action(self::AJAX_SYNC_NOW, array($this, 'ajax_sync_now'));
    }
    /**
     * {@inheritDoc}
     */
    protected function get_page_script_dependencies(): array
    {
        return array('ajax-script-shared');
    }
    /**
     * {@inheritDoc}
     */
    public function get_script_localization(bool $is_shared): array
    {
        $localization = parent::get_script_localization($is_shared);
        $localization['l10n']['status']['start'] = __('Starting', 'northmill-online-shared');
        $localization['l10n']['status']['done'] = __('Done', 'northmill-online-shared');
        $localization['l10n']['status']['failed'] = __('Failed', 'northmill-online-shared');
        $localization['l10n']['action']['sync'] = __('Sync', 'northmill-online-shared');
        $localization['l10n']['action']['enable'] = __('Enable automatic sync', 'northmill-online-shared');
        $localization['l10n']['action']['disable'] = __('Disable automatic sync', 'northmill-online-shared');
        $localization['l10n']['action']['check'] = __('Check sync status', 'northmill-online-shared');
        $localization['ajax_actions'] = array('enable_sync' => $this->shared->ajax->get_action(self::AJAX_ENABLE_SYNC)?->get_data_for_js(), 'disable_sync' => $this->shared->ajax->get_action(self::AJAX_DISABLE_SYNC)?->get_data_for_js(), 'sync_now' => $this->shared->ajax->get_action(self::AJAX_SYNC_NOW)?->get_data_for_js());
        $localization['is_enabled'] = $this->syncer->is_sync_enabled();
        return $localization;
    }
    /**
     * {@inheritDoc}
     */
    public function get_page_params(): array
    {
        $next = $this->shared->cron->get_cron_event(Cron_Module::CRON_EVENT_SYNC_SETTINGS)?->get_next_scheduled();
        if ($next) {
            $next = date_i18n('Y-m-d H:i:s', $next);
        }
        $data_preview_html = $this->shared->template_loader->get_admin_template_part('sync-settings/data-preview', array('data_preview' => $this->syncer->get_preview_data()), \false, \true);
        return array_merge(parent::get_page_params(), array('sync_status' => $this->get_sync_status_html(), 'data_preview' => $data_preview_html));
    }
    /**
     * Get the sync status HTML.
     *
     * @return string
     */
    private function get_sync_status_html(): string
    {
        $status_html = esc_html(sprintf(
            // translators: %s: date and time.
            __('Last sync: %s.', 'northmill-online-shared'),
            $this->syncer->get_last_sync_time()
        ));
        $next = $this->shared->cron->get_cron_event(Cron_Module::CRON_EVENT_SYNC_SETTINGS)->get_next_scheduled();
        if ($next) {
            $next = wp_date('Y-m-d H:i:s', $next);
            $status_html .= '<br>';
            $status_html .= esc_html(sprintf(
                // translators: %s: date and time.
                __('Next sync: %s.', 'northmill-online-shared'),
                $next
            ));
        }
        return $status_html;
    }
    /**
     * Enable sync from AJAX.
     */
    public function ajax_enable_sync(): array
    {
        return $this->ajax_update_option(\true);
    }
    /**
     * Disable sync from AJAX.
     */
    public function ajax_disable_sync(): array
    {
        return $this->ajax_update_option(\false);
    }
    /**
     * Toggle sync from AJAX.
     *
     * @param bool $enabled Whether to enable or disable the sync.
     */
    private function ajax_update_option(bool $enabled): array
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }
        $updated = $this->syncer->update_sync_enabled($enabled);
        if (!$updated) {
            wp_send_json_error('Failed to update option');
        }
        return array('sync_status' => $this->get_sync_status_html());
    }
    /**
     * Trigger manual sync.
     */
    public function ajax_sync_now(): array
    {
        $success = $this->syncer->sync();
        if (!$success) {
            wp_send_json_error('Failed to sync');
        }
        $data_preview_html = $this->shared->template_loader->get_admin_template_part('sync-settings/data-preview', array('data_preview' => $this->syncer->get_preview_data()), \false, \true);
        return array('data_preview_html' => $data_preview_html, 'sync_status' => $this->get_sync_status_html());
    }
}
