<?php

use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE);

if (strtoupper((string) (requestInput()->method())) !== 'POST') {
    Router::redirect('admin/scheduled-jobs');
}
$errorBag = formErrors();
if (!Session::checkCsrfToken()) {
    $errorBag->addGlobal(t('Form expired, please try again'));
    flashFormErrors($errorBag, 'admin/scheduled-jobs', 'scheduled_job_purge');
    Router::redirect('admin/scheduled-jobs');
}

$deleted = app(\MintyPHP\Service\Scheduler\ScheduledJobService::class)->purgeRunsExpired();
Flash::success(sprintf(t('%d scheduler run logs purged'), $deleted), 'admin/scheduled-jobs', 'scheduled_job_runs_purged');
Router::redirect('admin/scheduled-jobs');
