<?php

namespace SEOAIC\cron;

class MissedScheduleFallback
{
    private const FALLBACK_MULTIPLIER = 1.1;
    private bool $shutdown_scheduled = false;

    protected \SEOAIC\SEOAIC $seoiac;

    public function __construct(\SEOAIC\SEOAIC $seoiac)
    {
        $this->seoiac = $seoiac;
        add_action('admin_init', [$this, 'maybe_trigger']);
        //add_action('send_headers', [$this, 'maybe_trigger'], 1);
        add_action('init', [$this, 'maybe_trigger'], 1);
    }

    public function maybe_trigger(): void
    {
        if ($this->shutdown_scheduled) {
            return;
        }

        $opts     = get_option('seoaic_options');
        $opts     = is_array($opts) ? $opts : [];
        $last_run = (int) ($opts[MissedScheduleCron::LAST_RUN_OPTION] ?? 0);

        $freq = (int) apply_filters('seoaic_missed_schedule_frequency', MissedScheduleCron::DEFAULT_FREQ);
        $freq = $freq > 0 ? $freq : MissedScheduleCron::DEFAULT_FREQ;

        if ($last_run < (time() - (int) round(self::FALLBACK_MULTIPLIER * $freq))) {
            //nocache_headers();

            if (!has_action('shutdown', [$this, 'shutdown_run'])) {
                add_action('shutdown', [$this, 'shutdown_run']);
            }

            $this->shutdown_scheduled = true;
            //error_log('SEOAIC Fallback: schedule shutdown run');
        }
    }

    public function shutdown_run(): void
    {
        try {
            if (!isset($this->seoiac->missed_schedule_cron)) {
                error_log('SEOAIC Fallback: cron instance missing');
                return;
            }
            $res = $this->seoiac->missed_schedule_cron->run_once(0);
            //error_log('SEOAIC Fallback: shutdown run count=' . ($res['count'] ?? 0));
        } catch (\Throwable $e) {
            error_log('SEOAIC Fallback: error ' . $e->getMessage());
        }
    }
}