<?php

declare(strict_types=1);

if (! defined('DAY_IN_SECONDS')) {
    define('DAY_IN_SECONDS', 86400);
}

if (! function_exists('__')) {
    function __(string $message): string
    {
        return $message;
    }
}

/** @var array<int, array{timestamp: int, recurrence: string, hook: string, interval: int}> $GLOBALS['amgScheduledEvents'] */
$GLOBALS['amgScheduledEvents'] = [];

/** @var int $GLOBALS['amgCurrentInterval'] */
$GLOBALS['amgCurrentInterval'] = 300;

if (! function_exists('wp_schedule_event')) {
    function wp_schedule_event(int $timestamp, string $recurrence, string $hook, array $args = [], bool $wpError = false): bool
    {
        $GLOBALS['amgScheduledEvents'][] = [
            'timestamp' => $timestamp,
            'recurrence' => $recurrence,
            'hook' => $hook,
            'interval' => $GLOBALS['amgCurrentInterval'],
        ];

        return true;
    }
}

if (! function_exists('wp_next_scheduled')) {
    function wp_next_scheduled(string $hook, array $args = [], bool $skipPast = false): int|false
    {
        foreach ($GLOBALS['amgScheduledEvents'] as $index => $event) {
            if ($event['hook'] === $hook) {
                unset($GLOBALS['amgScheduledEvents'][$index]);
                $GLOBALS['amgScheduledEvents'] = array_values($GLOBALS['amgScheduledEvents']);

                return $event['timestamp'];
            }
        }

        return false;
    }
}

if (! function_exists('wp_unschedule_event')) {
    function wp_unschedule_event(int $timestamp, string $hook, array $args = []): bool
    {
        $GLOBALS['amgScheduledEvents'] = array_values(array_filter(
            $GLOBALS['amgScheduledEvents'],
            fn (array $event) => ! ($event['hook'] === $hook && $event['timestamp'] === $timestamp)
        ));

        return true;
    }
}

if (! function_exists('wp_clear_scheduled_hook')) {
    function wp_clear_scheduled_hook(string $hook, array $args = []): void
    {
        $GLOBALS['amgScheduledEvents'] = array_values(array_filter(
            $GLOBALS['amgScheduledEvents'],
            fn (array $event) => $event['hook'] !== $hook
        ));
    }
}

if (! function_exists('wp_get_scheduled_event')) {
    function wp_get_scheduled_event(string $hook, array $args = [], bool $skipPast = true): object|false
    {
        foreach ($GLOBALS['amgScheduledEvents'] as $event) {
            if ($event['hook'] === $hook) {
                return (object) [
                    'timestamp' => $event['timestamp'],
                    'schedule' => $event['recurrence'],
                    'interval' => $event['interval'],
                    'hook' => $event['hook'],
                ];
            }
        }

        return false;
    }
}

if (! function_exists('add_filter')) {
    function add_filter(string $hook, callable $callback): void
    {
    }
}

if (! function_exists('add_action')) {
    function add_action(string $hook, callable $callback): void
    {
    }
}
