<?php
	require_once __DIR__ . '/../main/app/config/app.php';
	require_once __DIR__ . '/../main/app/config/connect.php';
	require_once __DIR__ . '/../main/app/config/status.php';
	
	// Check APP_KEY (GET param or $argv)
	if (!isset($_GET['APP_KEY']) && !isset($argv[1])) {
		die('APP_KEY is required');
	}
	$appKey = $_GET['APP_KEY'] ?? $argv[1];
	if ($appKey !== APP_KEY) {
		die('Invalid APP_KEY');
	}

	$failedJob = $db->query("SELECT * FROM FailedJobs WHERE (lastRetryAt >= DATE_SUB(NOW(), INTERVAL 1 DAY) OR lastRetryAt IS NULL) AND attempts < maxAttempts AND isProcessing = '0' ORDER BY id ASC LIMIT 1 FOR UPDATE");
	$failedJob = $failedJob->fetch(\PDO::FETCH_ASSOC);

	if (!$failedJob) {
		die('No failed job found');
	}

	$jobName = $failedJob['name'];
	$payload = $failedJob['payload'];
		
	if ($payload === false) {
		die('Invalid payload received');
	}
	
	// Job name starts with Main, load the main app
	if (strpos($jobName, 'Main') === 0) {
		require_once __DIR__ . '/../main/vendor/autoload.php';
		require_once __DIR__ . '/../main/core/helper.php';
		
		// Initialize the worker
		$worker = new \Main\Core\Jobs\Worker();
	}
	
	// Job name starts with Dashboard, load the dashboard app
	if (strpos($jobName, 'Dashboard') === 0) {
		require_once __DIR__ . '/../dashboard/vendor/autoload.php';
		require_once __DIR__ . '/../dashboard/core/helper.php';
		
		// Initialize
		global $settings, $readSettings, $modules, $readModules;
		$settings = db()->query("SELECT * FROM Settings");
		foreach ($settings as $setting) {
			$readSettings[$setting["name"]] = $setting["value"];
		}
		$modules = db()->query("SELECT * FROM Modules");
		$readModules = $modules->fetchAll();
		
		// Initialize the worker
		$worker = new \Dashboard\Core\Jobs\Worker();
	}
	
	// Job name starts with API, load the api app
	if (strpos($jobName, 'Api') === 0) {
		require_once __DIR__ . '/../api/vendor/autoload.php';
		require_once __DIR__ . '/../api/core/helper.php';
		
		// Initialize
		global $settings, $readSettings, $modules, $readModules;
		$settings = $db->query("SELECT * FROM Settings");
		foreach ($settings as $setting) {
			$readSettings[$setting["name"]] = $setting["value"];
		}
		$modules = $db->query("SELECT * FROM Modules");
		$readModules = $modules->fetchAll();
		
		// Initialize the worker
		$worker = new \Api\Core\Jobs\Worker();
	}
	
	if (!isset($worker)) {
		die('Worker: Worker not initialized!');
	}
	
	if (settings("timezone") != null) {
		date_default_timezone_set(settings("timezone"));
	}
	
	$success = $worker->processFailedJob($failedJob);
	
	if (!$success) {
		die('Failed job processing failed');
	}
	
	die('Failed job processed successfully');
