<?php
/**
 * Background Updater
 *
 * Uses https://github.com/A5hleyRich/wp-background-processing to handle DB
 * updates in the background.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

include_once( plugin_dir_path(dirname( __FILE__)) . 'assets/lib/wp-async-request.php' );
include_once( plugin_dir_path(dirname( __FILE__)) . 'assets/lib/wp-background-process.php' );

/**
 * EMC_Background_Updater Class.
 */
class EMC_Background_Updater extends WP_EMC_Background_Process {

	/**
	 * @var string
	 */
	protected $action = 'emc_updater';

	/**
	 * Dispatch updater.
	 *
	 * Updater will still run via cron job if this fails for any reason.
	 */
	public function dispatch() {
		$dispatched = parent::dispatch();

		if ( is_wp_error( $dispatched ) ) {
			envoimoinscher_model::log( sprintf( 'Unable to dispatch EMC updater: %s', $dispatched->get_error_message() ), true );
		}
	}

	/**
	 * Handle cron healthcheck
	 *
	 * Restart the background process if not already running
	 * and data exists in the queue.
	 */
	public function handle_cron_healthcheck() {
		if ( $this->is_process_running() ) {
			// Background process already running.
			return;
		}

		if ( $this->is_queue_empty() ) {
			// No data to process.
			$this->clear_scheduled_event();
			return;
		}

		$this->handle();
	}

	/**
	 * Schedule fallback event.
	 */
	protected function schedule_event() {
		if ( ! wp_next_scheduled( $this->cron_hook_identifier ) ) {
			wp_schedule_event( time() + 10, $this->cron_interval_identifier, $this->cron_hook_identifier );
		}
	}

	/**
	 * Is the updater running?
	 * @return boolean
	 */
	public function is_updating() {
		return false === $this->is_queue_empty();
	}

	/**
	 * Task
	 *
	 * Override this method to perform any actions required on each
	 * queue item. Return the modified item for further processing
	 * in the next pass through. Or, return false to remove the
	 * item from the queue.
	 *
	 * @param string $callback Update callback function
	 * @return mixed
	 */
	protected function task( $callback ) {
		if ( ! defined( 'EMC_UPDATING' ) ) {
			define( 'EMC_UPDATING', true );
		}
        
        include_once(plugin_dir_path(dirname( __FILE__)) . 'upgrade/emc-update-functions.php');

		if ( is_callable( $callback ) ) {
			envoimoinscher_model::log( sprintf( 'Emc updates: running %s callback', $callback ), true );
			call_user_func( $callback );
            envoimoinscher_model::log( sprintf( 'Emc updates: finished %s callback', $callback ), true );
		} else {
			envoimoinscher_model::log( sprintf( 'Emc updates: could not find %s callback', $callback ), true );
		}

		return false;
	}

	/**
	 * Complete
	 *
	 * Override if applicable, but ensure that the below actions are
	 * performed, or, call parent::complete().
	 */
	protected function complete() {
		envoimoinscher_model::log( 'Emc updates: data update complete', true );
		envoimoinscher_model::update_db_version(EMC()->version);
		parent::complete();
	}
}
