<?php
declare(strict_types=1);

namespace Help4BuilderSuite\Support;

if (! defined('ABSPATH')) {
    exit;
}

final class AdminRequest
{
    public static function queryText(string $key, string $default = ''): string
    {
        $value = self::queryValue($key);
        if ($value === null) {
            return $default;
        }

        return sanitize_text_field(self::scalarString($value));
    }

    public static function queryKey(string $key, string $default = ''): string
    {
        $value = self::queryValue($key);
        if ($value === null) {
            return $default;
        }

        return sanitize_key(self::scalarString($value));
    }

    public static function queryAbsInt(string $key, int $default = 0): int
    {
        $value = self::queryValue($key);
        if ($value === null) {
            return $default;
        }

        return absint(self::scalarString($value));
    }

    public static function queryFloat(string $key, float $default = 0.0): float
    {
        $value = self::queryValue($key);
        if ($value === null) {
            return $default;
        }

        return (float) self::scalarString($value);
    }

    public static function queryHasValue(string $key): bool
    {
        $value = self::queryValue($key);

        return $value !== null && self::scalarString($value) !== '';
    }

    /**
     * @return array<string, mixed>
     */
    public static function queryArray(): array
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only query-string accessor; callers verify nonces before mutations.
        if (! isset($_GET) || ! is_array($_GET)) {
            return [];
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only query-string accessor; callers verify nonces before mutations.
        $query = map_deep(wp_unslash($_GET), 'sanitize_text_field');

        return is_array($query) ? $query : [];
    }

    private static function queryValue(string $key)
    {
        $query = self::queryArray();
        if (! array_key_exists($key, $query)) {
            return null;
        }

        return self::scalarString($query[$key]);
    }

    private static function scalarString($value): string
    {
        if (is_scalar($value)) {
            return (string) $value;
        }

        return '';
    }
}
