<?php
namespace SabaiApps\Directories\Component\System\Helper;

use SabaiApps\Directories\Application;

/**
 * CronHelper provides methods to run scheduled tasks (cron) and manage task intervals.
 */
class CronHelper {

	/**
	 * Runs the cron tasks and logs the results.
	 *
	 * @param Application $application
	 * @param array|null  $logs
	 * @param bool        $force
	 */
	public function help( Application $application, ?array &$logs = null, $force = false ) {
		// Init progress
		if ( ! isset( $logs ) ) {
			$logs = array(
				'notice'  => array(),
				'info'    => array(),
				'success' => array(),
				'error'   => array(),
				'warning' => array(),
			);
			$log  = true;
		}
		$logs['info'][] = __( 'Running cron...', 'directories-pro' );
		// Get timestamp of last cron
		$last_run = $application->getPlatform()->getOption( 'system_cron_last' );
		if ( ! is_array( $last_run ) ) {
			$last_run = array( '' => time() );
		} else {
			$logs['info'][] = sprintf(
				__( 'Cron was last run at %s', 'directories-pro' ),
				$application->System_Date_datetime( $last_run[''] )
			);
			$last_run['']   = time();
		}
		// Invoke cron
		$application->Action( 'system_cron', array( &$logs, &$last_run, $force ) );
		// Save timestamp
		$application->getPlatform()->setOption( 'system_cron_last', $last_run );
		// Log
		if ( ! empty( $log ) ) {
			foreach ( array_keys( $logs ) as $level ) {
				foreach ( (array) $logs[ $level ] as $log ) {
					switch ( $level ) {
						case 'notice':
							$application->logDebug( strip_tags( $log ) );
							break;
						case 'success':
						case 'info':
							$application->logNotice( strip_tags( $log ) );
							break;
						case 'warning':
							$application->logWarning( strip_tags( $log ) );
							break;
						case 'error':
							$application->logError( strip_tags( $log ) );
							break;
						default:
					}
				}
			}
		}
	}

	/**
	 * Checks if a cron task can be run based on the interval and updates last run time.
	 *
	 * @param Application $application
	 * @param string      $name
	 * @param array       $logs
	 * @param array       $lastRun
	 * @param int         $interval
	 * @param bool        $updateLastRun
	 * @param bool        $addLog
	 * @return bool
	 */
	public function canRunTask( Application $application, $name, array &$logs, array &$lastRun, $interval = 86400, $updateLastRun = true, $addLog = true ) {
		$ret = true;
		if ( ! empty( $lastRun[ $name ] ) ) {
			$ret = time() > $lastRun[ $name ] + $interval;
			if ( ! $ret ) {
				// Add log?
				if ( $addLog ) {
					$logs['info'][] = sprintf(
						__( '%1$s - cron task was last run at %2$s, skipping until %3$s.', 'directories-pro' ),
						$name,
						$application->System_Date_datetime( $lastRun[ $name ] ),
						$application->System_Date_datetime( $lastRun[ $name ] + $interval )
					);
				}
			}
		}
		// Update last run timestamp?
		if ( $ret && $updateLastRun ) {
			$lastRun[ $name ] = time();
		}

		return $ret;
	}
}
