<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_JOBS_VIEW);

$scheduledJobService = app(\MintyPHP\Service\Scheduler\ScheduledJobService::class);

$jobId = (int) ($id ?? 0);
$job = $jobId > 0 ? $scheduledJobService->find($jobId) : null;
if (!$job) {
    Flash::error(t('Scheduled job not found'), 'admin/scheduled-jobs', 'scheduled_job_not_found');
    Router::redirect('admin/scheduled-jobs');
}

$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$canManage = $authorizationService->authorize(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_JOBS_MANAGE, [
    'actor_user_id' => $currentUserId,
])->isAllowed();
$canRunNow = $authorizationService->authorize(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_JOBS_RUN_NOW, [
    'actor_user_id' => $currentUserId,
])->isAllowed();
$form = [
    'enabled' => (int) ($job['enabled'] ?? 0),
    'timezone' => (string) ($job['timezone'] ?? ''),
    'schedule_type' => (string) ($job['schedule_type'] ?? 'daily'),
    'schedule_interval' => (int) ($job['schedule_interval'] ?? 1),
    'schedule_time' => (string) ($job['schedule_time'] ?? ''),
    'schedule_weekdays' => $scheduledJobService->weekdaysFromCsv((string) ($job['schedule_weekdays_csv'] ?? '')),
    'catchup_once' => (int) ($job['catchup_once'] ?? 1),
];
$errorBag = formErrors();

if (requestInput()->method() === 'POST') {
    if (!$canManage) {
        Guard::deny();
    }

    if (!Session::checkCsrfToken()) {
        $errorBag->addGlobal(t('Form expired, please try again'));
    }

    if (!$errorBag->hasAny()) {
        $saved = $scheduledJobService->updateFromAdmin($jobId, requestInput()->bodyAll());
        if (!($saved['ok'] ?? false)) {
            $errorBag->merge((array) ($saved['errors'] ?? [t('Scheduled job could not be saved')]));
            $form = array_merge($form, (array) ($saved['form'] ?? []));
        } else {
            Flash::success(t('Scheduled job saved'), "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_saved');
            $job = $saved['job'] ?? $job;
            $form = [
                'enabled' => (int) ($job['enabled'] ?? 0),
                'timezone' => (string) ($job['timezone'] ?? ''),
                'schedule_type' => (string) ($job['schedule_type'] ?? 'daily'),
                'schedule_interval' => (int) ($job['schedule_interval'] ?? 1),
                'schedule_time' => (string) ($job['schedule_time'] ?? ''),
                'schedule_weekdays' => $scheduledJobService->weekdaysFromCsv((string) ($job['schedule_weekdays_csv'] ?? '')),
                'catchup_once' => (int) ($job['catchup_once'] ?? 1),
            ];
        }
    }
}

$scheduleSummary = $scheduledJobService->scheduleSummary($job ?? []);
$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();

Buffer::set('title', t('Edit scheduled job'));
Buffer::set('grid_lang', json_encode(gridLang(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
