<?php
declare(strict_types=1);

namespace Ekesto\CacheWarmup\Settings\Actions;

use Ekesto\CacheWarmup\WarmupRuntime;
use Ekesto\CacheWarmup\Settings\AdminPage;
use Ekesto\CacheWarmup\Settings\Repository;
use Ekesto\CacheWarmup\Support\Access;
use Ekesto\CacheWarmup\Triggers;

/**
 * Handles nonce-protected admin bar actions.
 */
final class AdminBarAction
{
    private const NOTICE_QUERY_ARG = 'ekesto_cache_warmup_notice';
    private const NOTICE_FULL_QUEUED = 'full_queued';

    /**
     * Handle admin-post request for toggling warmup enabled/paused state.
     *
     * @return void
     */
    public static function handleToggleEnabled(): void
    {
        if (!Access::userCanManage()) {
            wp_die(esc_html__('Not allowed.', 'cache-autopilot'));
        }

        check_admin_referer('ekesto_cache_warmup_toggle_enabled');

        $targetEnabled = self::requestedEnabledState();
        if ($targetEnabled !== null) {
            Repository::setGeneralEnabled($targetEnabled);
        }

        self::redirectBack();
    }

    /**
     * Handle admin-post request for queueing a full warmup run.
     *
     * @return void
     */
    public static function handleRunFullWarmup(): void
    {
        if (!Access::userCanManage()) {
            wp_die(esc_html__('Not allowed.', 'cache-autopilot'));
        }

        check_admin_referer('ekesto_cache_warmup_run_full');

        $notice = null;
        if (Repository::isEnabled('general.enabled')) {
            if (Triggers::enqueueManualFullWarmup('manual:admin_bar')) {
                $notice = self::NOTICE_FULL_QUEUED;
            }
        }

        self::redirectBack($notice);
    }

    /**
     * Read the requested target enabled state from request input.
     *
     * @return bool|null Parsed boolean value, or null for invalid/missing input.
     */
    private static function requestedEnabledState(): ?bool
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only parsing after the admin-post handler has verified the action nonce.
        if (!isset($_GET['enabled'])) {
            return null;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only parsing after the admin-post handler has verified the action nonce.
        $raw = sanitize_text_field(wp_unslash((string) $_GET['enabled']));
        if ($raw === '1') {
            return true;
        }

        if ($raw === '0') {
            return false;
        }

        return null;
    }

    /**
     * Redirect to the previous page with a safe fallback to the plugin settings screen.
     *
     * @return void
     */
    private static function redirectBack(?string $notice = null): void
    {
        $fallback = AdminPage::settingsPageUrl();

        $referrer = wp_get_referer();
        if (!is_string($referrer) || $referrer === '') {
            $referrer = $fallback;
        }

        $target = wp_validate_redirect($referrer, $fallback);
        if (is_string($notice) && $notice !== '') {
            $target = add_query_arg(self::NOTICE_QUERY_ARG, $notice, $target);
        }

        wp_safe_redirect($target);
        exit;
    }
}
