<?php

declare(strict_types=1);

namespace ShieldX\Support;

defined('ABSPATH') || exit;

final class RequestPath
{
    public static function decodeTwice(string $path): string
    {
        $decoded = $path;

        for ($i = 0; $i < 2; $i++) {
            $next = rawurldecode($decoded);
            if ($next === $decoded) {
                break;
            }
            $decoded = $next;
        }

        return $decoded;
    }

    public static function adminEndpointPath(string $endpoint): string
    {
        $endpoint = ltrim($endpoint, '/');
        $path = '';

        if (function_exists('admin_url') && function_exists('wp_parse_url')) {
            $parsed = wp_parse_url((string) admin_url($endpoint), PHP_URL_PATH);
            $path = is_string($parsed) ? $parsed : '';
        }

        if ($path === '') {
            $path = '/wp-admin/' . $endpoint;
        }

        return '/' . ltrim(strtolower(str_replace('\\', '/', self::decodeTwice($path))), '/');
    }
}
