<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_Exchanger_Cron {

    public static function register() {
        add_action('aieo_exchanger_build_feeds_tick', array(__CLASS__, 'build_feeds_tick'));
        add_action('aieo_exchanger_run_imports_tick', array(__CLASS__, 'run_imports_tick'));
        add_action('aieo_exchanger_run_import_now',   array(__CLASS__, 'run_import_now'), 10, 1);
        add_action('aieo_exchanger_prune_runlog',     array(__CLASS__, 'prune_runlog'));

        if (!wp_next_scheduled('aieo_exchanger_build_feeds_tick')) {
            wp_schedule_event(time() + 60, 'hourly', 'aieo_exchanger_build_feeds_tick');
        }
        if (!wp_next_scheduled('aieo_exchanger_run_imports_tick')) {
            wp_schedule_event(time() + 90, 'hourly', 'aieo_exchanger_run_imports_tick');
        }
        if (!wp_next_scheduled('aieo_exchanger_prune_runlog')) {
            wp_schedule_event(time() + 120, 'daily', 'aieo_exchanger_prune_runlog');
        }
    }

    public static function build_feeds_tick() {
        foreach (AIEO_Exchanger_Feeds::list_all() as $feed) {
            if (empty($feed['enabled']) || empty($feed['schedule_cron'])) { continue; }
            if (!self::is_due($feed['schedule_cron'], $feed['last_built_at'])) { continue; }

            try {
                $r = AIEO_Exchanger_Feed_Builder::build((int) $feed['id']);
                if ($r['ok']) {
                    AIEO_Exchanger_Rest::notify_targets(AIEO_Exchanger_Feeds::get((int) $feed['id']));
                }
            } catch (\Throwable $e) {
                AIEO_Exchanger_Run_Log::record('source', (int) $feed['id'], 0, 0, 0, 0, 0,
                    array(array('phase' => 'cron_build', 'error' => $e->getMessage())));
            }
        }
    }

    public static function run_imports_tick() {
        foreach (AIEO_Exchanger_Imports::list_all() as $job) {
            if (empty($job['enabled']) || empty($job['schedule_cron'])) { continue; }
            if (!self::is_due($job['schedule_cron'], $job['last_run_at'])) { continue; }
            self::run_import_now((int) $job['id']);
        }
    }

    public static function run_import_now($job_id) {
        try {
            AIEO_Exchanger_Puller::run_full((int) $job_id);
        } catch (\Throwable $e) {
            AIEO_Exchanger_Run_Log::record('target', (int) $job_id, 0, 0, 0, 0, 0,
                array(array('phase' => 'cron_run', 'error' => $e->getMessage())));
        }
    }

    public static function prune_runlog() {
        $retention = (int) apply_filters('aieo_exchanger_runlog_retention_days', 30);
        AIEO_Exchanger_Run_Log::prune($retention);
    }

    
    private static function is_due($cadence, $last_run) {
        $intervals = array(
            'hourly'     => HOUR_IN_SECONDS,
            'twicedaily' => 12 * HOUR_IN_SECONDS,
            'daily'      => DAY_IN_SECONDS,
            'weekly'     => WEEK_IN_SECONDS,
        );
        if (!isset($intervals[$cadence])) { return false; }
        if (!$last_run) { return true; }
        $last_ts = strtotime($last_run . ' UTC');
        return $last_ts <= 0 || (time() - $last_ts) >= $intervals[$cadence];
    }
}
