<?php
namespace Prodigy\includes\synchronization\cron;

use Prodigy\Includes\Helpers\Prodigy_Logger;
use Prodigy\Includes\Prodigy_Options;

/**
 * Set cron jobs class
 */
class Prodigy_Cron_Scheduler {

	/**
	 * Set cron schedule
	 */
	public function __construct() {
		if ( ! wp_next_scheduled( 'domain_change_check_event' ) ) {
			wp_schedule_event( time(), 'hourly', 'domain_change_check_event' );
		}
		add_action( 'domain_change_check_event', array( $this, 'refresh_domain_for_platform' ) );
	}

	/**
	 * @return void
	 */
	public function refresh_domain_for_platform() {
		if ( PRODIGY_DEBUG_MODE ) {
			Prodigy_Logger::add_record( Prodigy_Logger::TYPE_INFO, 'RUN cron' );
		}
		if ( $this->check_wp_domain_change() ) {
			Prodigy_Options::refresh_wp_domain_on_hs_side();
		}
	}

	/**
	 * @return bool
	 */
	private function check_wp_domain_change(): bool {
		$stored_domain  = get_option( 'previous_wp_domain' );
		$current_domain = site_url();

		if ( $current_domain !== $stored_domain ) {
			update_option( 'previous_wp_domain', $current_domain );
			return true;
		}

		return false;
	}
}
