<?php

class IpToCountryHelper
{
  public static $ic;
  public static $deprecated = 15; // days

  public function __construct()
  {
  }

  public static function getInstance()
  {
    if (!empty(self::$ic)) return self::$ic;
    self::$ic = new IpToCountryHelper();
    return self::$ic;
  }

  public static function getValues($ip = "")
  {
    if ($ip == "") $ip = $_SERVER['REMOTE_ADDR'];

    MySqlHelper::getInstance()->query("SELECT * FROM `" . CRMADATBAZIS . "`.`iptocountry` WHERE IP='" . $ip . "' LIMIT 1;");
    $res = MySqlHelper::getInstance()->fetchAssoc();
    if (empty($res)) // ha nincs rekord, akkor insert-el egy uj rekordot
    {
      $tomb = self::downloadValues($ip);
      self::saveRecord($tomb);
    } else // ha van rekord
    {
      $res = $res[0];
      if (substr($res['AddDateTime'], 0, 10) < date('Y-m-d', time() - 86400 * self::$deprecated)) // es elevult a rekord, akkor torli a regit es insert-el egy uj rekordot
      {
        self::delOldRecords();
        $tomb = self::downloadValues($ip);
        self::saveRecord($tomb);
      } else // es nem evult el a rekord, akkor az adatbazisbol adja vissza
      {
        $tomb = $res;
      }
    }
    return ($tomb);
  }


  public static function downloadValues($ip = "")
  {
    if ($ip == "") $ip = $_SERVER['REMOTE_ADDR'];
    $locale = @file_get_contents("http://freegeoip.net/xml/" . $ip, FALSE, stream_context_create(array('http' => array('timeout' => 2))));
    $tomb = json_decode(json_encode(simplexml_load_string($locale)), TRUE);
    return ($tomb);
  }

  public static function saveRecord($tomb = array())
  {
    $tomb['AddDateTime'] = date('Y-m-d H:i:s', time());
    MySqlHelper::getInstance()->insert("`" . CRMADATBAZIS . "`.`iptocountry`", $tomb);
  }

  public static function delOldRecords()
  {
    MySqlHelper::getInstance()->delete("`" . CRMADATBAZIS . "`.`iptocountry`", "DATE(`AddDateTime`)<'" . date('Y-m-d', time() - 86400 * self::$deprecated) . "'");
  }


  public static function getCountryName($ip = "")
  {
    if ($ip == "") $ip = $_SERVER['REMOTE_ADDR'];
    $ret = self::getValues($ip);
    if (!isset($ret["CountryName"]) || trim($ret["CountryName"]) == '') $ret["CountryName"] = 'unknown';
    return (trim($ret["CountryName"]));
  }
}
