<?php
/*+*******************************************************************************
 * The content of this file is subject to the CRMTiger Pro license.
 * ("License"); You may not use this file except in compliance with the License
 * The Initial Developer of the Original Code is vTiger
 * The Modified Code of the Original Code owned by https://crmtiger.com/
 * Portions created by CRMTiger.com are Copyright(C) CRMTiger.com
 * All Rights Reserved.
  ***************************************************************************** */
class CTMobileSettings_SaveApi_Action extends Vtiger_Save_Action {
    
	public function process(Vtiger_Request $request) {
		global $adb,$site_URL;
		$mode = trim($request->get('mode'));
		$api_Key = trim($request->get('api_Key'));
		if($mode == 'Google'){
			$getLicenseQuery=$adb->pquery("SELECT * FROM ctmobile_api_settings WHERE order_no LIKE '%GOOGLE%'");
			$numOfLicenseCount = $adb->num_rows($getLicenseQuery);
			
			$address = "Prerna Arcade, Parimal Underbridge, Ellisbridge, Tulsibag Society, Ambawadi, Ahmedabad, Gujarat 380006";
			$address=urlencode($address);
			
			$data = array();
			$opts = array('http'=>array('header'=>"User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36\r\n"));
			$context = stream_context_create($opts);
			$formattedAddr = str_replace(' ','+',$address);
			//Send request and receive json data by address
			$url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&key='.$api_Key;
			$curl = curl_init();
		    curl_setopt_array($curl, array(
		      CURLOPT_URL => $url,
		      CURLOPT_RETURNTRANSFER => true,
		      CURLOPT_ENCODING => '',
		      CURLOPT_MAXREDIRS => 10,
		      CURLOPT_TIMEOUT => 0,
		      CURLOPT_FOLLOWLOCATION => true,
		      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		      CURLOPT_CUSTOMREQUEST => 'GET',
		      CURLOPT_USERAGENT => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36"
		    ));
		    $geocodeFromAddr = curl_exec($curl);
		    curl_close($curl);

			$output = json_decode($geocodeFromAddr);
			$status = $output->status;
			if($status === 'OK'){
				if($numOfLicenseCount > 0){
					$record=$adb->query_result($getLicenseQuery,0,'id');
					$query=$adb->pquery("UPDATE ctmobile_api_settings SET api_key=? WHERE id=?",array($api_Key,$record));
					if($query){
						
						$result = array('code'=>2, 'msg'=>vtranslate('Google Api Key Updated Successfully','CTMobileSettings'));
					}
				}else{
					$query=$adb->pquery("INSERT INTO ctmobile_api_settings (api_key,order_no) values(?,?)",array($api_Key,'GOOGLE::0'));
					if($query){
						$result = array('code'=>1, 'msg'=>vtranslate('Google Api Key Inserted Successfully','CTMobileSettings'));
					}
				}
			}else{
				$result = array('code'=>100, 'msg'=>vtranslate($output->error_message,'CTMobileSettings'));
			}
			$response = new Vtiger_Response();
			$response->setEmitType(Vtiger_Response::$EMIT_JSON);
			$response->setResult($result);
			$response->emit();
		}else if($mode == 'LocationIQ'){
			$getLicenseQuery=$adb->pquery("SELECT * FROM ctmobile_api_settings WHERE order_no LIKE '%LOCATIONIQ%'");
			$numOfLicenseCount = $adb->num_rows($getLicenseQuery);
			
			$address = "Prerna Arcade, Parimal Underbridge, Ellisbridge, Tulsibag Society, Ambawadi, Ahmedabad, Gujarat 380006";
			$address=urlencode($address);
			
			$data = array();
			$opts = array('http'=>array('header'=>"User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36\r\n"));
			$context = stream_context_create($opts);
			$formattedAddr = str_replace(' ','+',$address);
			//Send request and receive json data by address
			$url = 'https://us1.locationiq.com/v1/search.php?key='.$api_Key.'&q='.$formattedAddr.'&format=json';
			
			$curl = curl_init();
		    curl_setopt_array($curl, array(
		      CURLOPT_URL => $url,
		      CURLOPT_RETURNTRANSFER => true,
		      CURLOPT_ENCODING => '',
		      CURLOPT_MAXREDIRS => 10,
		      CURLOPT_TIMEOUT => 0,
		      CURLOPT_FOLLOWLOCATION => true,
		      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		      CURLOPT_CUSTOMREQUEST => 'GET',
		      CURLOPT_USERAGENT => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36"
		    ));
		    $geocodeFromAddr = curl_exec($curl);
		    curl_close($curl);

			$output = json_decode($geocodeFromAddr,true);
			if($output['error'] != ''){
				$result = array('code'=>100, 'msg'=>vtranslate($output['error'],'CTMobileSettings'));
			}else{
				if($numOfLicenseCount > 0){
					$record=$adb->query_result($getLicenseQuery,0,'id');
					$query=$adb->pquery("UPDATE ctmobile_api_settings SET api_key=? WHERE id=?",array($api_Key,$record));
					if($query){
						
						$result = array('code'=>2, 'msg'=>vtranslate('Location IQ Api Key Updated Successfully','CTMobileSettings'));
					}
				}else{
					$query=$adb->pquery("INSERT INTO ctmobile_api_settings (api_key,order_no) values(?,?)",array($api_Key,'LOCATIONIQ::0'));
					if($query){
						$result = array('code'=>1, 'msg'=>vtranslate('Location IQ Api Key Inserted Successfully','CTMobileSettings'));
					}
				}
			}
			$response = new Vtiger_Response();
			$response->setEmitType(Vtiger_Response::$EMIT_JSON);
			$response->setResult($result);
			$response->emit();
		}else if($mode == 'updatemapstatus'){
			$map_type = $request->get('map_type');
			if($map_type == 'GOOGLE'){
				$apikey = CTMobileSettings_Module_Model::getGoogleApiKey();
				if($apikey){
					$update1 = $adb->pquery("UPDATE ctmobile_api_settings SET order_no = ? WHERE order_no LIKE ?",array('GOOGLE::1','%GOOGLE%'));
					$update2 = $adb->pquery("UPDATE ctmobile_api_settings SET order_no = ? WHERE order_no LIKE ?",array('LOCATIONIQ::0','%LOCATIONIQ%'));
					$update3 = $adb->pquery("UPDATE ctmobile_api_settings SET order_no = ? WHERE order_no LIKE ?",array('OPENSTREET::0','%OPENSTREET%'));
					$result = array('code'=>1, 'msg'=>vtranslate('Map status updated Successfully','CTMobileSettings'));
				}else{
					$activemap = CTMobileSettings_Module_Model::getActiveMap();
					$result = array('code'=>100, 'msg'=>vtranslate('Please add google Api first !','CTMobileSettings'),'activemap'=>$activemap);
				}
			}else if($map_type == 'LOCATIONIQ'){
				$update1 = $adb->pquery("UPDATE ctmobile_api_settings SET order_no = ? WHERE order_no LIKE ?",array('GOOGLE::0','%GOOGLE%'));
				$update2 = $adb->pquery("UPDATE ctmobile_api_settings SET order_no = ? WHERE order_no LIKE ?",array('LOCATIONIQ::1','%LOCATIONIQ%'));
				$update3 = $adb->pquery("UPDATE ctmobile_api_settings SET order_no = ? WHERE order_no LIKE ?",array('OPENSTREET::0','%OPENSTREET%'));
				$result = array('code'=>1, 'msg'=>vtranslate('Map status updated Successfully','CTMobileSettings'));
			}else{
				$update1 = $adb->pquery("UPDATE ctmobile_api_settings SET order_no = ? WHERE order_no LIKE ?",array('GOOGLE::0','%GOOGLE%'));
				$update2 = $adb->pquery("UPDATE ctmobile_api_settings SET order_no = ? WHERE order_no LIKE ?",array('LOCATIONIQ::0','%LOCATIONIQ%'));
				$update3 = $adb->pquery("UPDATE ctmobile_api_settings SET order_no = ? WHERE order_no LIKE ?",array('OPENSTREET::1','%OPENSTREET%'));
				$result = array('code'=>1, 'msg'=>vtranslate('Map status updated Successfully','CTMobileSettings'));
			}
			$response = new Vtiger_Response();
			$response->setEmitType(Vtiger_Response::$EMIT_JSON);
			$response->setResult($result);
			$response->emit();
		}

	}
}
?>
