<?php
namespace GriffinForms\Includes\Schedulers;

use GriffinForms\Includes\Pipelines\JobWorker;
use GriffinForms\Traits\Singleton;

class JobScheduler
{
    use Singleton;

    /**
     * Ensure the custom interval is always registered early, even if register()
     * has not yet been called (e.g., during WP-Cron reschedule checks).
     */
    public static function ensureIntervalRegistered(): void
    {
        add_filter('cron_schedules', [__CLASS__, 'registerIntervalStatic']);
    }

    public function register(): void
    {
        add_filter('cron_schedules', [ $this, 'registerInterval' ]);
        add_action('griffinforms_process_jobs', [ $this, 'processQueue' ]);

        if (!wp_next_scheduled('griffinforms_process_jobs')) {
            wp_schedule_event(time() + 60, 'griffinforms_every_minute', 'griffinforms_process_jobs');
        }
    }

    public function registerInterval($schedules)
    {
        if (!isset($schedules['griffinforms_every_minute'])) {
            $schedules['griffinforms_every_minute'] = [
                'interval' => 60,
                'display'  => __('Every Minute (GriffinForms)', 'griffinforms-form-builder'),
            ];
        }

        return $schedules;
    }

    public static function registerIntervalStatic($schedules)
    {
        if (!isset($schedules['griffinforms_every_minute'])) {
            $schedules['griffinforms_every_minute'] = [
                'interval' => 60,
                'display'  => __('Every Minute (GriffinForms)', 'griffinforms-form-builder'),
            ];
        }

        return $schedules;
    }

    public function processQueue(): void
    {
        $worker = new JobWorker();
        $worker->process();
    }
}

// Register the interval as early as possible for cron reschedules.
JobScheduler::ensureIntervalRegistered();
