<?php

/**
 * See http://www.geoplugin.com/webservices/php for more specific details of this free service
 */
class PolylangGeoLocator extends PolylangGeoLocatorHandler
{
    /**
     * @var array
     */
    protected $data = array();

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

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

    /**
     * @return string
     */
    public function getCity()
    {
        return $this->getValue('geoplugin_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();
        $url = 'http://www.geoplugin.net/php.gp?ip=' . $ip;
        $content = $this->polylang->getTools()->request($url);
        if (!empty($content)) {
            $this->data[$ip] = unserialize($content);
        }
        return $this->data[$ip];
    }

}
