<?php
namespace WebshoptigerCatalogSync;

defined( 'ABSPATH' ) || exit;

class Scheduler {

    const HOOK          = 'webshoptigercatalogsync_run';           // Global sync hook
    const HOOK_PER_SITE = 'webshoptigercatalogsync_run_per_site';  // Per-site schedule checker hook

    public static function init(): void {
        add_filter( 'cron_schedules', [ __CLASS__, 'add_schedules' ] );
        add_action( self::HOOK,          [ 'WebshoptigerCatalogSync\\Sync', 'run_all' ] );
        add_action( self::HOOK_PER_SITE, [ __CLASS__, 'run_per_site_schedules' ] );
    }

    public static function add_schedules( array $schedules ): array {
        $schedules['fifteen_min'] = [
            'interval' => 15 * MINUTE_IN_SECONDS,
            'display'  => 'Every 15 minutes',
        ];
        $schedules['thirtymin'] = [
            'interval' => 30 * MINUTE_IN_SECONDS,
            'display'  => 'Every 30 minutes',
        ];
        return $schedules;
    }

    public static function schedule(): void {
        if ( ! Settings::is_source_site() ) return;

        if ( ! wp_next_scheduled( self::HOOK ) ) {
            $interval     = Settings::get( 'interval', 'hourly' );
            $schedules    = wp_get_schedules();
            $interval_sec = isset( $schedules[ $interval ] ) ? (int) $schedules[ $interval ]['interval'] : HOUR_IN_SECONDS;
            // Schedule first run after one full interval — not immediately
            wp_schedule_event( time() + $interval_sec, $interval, self::HOOK );
        }

        // Per-site schedule checker — also delay first run
        if ( ! wp_next_scheduled( self::HOOK_PER_SITE ) ) {
            wp_schedule_event( time() + 15 * MINUTE_IN_SECONDS, 'fifteen_min', self::HOOK_PER_SITE );
        }
    }

    public static function unschedule(): void {
        foreach ( [ self::HOOK, self::HOOK_PER_SITE ] as $hook ) {
            $timestamp = wp_next_scheduled( $hook );
            if ( $timestamp ) {
                wp_unschedule_event( $timestamp, $hook );
            }
        }
    }

    public static function reschedule(): void {
        self::unschedule();
        self::schedule();
    }

    /**
     * Called every 15 minutes — checks which sites have a per-site
     * schedule set and are due for a sync.
     */
    public static function run_per_site_schedules(): void {
        if ( ! Settings::is_source_site() ) return;

        $due_sites = SiteManager::get_sites_due_for_sync();
        foreach ( $due_sites as $site ) {
            Sync::sync_site( (int) $site['id'] );
            SiteManager::update_next_sync( (int) $site['id'], $site['sync_interval'] );
        }
    }

    public static function get_next_run(): string {
        $ts = wp_next_scheduled( self::HOOK );
        if ( ! $ts ) return 'Not scheduled';
        return date_i18n( 'd-m-Y H:i:s', $ts + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
    }

    public static function get_next_run_per_site( array $site ): string {
        if ( ( $site['sync_interval'] ?? 'global' ) === 'global' ) {
            return 'Uses global schedule';
        }
        if ( empty( $site['next_sync_at'] ) ) {
            return 'On next check (within 15 min)';
        }
        return date_i18n( 'd-m-Y H:i:s', strtotime( $site['next_sync_at'] ) + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
    }
}
