<?php

declare(strict_types=1);

namespace Inpsyde\MultilingualPress\Module\Redirect\GeoLocation;

use Inpsyde\MultilingualPress\Framework\Http\Request;

class GeolocationFinder implements GeolocationFinderInterface
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var string
     */
    protected $geolocationServiceUrl;

    public function __construct(Request $request, string $geolocationServiceUrl)
    {
        $this->request = $request;
        $this->geolocationServiceUrl = $geolocationServiceUrl;
    }

    /**
     * @inheritDoc
     */
    public function find(): string
    {
        $ipAddress = $this->findIpAddress();
        if (empty($ipAddress)) {
            return '';
        }

        $url = "{$this->geolocationServiceUrl}?ip={$ipAddress}";

        $geolocationData = file_get_contents($url);

        if (!$geolocationData) {
            return '';
        }

        $geolocationData = json_decode($geolocationData);

        return $geolocationData->geoplugin_countryCode ?? '';
    }

    /**
     * Finds the IP address from the request.
     *
     * @return string The IP address.
     */
    protected function findIpAddress(): string
    {
        $remoteAddressHeader = $this->request->serverValue('REMOTE_ADDR') ?? '';
        $forwardedForHeader = $this->request->serverValue('HTTP_X_FORWARDED_FOR') ?? '';
        $clientIpHeader = $this->request->serverValue('HTTP_CLIENT_IP') ?? '';

        return $clientIpHeader ?? $forwardedForHeader ?? $remoteAddressHeader;
    }
}
