<?php

interface PolylangGeoLocatorInterface
{

    /**
     * @return string
     */
    public function getCountryCode();

    /**
     * @return string
     */
    public function getRegion();

    /**
     * @return string
     */
    public function getCity();

    /**
     * @param string $method
     * @return string
     */
    public function execute($method);

    /**
     * @return string
     */
    public function getIp();

    /**
     * @param string $ip
     */
    public function setIp(string $ip);
}

abstract class PolylangGeoLocatorHandler implements PolylangGeoLocatorInterface
{
    /** @var modX */
    public $modx = null;
    /** @var Polylang */
    public $polylang = null;
    /** @var array */
    public $config = array();
    /** @var string $ip */
    protected $ip;

    public function __construct(Polylang $polylang, $config = array())
    {
        $this->polylang = $polylang;
        $this->modx = $polylang->modx;
        $this->config = array_merge($this->config, $config);
    }

    /**
     * @param string $method
     * @param bool $prepare
     *
     * @return string|false
     */
    public function execute($method, $prepare = false)
    {
        if ($prepare) {
            $method = $this->prepareMethodName($method);
        }
        if (method_exists($this, $method)) {
            return $this->$method();
        } else {
            $this->modx->log(modX::LOG_LEVEL_ERROR, "Call to undefined function {$method}");
            return false;
        }
    }

    /**
     * @param string $method
     *
     * @return string
     */
    public function prepareMethodName($method)
    {
        $result = '';
        $items = explode('_', $method);
        foreach ($items as $item) {
            $result .= ucfirst($item);
        }
        return 'get' . $result;
    }

    /**
     * @return string
     */
    public function getIp()
    {
        return $this->ip;
    }

    /**
     * @param string $ip
     */
    public function setIp(string $ip)
    {
        $this->ip = $ip;
    }

}
