<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * used to get user gegraphical information 
 * @author Mohamed Mahdy
 */
 class User_geographical_info {
     
    protected $errors = array();
    public $CI;
    private $service = 'api.ipinfodb.com';
    private $version = 'v3';
    private $apiKey = '37865e42cdab832d6a0166d714d2b49d6d7631ba7e2b6a7aca07389e204af35a';
    public static $locationData;
    
    public function __construct()
    {
       $this->CI =& get_instance();
       if(is_array($this->CI->session->userdata("locationData"))){
          self::$locationData = $this->CI->session->userdata("locationData");
       }
       $this->setKey($this->apiKey);
    }
    /**
     * set the api key string
     * @param string $key 
     */
    private function setKey($key)
    {
        if(!empty($key))
        {
            $this->apiKey = $key;
            log_message('debug','api has been setted ok .. '.$this->apiKey);
        }
    }

    private function getError()
    {
       return implode("\n", $this->errors);
    }
    /**
     * @param string $host
     * @return array 
     */
    private function getCountry($host)
    { 
       $host_data = $this->getResult($host, 'ip-country');
       if(is_array($host_data) and count($host_data) > 0)
       {
          log_message('debug','\$host_data array has been initialized');
          return $host_data;
       }
       else
       {
          log_message('debug',"\$host_data not array or it's count is ".count($host_data));
          return false;
       }    
    }
    /**
     *
     * @param type $host
     * @return type 
     */
    function getCity($host)
    {
       return $this->getResult($host, 'ip-city');
    }

    private function getResult($host, $name)
    {
        $ip = @gethostbyname($host);
        if(preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip)){
            $xml = @file_get_contents('http://' . $this->service . '/' . $this->version . '/' . $name . '/?key=' . $this->apiKey . '&ip=' . $ip . '&format=xml');
            try{
                $response = @new SimpleXMLElement($xml);
                foreach($response as $field=>$value)
                {
                   $result[(string)$field] = (string)$value;
                }
                return $result;
            }
            catch(Exception $e){
                $this->errors[] = $e->getMessage();
                return;
            }
        }
        $this->errors[] = '"' . $host . '" is not a valid IP address or hostname.';
        return;
    }
}