<?php

/**
 * Cron Jobs Handler
 *
 * @package _121Digital\Connect
 */

namespace _121Digital\Connect\Core;

use _121Digital\Connect\Registration\RegistrationManager;

/**
 * Cron Class
 *
 * Handles scheduled tasks and cron jobs
 */
class Cron
{
    /**
     * Registration Manager instance
     *
     * @var RegistrationManager
     */
    private RegistrationManager $registrationManager;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->registrationManager = new RegistrationManager();
    }

    /**
     * Register cron hooks
     *
     * @return void
     */
    public function register(): void
    {
        add_filter('cron_schedules', [$this, 'addCustomInterval']);
        add_action('sc_cron_hook', [$this, 'runCronTask']);

        if (!wp_next_scheduled('sc_cron_hook')) {
            wp_schedule_event(time(), 'every_5_minutes', 'sc_cron_hook');
        }
    }

    /**
     * Add custom cron interval
     *
     * @param array $schedules
     * @return array
     */
    public function addCustomInterval(array $schedules): array
    {
        $schedules['every_5_minutes'] = [
            'interval' => 300, // 300 seconds = 5 minutes
            'display' => __('Every 5 Minutes'),
        ];
        return $schedules;
    }

    /**
     * Run cron task
     *
     * @return void
     */
    public function runCronTask(): void
    {
        $result = $this->registrationManager->verify();

        update_option('sc_last_cron_execution', current_time('mysql'));

        if ($result['success']) {
            update_option('sc_site_registered', true);
        } else {
            update_option('sc_site_registered', false);
            if (isset($result['reason'])) {
                update_option('sc_last_backend_error', $result['reason']);
            } elseif (isset($result['message'])) {
                update_option('sc_last_backend_error', $result['message']);
            }
        }
    }

    /**
     * Clear scheduled cron jobs
     *
     * @return void
     */
    public static function clearScheduledJobs(): void
    {
        wp_clear_scheduled_hook('sc_cron_hook');
    }
}
