<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Models\CronModel;
use App\Services\CronService;

final class CronController extends Controller
{
    public function index(): void
    {
        require_permission('cron.view_logs');

        $model = new CronModel();

        $this->view('admin/cron/index', [
            'rows' => $model->logs(),
        ]);
    }

    public function runNow(): void
    {
        require_permission('cron.run_jobs');

        if (!$this->isPost()) {
            redirect('admin/cron');
        }

        csrf_check();

        $job = trim((string) ($_POST['job_key'] ?? 'all'));

        match ($job) {
            'submission_deadline_reminders' => CronService::runSubmissionDeadlineReminders(true),
            'review_due_reminders' => CronService::runReviewDueReminders(true),
            'decision_pending_reminders' => CronService::runDecisionPendingReminders(true),
            'camera_ready_reminders' => CronService::runCameraReadyReminders(true),
            default => CronService::runAll(true),
        };

        flash('success', 'Cron executed.');
        redirect('admin/cron');
    }
}
