<?php
declare(strict_types=1);

namespace Ekesto\CacheWarmup\Settings\Actions;

use Ekesto\CacheWarmup\Settings\AdminPage;
use Ekesto\CacheWarmup\Sitemap;
use Ekesto\CacheWarmup\Support\Access;

/**
 * Handles nonce-protected asynchronous sitemap refresh requests.
 */
final class SitemapRefreshAction
{
    /** Admin-post action and nonce action for manual sitemap refresh requests. */
    public const ACTION = 'ekesto_cache_warmup_refresh_sitemap';

    /** Query argument used by global operational notices. */
    private const NOTICE_QUERY_ARG = 'ekesto_cache_warmup_notice';

    /** Notice value shown after a manual sitemap refresh was requested. */
    private const NOTICE_REFRESH_REQUESTED = 'sitemap_refresh_requested';

    /**
     * Schedule an immediately eligible sitemap refresh and return to the referring admin screen.
     *
     * @return void
     */
    public static function handleAdminPost(): void
    {
        if (!Access::userCanManage()) {
            wp_die(esc_html__('Not allowed.', 'cache-autopilot'));
        }

        check_admin_referer(self::ACTION);

        Sitemap::requestImmediateMembershipRebuild([
            'source' => 'manual_retry',
            'hook' => 'admin_post',
        ]);

        self::redirectBack();
    }

    /**
     * Redirect to the previous page with a safe settings-page fallback.
     *
     * @return void
     */
    private static function redirectBack(): void
    {
        $fallback = AdminPage::settingsPageUrl(['tab' => 'warmup']);
        $referrer = wp_get_referer();
        if (!is_string($referrer) || $referrer === '') {
            $referrer = $fallback;
        }

        $target = wp_validate_redirect($referrer, $fallback);
        $target = add_query_arg(self::NOTICE_QUERY_ARG, self::NOTICE_REFRESH_REQUESTED, $target);

        wp_safe_redirect($target);
        exit;
    }
}
