<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Operations;

defined('ABSPATH') || exit;

class OperationalMonitor
{
    public const HEARTBEAT_HOOK = 'apd_operational_heartbeat';
    public const HEARTBEAT_OPTION = 'apd_operational_heartbeat_at';
    public const CRON_INTERVAL = 'apd_five_minutes';

    public function register() : void
    {
        add_filter('cron_schedules', [$this, 'cronSchedules']);
        add_action(self::HEARTBEAT_HOOK, [$this, 'heartbeat']);
        add_action('init', [$this, 'schedule'], 4);
    }

    public function cronSchedules(array $schedules) : array
    {
        $schedules[self::CRON_INTERVAL] = [
            'interval' => 5 * MINUTE_IN_SECONDS,
            'display' => __('Every five minutes', 'asuka-product-designer'),
        ];

        return $schedules;
    }

    public function schedule() : void
    {
        if (is_multisite() && ! is_main_site()) {
            return;
        }

        if (! wp_next_scheduled(self::HEARTBEAT_HOOK)) {
            wp_schedule_event(time() + MINUTE_IN_SECONDS, self::CRON_INTERVAL, self::HEARTBEAT_HOOK);
        }
    }

    public function heartbeat() : void
    {
        $timestamp = time();
        if (is_multisite()) {
            update_site_option(self::HEARTBEAT_OPTION, $timestamp);
            return;
        }

        update_option(self::HEARTBEAT_OPTION, $timestamp, false);
    }

    public static function lastHeartbeat() : int
    {
        $value = is_multisite()
            ? get_site_option(self::HEARTBEAT_OPTION, 0)
            : get_option(self::HEARTBEAT_OPTION, 0);

        return max(0, (int) $value);
    }
}
