<?php
class ControllerShippingTeaser extends Controller {
	
	public function geolocation(){
		
		if ($this->request->server['REQUEST_METHOD'] == 'POST' && isset($this->request->post['ip'])) {
			
			$json = array();
			
			$ip = $this->request->post['ip'];
			$service = 'geoplugin';
					
			$json['msg'] = $this->getLocation($ip, $service);
			
		}
		
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));	
		
	}	
	
	protected function getDBGeoData($geo_data) {
		
		$_SESSION['geo_data'] = $geo_data;
		
		$this->load->model('shipping/free');
		$in_zone = $this->model_shipping_free->inGeoZone($geo_data['country_code']);
	
		if ($in_zone) {
			$_SESSION['free_total'] = $this->config->get('free_total');
			$_SESSION['fsp_match'] = 1;
		} else {
			$_SESSION['fsp_match'] = 0;
		}
	}
	
	protected function getLocation($ip, $service) {
		
		switch ($service) {
			case 'geoplugin':
				$response = $this->getGeoplugin($ip);
				break;
		}
		
		if (!empty($response)) {
			$this->getDBGeoData($response);
			return $response;	
		}
		return 'Service Unavailable';	
	}
		
	protected function getGeoplugin($ip) {
	
		$response = $this->getContents($ip, 'http://www.geoplugin.net/json.gp?ip=');
		
		if (empty($response)) {
			$_SESSION['geoip_success'] = 0;
		} else {
			$response = $this->reformatGeopluginResponse($response);
			$_SESSION['geoip_success'] = 1;
		}
		
		return $response;
		
	}
	
	protected function reformatGeopluginResponse($d) {
	
		$geoplugin_data = json_decode($d, true);
		
		$response = array(
		
			'ip' 			=> $geoplugin_data['geoplugin_request'],
			'country_code' 	=> $geoplugin_data['geoplugin_countryCode'],
			'country_name' 	=> $geoplugin_data['geoplugin_countryName'],
			'city'			=> $geoplugin_data['geoplugin_city']
		);
	
		return $response;
	}
	
	protected function getContents($ip, $url) {
		
		$url .= $ip;
		$response = file_get_contents("$url");
		
		return $response;
		
	}
	
}