<?php

namespace routes;

use classes\authentication;
use objects\logs_o;
use traits\route_t;

class cronRoute
{
    use route_t;

    public function run(): void
    {
        $this->post('/superuser/cron', function () {
            // Get the post data
            global $response;
            // Make sure the user has the SUPERUSER_RUN_CRON permission
            if (!$this->requirePermission('SUPERUSER_RUN_CRON')) {
                $response->error('Permission denied', 403);
            }
            // Get the user object
            $user = (new authentication())->get_user();
            // Get the post data
            $data = json_decode(file_get_contents('php://input'), true);
            // Check if a specific cron job is requested
            if (isset($data['job'])) {
                // Check if the cron job exists
                if (!file_exists(WD . '/cron/' . $data['job'] . '.php')) {
                    $response->error('Cron job not found', 404);
                }
                // Include the cron job
                require_once WD . '/cron/' . $data['job'] . '.php';
                // Log the incident
                (new logs_o())->add('cron', 'global', 1, $user->id, 'CRON_JOB_RUN', 'Ran cron job: ' . $data['job']);
                $response->success('Cron job ran successfully');
            }
            // If no specific cron job is requested, run all cron jobs (through the cron.php file)
            require_once WD . '/cron/Cron.php';
            // Log the incident
            (new logs_o())->add('cron', 'global', 1, $user->id, 'CRON_RUN', 'Ran all cron jobs');
            $response->success([
                'message' => 'All cron jobs ran successfully',
                'data' => $response_cron ?? []
            ]);
        },
            [
                'SUPERUSER_RUN_CRON' => 'Run cron jobs'
            ]
        );
    }
}