<?php
/**
 * Cron local Nexora: ejecuta cada tarea con cadencia aislada por reino.
 * El estado de ejecución vive en cache/realms/<realm>/cron_state.json.
 */

define('access', 'cron');
define('NEXORA_CRON_REALM_RUNNER', true);

if(!@include_once(str_replace('\\','/',dirname(dirname(__FILE__))).'/webengine.php')) {
	die('Failed to load WebEngine CMS.');
}

function loadCronFile($path) {
	include($path);
}

$realms = class_exists('NexoraRealm') && NexoraRealm::enabled() ? NexoraRealm::ids() : array(null);
foreach($realms as $realm) {
	try {
		if($realm !== null) NexoraRealm::selectPublic($realm, false);
		$cronList = getCronList();
		if(!is_array($cronList)) continue;

		foreach($cronList as $cron) {
			if((int)$cron['cron_status'] !== 1) continue;
			if(!nexoraCronIsDue($cron, $realm)) continue;

			$filePath = __PATH_CRON__.basename($cron['cron_file_run']);
			if(!is_file($filePath)) continue;
			try {
				loadCronFile($filePath);
			} catch(Throwable $ex) {
				@error_log('[Nexora cron]['.($realm === null ? 'default' : $realm).']['.basename($cron['cron_file_run']).'] '.$ex->getMessage());
			}
		}
	} catch(Throwable $ex) {
		@error_log('[Nexora cron]['.($realm === null ? 'default' : $realm).'] '.$ex->getMessage());
	}
}
