<?php

use MintyPHP\Buffer;
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_VIEW);

$factory = new SchedulerServicesFactory();
$scheduledJobService = $factory->createScheduledJobService();

$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');
}

$canManage = can('jobs.manage');
$canRunNow = can('jobs.run_now');
$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),
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$canManage) {
        Flash::error(t('Permission denied'), "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_manage_denied');
        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_edit_csrf');
        Router::redirect("admin/scheduled-jobs/edit/$jobId");
    }

    $saved = $scheduledJobService->updateFromAdmin($jobId, $_POST);
    if (!($saved['ok'] ?? false)) {
        foreach ((array) ($saved['errors'] ?? [t('Scheduled job could not be saved')]) as $error) {
            Flash::error((string) $error, "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_save_failed');
        }
        $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 ?? []);

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