<?php

use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Scheduler\SchedulerServicesFactory;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requirePermission(PermissionService::JOBS_RUN_NOW);

$jobId = (int) ($id ?? 0);
if (strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    Router::redirect("admin/scheduled-jobs/edit/$jobId");
}
if (!Session::checkCsrfToken()) {
    Flash::error(t('Form expired, please try again'), "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_run_csrf');
    Router::redirect("admin/scheduled-jobs/edit/$jobId");
}

$factory = new SchedulerServicesFactory();
$result = $factory->createSchedulerRunService()->runJobNow($jobId, (int) ($_SESSION['user']['id'] ?? 0));
if (!($result['ok'] ?? false)) {
    $error = (string) ($result['error'] ?? '');
    if ($error === 'lock_not_acquired') {
        Flash::error(t('Scheduler is already running'), "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_run_locked');
    } elseif ($error === 'job_not_found') {
        Flash::error(t('Scheduled job not found'), 'admin/scheduled-jobs', 'scheduled_job_run_not_found');
    } else {
        Flash::error(t('Scheduled job run failed'), "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_run_failed');
    }
    Router::redirect($error === 'job_not_found' ? 'admin/scheduled-jobs' : "admin/scheduled-jobs/edit/$jobId");
}

$status = strtolower(trim((string) ($result['status'] ?? '')));
if ($status === 'skipped') {
    Flash::success(t('Scheduled job run skipped'), "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_run_skipped');
} else {
    Flash::success(t('Scheduled job run completed'), "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_run_success');
}
Router::redirect("admin/scheduled-jobs/edit/$jobId");
