<?php

namespace Sibs\Stargate\Utils;

defined('ABSPATH') || exit;

class UrlUtils
{
    /**
     * Get Checkout URL.
     *
     * @return string
     */
    public static function get_checkout_url()
    {
        return wc_get_checkout_url();
    }

    /**
     * Get $_REQUEST value.
     *
     * @param string $key     key
     * @param string $default default
     *
     * @return string
     */
    public static function get_request_value($key, $default = false)
    {
        if (isset($_REQUEST[$key])) {
            return sanitize_text_field(wp_unslash($_REQUEST[$key]));
        }

        return $default;
    }

    /**
     * Get Order from Request.
     */
    public static function get_order_from_request(): ?\WC_Order
    {
        // 1. Tenta pelo endpoint (funciona com config dinâmica do Woo)
        $order_id = absint(get_query_var('order-received'));

        // 2. Fallback via GET (compatibilidade)
        if (!$order_id && isset($_GET['order-received'])) {
            $order_id = absint($_GET['order-received']);
        }

        // 3. Fallback via order key (Blocks + casos modernos)
        if (!$order_id && !empty($_GET['key'])) {
            $order_id = wc_get_order_id_by_order_key(wc_clean($_GET['key']));
        }

        if (!$order_id) {
            return null;
        }

        $wc_order = wc_get_order($order_id);

        if (!$wc_order instanceof \WC_Order) {
            return null;
        }

        // 4. Segurança: validar key se existir
        if (!empty($_GET['key'])) {
            $request_key = wc_clean($_GET['key']);
            if ($wc_order->get_order_key() !== $request_key) {
                return null;
            }
        }

        return $wc_order;
    }
}
