<?php
/**
 * Manages WP-cron scheduling for automatic sync.
 *
 * @package SkyEmagSync
 */

namespace SkyEmagSync\Sync;

use SkyEmagSync\Options;

defined( 'ABSPATH' ) || exit;

class Scheduler {

    const CRON_HOOK = 'skyemag_cron_sync';

    public function register(): void {
        // Register custom intervals
        add_filter( 'cron_schedules', [ $this, 'add_intervals' ] );

        // Hook cron event to runner
        add_action( self::CRON_HOOK, [ Runner::class, 'run_cron' ] );
    }

    // ── Intervals ────────────────────────────────────────────────────────

    public function add_intervals( array $schedules ): array {
        $schedules['skyemag_15min'] = [
            'interval' => 15 * MINUTE_IN_SECONDS,
            'display'  => __( 'Every 15 Minutes', 'skyservers-product-sync-for-emag' ),
        ];
        $schedules['skyemag_30min'] = [
            'interval' => 30 * MINUTE_IN_SECONDS,
            'display'  => __( 'Every 30 Minutes', 'skyservers-product-sync-for-emag' ),
        ];
        $schedules['skyemag_3h'] = [
            'interval' => 3 * HOUR_IN_SECONDS,
            'display'  => __( 'Every 3 Hours', 'skyservers-product-sync-for-emag' ),
        ];
        $schedules['skyemag_6h'] = [
            'interval' => 6 * HOUR_IN_SECONDS,
            'display'  => __( 'Every 6 Hours', 'skyservers-product-sync-for-emag' ),
        ];
        $schedules['skyemag_12h'] = [
            'interval' => 12 * HOUR_IN_SECONDS,
            'display'  => __( 'Every 12 Hours', 'skyservers-product-sync-for-emag' ),
        ];
        return $schedules;
    }

    // ── Schedule management ──────────────────────────────────────────────

    /**
     * Schedule the cron event (idempotent – won't double-schedule).
     */
    public static function schedule(): void {
        if ( wp_next_scheduled( self::CRON_HOOK ) ) {
            return;
        }
        $interval = Options::SCHEDULE_INTERVALS[ Options::sync_schedule() ] ?? 'skyemag_30min';
        wp_schedule_event( time(), $interval, self::CRON_HOOK );
    }

    /**
     * Unschedule all cron events for this hook.
     */
    public static function unschedule(): void {
        $timestamp = wp_next_scheduled( self::CRON_HOOK );
        if ( $timestamp ) {
            wp_unschedule_event( $timestamp, self::CRON_HOOK );
        }
    }

    /**
     * Reschedule with the currently configured interval (called when frequency changes).
     */
    public static function reschedule(): void {
        self::unschedule();
        if ( Options::is_master_enabled() ) {
            self::schedule();
        }
    }
}
