<?php

namespace Openguru\OpenCartFramework\Http;

use Openguru\OpenCartFramework\Support\Arr;
use Openguru\OpenCartFramework\Support\Utils;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

final class Request extends SymfonyRequest
{
    public function json(string $key = null, $default = null)
    {
        $content = $this->getContent();

        if (! $content) {
            return $default;
        }

        $decoded = Utils::safeJsonDecode($content);

        if ($key === null) {
            return $decoded;
        }

        return Arr::get($decoded, $key, $default);
    }

    public function get(string $key = null, $default = null)
    {
        return $this->query->get($key, $default);
    }

    public function getClientIp(): ?string
    {
        return $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? null;
    }

    public function getUserAgent(): ?string
    {
        return $_SERVER['HTTP_USER_AGENT'] ?? null;
    }

    public function header(string $key, ?string $default = null): ?string
    {
        return $this->headers->get($key, $default);
    }

    public function getApiKey(): ?string
    {
        $header =
            $_SERVER['HTTP_X_API_KEY']
            ?? $this->header('X-API-KEY')
            ?? null;

        return $header ? trim($header) : null;
    }
}
