<?php

/**
 * See https://ipinfo.io/developers
 */

use ipinfo\ipinfo\IPinfo;
use \ipinfo\ipinfo\IPinfoException;

class PolylangGeoLocatorIPInfo extends PolylangGeoLocatorHandler
{
    /** @var array */
    protected $data = array();
    /** @var string */
    protected $accessToken;

    public function __construct(Polylang $polylang, $config = array())
    {
        parent:: __construct($polylang, $config);
        $this->accessToken = $this->modx->getOption('polylang_geo_locator_ipinfo_access_token', null, '');
    }

    /**
     * @return string
     */
    public function getCountryCode()
    {
        return $this->getValue('country');
    }

    /**
     * @return string
     */
    public function getRegion()
    {
        return $this->getValue('region');
    }

    /**
     * @return string
     */
    public function getCity()
    {
        return $this->getValue('city');
    }

    /**
     * @param string $key
     *
     * @return string
     */
    protected function getValue($key)
    {
        $value = '';
        $data = $this->loadData();
        if (!empty($data) && is_array($data) && isset($data[$key])) {
            $value = $data[$key];
        }
        return $value;
    }

    /**
     * @return array|null
     */
    protected function loadData()
    {
        $ip = $this->getIp();
        if (empty($ip)) return null;
        if (isset($this->data[$ip])) return $this->data[$ip];
        $this->data[$ip] = array();
        try {
            $client = new IPinfo($this->accessToken);
            $details = $client->getDetails($ip);
            $this->data[$ip] = array(
                'country' => $details->country,
                'region' => $details->region,
                'city' => $details->city,
            );
        } catch (IPinfoException $e) {
            $this->modx->log(modX::LOG_LEVEL_ERROR, '[PolylangGeoLocatorIPInfo] ' . $e->getMessage());
            return null;
        }
        return $this->data[$ip];
    }

}
