<?php
/**
 * Functions for the sync page.
 *
 * @package northmill-online-shared
 *
 * @phpcs:disable Squiz.Commenting.FunctionComment.MissingParamTag
 */

declare(strict_types=1);


namespace Northmill_Online_Shared\Modules\Admin\Pages\Page;

use Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts\WP_Repository;
use Northmill_Online_Shared\Abstracts\Hub_API\Sync\Ajax\Ajax_Syncers;
use Northmill_Online_Shared\Helpers\Hook_Helpers;
use Northmill_Online_Shared\Modules\Admin\Pages\Abstract_Admin_Page;
use Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Sync\Models\Admin_Sync_Tool_Model;
use Northmill_Online_Shared\Modules\Admin\Settings\Settings_Fields_Module;
use Northmill_Online_Shared\Modules\Cron_Module;

defined( 'ABSPATH' ) || exit;

/**
 * Class Admin_Sync
 */
class Admin_Sync extends Abstract_Admin_Page {

	/**
	 * {@inheritDoc}
	 */
	public function get_script_localization( bool $is_shared ): array {
		$loc = parent::get_script_localization( $is_shared );

		$loc['ajax_sync_actions'] = $this->get_ajax_syncer_data();

		$loc['tools'] = array();
		foreach ( $this->get_tools() as $tool ) {
			$loc['tools'][ $tool->get_id_for_js() ] = $tool->get_data_for_js();
		}

		$loc['sync_start_processing_sync'] = __( 'Start processing:', 'northmill-online-shared' );
		$loc['sync_completed_processing']  = __( 'Completed:', 'northmill-online-shared' );
		$loc['sync_skipped_processing']    = __( 'Disabled:', 'northmill-online-shared' );
		$loc['sync_cleaned']               = __( 'Cleaned:', 'northmill-online-shared' );
		$loc['sync_processed']             = __( 'Processed page', 'northmill-online-shared' );
		$loc['sync_processed_for_account'] = __( 'for Hub account', 'northmill-online-shared' );
		$loc['sync_completed']             = __( 'Sync completed with Northmill.', 'northmill-online-shared' );
		$loc['sync_error']                 = __( 'Something went wrong. You can attempt to resume the sync using the button above.', 'northmill-online-shared' );
		$loc['sync_error_resume']          = __( 'Something went wrong. Attempting to resume...', 'northmill-online-shared' );
		$loc['action_started']             = __( 'Started:', 'northmill-online-shared' );
		$loc['action_completed']           = __( 'Done.', 'northmill-online-shared' );
		$loc['action_failed']              = __( 'Something failed when processing.', 'northmill-online-shared' );

		return $loc;
	}

	/**
	 * {@inheritDoc}
	 */
	public function register_ajax_actions(): void {
		parent::register_ajax_actions();

		foreach ( $this->get_tools() as $tool ) {
			$tool->add_ajax_action();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_page_params(): array {
		$params = parent::get_page_params();

		$settings_menu_slug = $this->shared->admin->pages->get_page( $this->shared->package_info->get_service_name(), 'settings' )->menu_slug;

		$syncer_event = $this->shared->cron->get_cron_event( Cron_Module::CRON_EVENT_SYNC );

		$params['title']            = $this->shared->package_info->package_data->get_name();
		$params['has_hub_accounts'] = count( WP_Repository::get_all_current_accounts() ) > 0;
		$params['sync_status']      = $syncer_event->print_status_texts( true );
		$params['settings_url']     = admin_url( 'admin.php?page=' . $settings_menu_slug );
		$params['sync_enabled']     = $this->shared->admin->settings->is_setting_enabled( Settings_Fields_Module::AUTO_SYNC );
		$params['ajax_syncer_data'] = $this->get_ajax_syncer_data();
		$params['tools']            = $this->get_tools();

		return $params;
	}

	/**
	 * Get the custom tools for the sync page.
	 *
	 * @return Admin_Sync_Tool_Model[]
	 */
	private function get_tools(): array {
		return Hook_Helpers::apply_scoped_filters(
			'northmill_online_shared_sync_page_tools',
			array(
				new Admin_Sync_Tool_Model(
					'mf_btn_reactivate_cron',
					__( 'Reset automatic sync', 'northmill-online-shared' ),
					__( 'Reset sync', 'northmill-online-shared' ),
					array( $this, 'ajax_reactivate_cron' ),
				),
			),
		);
	}

	/**
	 * Get the syncer data for the sync page.
	 *
	 * @return array
	 */
	private function get_ajax_syncer_data(): array {
		$ajax_syncers = Ajax_Syncers::get_all( true );

		return array_map(
			function ( $syncer ) {
				return array_merge(
					$syncer->get_data_for_js(),
					array(
						'title' => $syncer->syncer->get_display_name(),
					)
				);
			},
			$ajax_syncers
		);
	}

	/**
	 * Reactive cron from AJAX.
	 *
	 * @return void
	 */
	public function ajax_reactivate_cron(): void {
		$this->shared->cron->check_event_statuses();

		if ( ! $this->shared->admin->settings->is_setting_enabled( Settings_Fields_Module::AUTO_SYNC ) ) {
			wp_send_json_success( __( 'Sync disabled', 'northmill-online-shared' ) );
		}

		$schedules = wp_get_schedules();
		$schedule  = $this->shared->admin->settings->get_setting( Settings_Fields_Module::SYNC_INTERVAL );
		if (
			is_null( $schedule ) ||
			! isset( $schedules[ $schedule ] )
		) {
			wp_send_json_error( __( 'Invalid sync interval', 'northmill-online-shared' ) );
		}

		wp_send_json_success();
	}
}
