<?php


class ISTKR_IPdetails
{
    public $country_name;
    public $country_flag;

    public function __construct($raw_details)
    {
        foreach ($raw_details as $property => $value) {
            $this->$property = $value;
        }
    }
}


class ISTKR_IPinfo
{
    const API_URL = 'https://ipinfo.io';
    const STATUS_CODE_QUOTA_EXCEEDED = 429;
    const COUNTRIES_FILE = __DIR__ . '/src/countries.json';
    const COUNTRIES_FLAGS_FILE = __DIR__ . '/src/flags.json';

    public $access_token;
    public $countries;
    public $countries_flags;

    public function __construct($access_token)
    {
        $this->access_token = $access_token;
        $this->countries = $this->readJSONFile(self::COUNTRIES_FILE);
        $this->countries_flags = $this->readJSONFile(self::COUNTRIES_FLAGS_FILE);
    }

    private function buildHeaders()
    {
        $headers = [
            'user-agent' => 'IPinfoClient/PHP/3.1.2',
            'accept' => 'application/json',
            'content-type' => 'application/json',
        ];

        if ($this->access_token) {
            $headers['authorization'] = "Bearer {$this->access_token}";
        }

        return $headers;
    }

    private function readJSONFile($file)
    {
        return json_decode(file_get_contents($file), true);
    }

    private function getRequestDetails($ip_address)
    {
        $url = self::API_URL;
        if ($ip_address) {
            $url .= "/$ip_address";
        }

        try {
            $response = wp_remote_get($url, ['headers' => $this->buildHeaders()]);
        } catch (Exception $e) {
            return [];
        }

        return (array) json_decode(wp_remote_retrieve_body($response));
    }

    public function getDetails($ip_address)
    {
        $response_details = $this->getRequestDetails($ip_address);

        $country = $response_details['country'] ?? null;
        $details['country_name'] = $this->countries[$country] ?? null;
        $details['country_flag'] = $this->countries_flags[$country] ?? null;

        return new ISTKR_IPdetails($details);
    }
}
