HEX
Server: Apache/2.4.46 (Ubuntu)
System: Linux localhost 5.11.0-49-generic #55-Ubuntu SMP Wed Jan 12 17:36:34 UTC 2022 x86_64
User: root (0)
PHP: 7.4.16
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/html/labs/chatbot-v-4/classes/Master.php
<?php
require_once('../config.php');
Class Master extends DBConnection {
	private $settings;
	public function __construct(){
		global $_settings;
		$this->settings = $_settings;
		parent::__construct();
	}
	public function __destruct(){
		parent::__destruct();
	}
	
	public function save_response(){
		extract($_POST);
		if(!empty($id)){
			$del = $this->conn->query("DELETE FROM `questions` where id= '$id' ");
			if(!$del){
				return 2;
				exit;
			}
		}
		$data = "";
		$ins_resp = $this->conn->query("INSERT INTO `responses` set response_message = '{$response_message}' ");
		if(!$ins_resp){
			return 2;
			exit;
		}
		$resp_id = $this->conn->insert_id;

		foreach($question as $k => $v){
			$data = " response_id = {$resp_id} ";
			$data .= ", `question` = '$question[$k]' ";
			$ins[] = $this->conn->query("INSERT INTO `questions` set $data ");
		}
		if(isset($ins) && count($ins) == count($question)){
			$this->settings->set_flashdata("success"," Data successfully saved");
			return 1;
		}else{
			return 2;
			exit;
		}

	}
	public function delete_response(){
		extract($_POST);
		 $del = $this->conn->query("DELETE FROM `questions` where id = $id");
		 if($del){
			$this->settings->set_flashdata("success"," Data successfully deleted");
		 	return 1;
		 }else{
		 	$this->conn->error;
		 }
	}

	public function get_response(){
		extract($_POST);
		$message = str_replace(array("?"), '', $message);
		$chatId = str_replace(array("?"), '', $chatId);
		$option_value = str_replace(array("?"), '', $option_value);
		$preQuestionId = str_replace(array("?"), '', $preQuestionId);

		$cdate = date('Y-m-d',time());
		$not_question = array("what", "what is","who","who is", "where");
		if(in_array($message,$not_question)){
			$resp['status'] = "success";
			$resp['message'] = $this->settings->info('no_result');
			return json_encode($resp);
			exit;
		}
		$response =  array();

		$convert_lang = $this->get_lang();
		$get_country_code = $this->ip_info("Visitor", "Country Code");
		if(strtoupper($get_country_code) == 'IN')
		{
			$convert_lang = 'en';
		}


		if($preQuestionId == '5000' && $option_value == 'No')
		{
			$questionId = '4000';
			$sqlChatInsert = "DELETE FROM `chat_history` where chatId = '".$chatId."' and questionId = '".$questionId."'";
			$qryChatInsert = $this->conn->query($sqlChatInsert);
			if($qryChatInsert)
			{
				$insertResponse = "updated";
			}
			$questionId = '5000';
			$sqlChatInsert = "DELETE FROM `chat_history` where chatId = '".$chatId."' and questionId = '".$questionId."'";
			$qryChatInsert = $this->conn->query($sqlChatInsert);
			if($qryChatInsert)
			{
				$insertResponse = "updated";
			}
		}


		 

		if(strtoupper($message) == strtoupper("y0"))
		{
			$male_status = 'unchecked';
			$female_status = 'unchecked';

			$htmlQuestion1 = "";
			$htmlQuestion1 .= "Do you want to report the issue anonymously? <br/>";
			$htmlQuestion1 .= "<a class='btn btn-success cm-radio radio_send_chat ".$questionId."'  data-id='No' href='javascript:void(0);' onclick=\"selectAnsRadio('No', '".$chatId."')\"  > No <a/>";
			$htmlQuestion1 .= "<a class='btn btn-danger cm-radio radio_send_chat ".$questionId."' data-id='Yes' href='javascript:void(0);' onclick=\"selectAnsRadio('Yes', '".$chatId."')\"  > Yes <a/>";

			$response['status'] = "success";
			$response['message'] = $htmlQuestion1;
			return json_encode($response);
		} 


		//Get Answer

		
		 
		$sqlC = "SELECT * from `chat_history` where chatId = '".$chatId."'";
		$qryC = $this->conn->query($sqlC);
		$qArray = array();
		$questionIdC = '';
		$qchatCount = $qryC->num_rows;
		if($qryC->num_rows > 0)
		{
			//$resultC = $qryC->fetch_array();	
			while($rowC = $qryC->fetch_assoc()){	
			$questionIdC = $rowC['questionId'];
			$qArray[] = $questionIdC; 
			}
		}

		if(strtoupper($message) != strtoupper("Yes") && !$questionIdC)
		{
			
			// $resp['status'] = "success";
			// $resp['message'] = $this->settings->info('no_result');
			// return json_encode($resp);
			// exit;
		}
		// else if(strtoupper($message) != strtoupper("Hi") && !$questionIdC)
		// {
			
		// 	$resp['status'] = "success";
		// 	$resp['message'] = $this->settings->info('no_result');
		// 	return json_encode($resp);
		// 	exit;
		// }
		// else if(strtoupper($message) != strtoupper("Hello") && !$questionIdC)
		// {
			
		// 	$resp['status'] = "success";
		// 	$resp['message'] = $this->settings->info('no_result');
		// 	return json_encode($resp);
		// 	exit;
		// }


	//	$qArray = array("1000", "2000", "3000");
		if($qchatCount > 0)
		{
			$sql = "SELECT * from `tbl_labs_question_answer` where questionId NOT IN (".implode(',',$qArray).")";
		}
		else
		{
			$sql = "SELECT * from `tbl_labs_question_answer` where questionId in ('1000') limit 0,1";
		}
		$qry = $this->conn->query($sql);
		 
		$QuestionId = '';
		$question="";
		if($qry->num_rows > 0)
		{
			$result = $qry->fetch_array();		
			$questionId = $result['questionId'];		
			$question = $result['question'];

			 
			$question2 = '';
			if($convert_lang)
			{               
				if(strtolower($convert_lang) != 'en')
				{          
					$question2 = $this->translate($question, "en", "$convert_lang");
				}
			}

			$response['convert_language_lang'] = $convert_lang;
			$response['convert_language'] = $question2;


			$salesforce_key = $result['salesforce_key'];

			$questionTitle  = $question;

			$questiontype = $result['questiontype'];
						
			//return json_encode($resp);
			$cdate = date('Y-m-d',time());
			$response['status'] = "success";
			
			$response['questiontype'] = $questiontype;
			$htmlQuestion1 = "";
			$htmlQuestion1 = $question;
			if(strtoupper($questiontype) == strtoupper('radio'))
			{
				$titleOption1 = $result['titleOption1'];
				$valueOption1 = $result['valueOption1'];
				$titleOption2 = $result['titleOption2'];
				$valueOption2 = $result['valueOption2'];
				$titleOption3 = $result['titleOption3'];
				$valueOption3 = $result['valueOption3'];


				$titleOption4 = $result['titleOption4'];
				$valueOption4 = $result['valueOption4'];
				 

				
				$htmlQuestion1 .=  "<br/>";
				if($titleOption1)
				{
					$htmlQuestion1 .= "<a class='btn btn-outline-secondary cm-radio radio_send_chat ".$questionId."' data-id='No' href='javascript:void(0);' onclick=\"selectAnsRadio('".$valueOption1."', '".$chatId."')\"  > ".$titleOption1." <a/>";
				}
				if($titleOption2)
				{
					$htmlQuestion1 .= "<a class='btn btn-outline-secondary cm-radio radio_send_chat ".$questionId."' data-id='No' href='javascript:void(0);' onclick=\"selectAnsRadio('".$valueOption2."', '".$chatId."')\"  > ".$titleOption2." <a/>";
				}
				if($titleOption3)
				{
					$htmlQuestion1 .= "<a class='btn btn-outline-secondary cm-radio radio_send_chat ".$questionId."' data-id='No' href='javascript:void(0);' onclick=\"selectAnsRadio('".$valueOption3."', '".$chatId."')\"  > ".$titleOption3." <a/>";
				}

				if($titleOption4)
				{
					$htmlQuestion1 .= "<a class='btn btn-outline-secondary cm-radio radio_send_chat ".$questionId."' data-id='No' href='javascript:void(0);' onclick=\"selectAnsRadio('".$valueOption4."', '".$chatId."')\"  > ".$titleOption4." <a/>";
				}
				
			
			}

			if(strtoupper($questiontype) == strtoupper('select'))
			{				
				$htmlQuestion1 = $questionTitle;
				$htmlQuestion1 .= "<br/>";
				$htmlQuestion1 .= htmlFactoryList($chatId, $questionId);
			}

			if(strtoupper($questiontype) == strtoupper('file'))
			{
				$htmlQuestion1 = $questionTitle;
				$htmlQuestion1 .= "<br/>";
				$htmlQuestion1 .= htmlFileUpload($chatId, $questionId);
			}
			 
			$response['message'] = $htmlQuestion1;
			$response['questionId'] = $questionId;	
			$insertResponse = "";

			$chatId = isset($_POST['chatId']) ? $_POST['chatId'] : '';
			$preQuestionId = isset($_POST['preQuestionId']) ? $_POST['preQuestionId'] : '';
			$factoryId = isset($_POST['factoryId']) ? $_POST['factoryId'] : '';
			 			
			$sqlC = "SELECT * from `chat_history` where chatId = '".$chatId."' and questionId = '".$preQuestionId."'";
			$qryC = $this->conn->query($sqlC);
			$qArray = array();
			$questionIdC = '';
			$qchatCount = $qryC->num_rows;

			if(strtoupper($questiontype) == strtoupper('radio'))
			{
				$question = $option_value;
			}
			if($qchatCount > 0)
			{
				if($preQuestionId == '4000')
				{
					$message = $factoryId;
				}

				if($preQuestionId) {
					$sqlChatInsert = "update `chat_history` set answer = '".$message."',  updated_date = '".$cdate."' where chatId = '".$chatId."' and questionId = '".$preQuestionId."'";
					$qryChatInsert = $this->conn->query($sqlChatInsert);
					if($qryChatInsert)
					{
						$insertResponse = "updated";
						$sqlChatInsert = "insert into `chat_history` (chatId, questionId, question, answer, create_date, updated_date, salesforce_key) values ('".$chatId."', '".$questionId."',  '".$questionTitle."', '".$message."', '".$cdate."', '".$cdate."', '".$salesforce_key."')";
				        $qryChatInsert = $this->conn->query($sqlChatInsert);
				        if($qryChatInsert)
				        {
					       $insertResponse = "inserted";
				        }
					}
				}
			}
			else
			{
				$sqlChatInsert = "insert into `chat_history` (chatId, questionId, question, answer, create_date, updated_date, salesforce_key) values ('".$chatId."', '".$questionId."',  '".$questionTitle."', '".$message."', '".$cdate."', '".$cdate."', '".$salesforce_key."')";
				$qryChatInsert = $this->conn->query($sqlChatInsert);
				if($qryChatInsert)
				{
					$insertResponse = "inserted";
				}

				if($questionId == '5000')
				{
					$questionId = '5000';
					$sqlChatInsert = "update `chat_history` set answer = '".$option_value."',  updated_date = '".$cdate."' where chatId = '".$chatId."' and questionId = '".$questionId."'";
					$qryChatInsert = $this->conn->query($sqlChatInsert);
					if($qryChatInsert)
					{
						$insertResponse = "updated";
					}
				}
			}						
			$response['histroy'] = $insertResponse;			
			$response['sql'] = $sqlChatInsert;
			$response['end'] = "no";			
			return json_encode($response);
		}

		$CaseId = '';
		$salesforcePost = array();
		if($preQuestionId == '9000' && $message) {
			$sqlChatInsert = "update `chat_history` set answer = '".$message."',  updated_date = '".$cdate."' where chatId = '".$chatId."' and questionId = '".$preQuestionId."'";
			$qryChatInsert = $this->conn->query($sqlChatInsert);
			if($qryChatInsert)
			{
				$response['sql'] = $sqlChatInsert; 
			    $sql = "SELECT * from `chat_history` where chatId = '".$chatId."'";		        		        
		        $qry = $this->conn->query($sql);
		        if($qry->num_rows > 0)
		        {		
					$files = array();			   
					while ($row = $qry->fetch_row()) 
					{
						$questionId = $row[1];		
			            $salesforce_key = $row[5];
						$salesforce_answer = $row[6];

						if($salesforce_key)
						{
							$salesforcePost[$salesforce_key] = $salesforce_answer;

							if($salesforce_key == 'Files')
							{
								$allowed_image = array('gif', 'png', 'jpg', 'jpeg');
								$allowed_video = array('mp4', 'wav', 'avi', 'mov', 'mpeg', '3gp');
								$allowed_audio = array('mp3', 'ogg', 'flac');
								$ext = pathinfo($salesforce_answer, PATHINFO_EXTENSION);
								$fileType = '';
								if (in_array($ext, $allowed_image)) {
									$fileType = 'image';
								}
								else if (in_array($ext, $allowed_video)) {
									$fileType = 'video';
								}
								else if (in_array($ext, $allowed_audio)) {
									$fileType = 'audio';
								}

								$files[] = array("FileType"=>$fileType,"S3_URL"=>$salesforce_answer,"CaseId"=>"");

								$salesforcePost[$salesforce_key] = $files;
							}
						}
						//echo $questionId.",";
					} 

					$postdata = $salesforcePost; 
					$response['salesforce_post_data'] = $postdata;
				   
					$postdata = json_encode($postdata);
					$curl = curl_init();
					curl_setopt_array($curl, array(
					CURLOPT_URL => 'https://labsinitiative--chatbot.sandbox.my.salesforce-sites.com/services/apexrest/FactoryCase',
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => '',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => true,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => 'POST',
					CURLOPT_POSTFIELDS =>$postdata,
					CURLOPT_HTTPHEADER => array(
					  'Content-Type: application/json',
					  'Cookie: CookieConsentPolicy=0:1; LSKey-c$CookieConsentPolicy=0:1; BrowserId=z9mjH4z7Ee2Ob-W8c40DpA'
					),
				  ));
				  $apiresponse = curl_exec($curl);

				  $resdata = json_decode($apiresponse,true);
				  curl_close($curl);
				 // echo $response;
				  $response['salesforce_response'] = $apiresponse;
				  
				  $CaseId = $resdata['CaseId'];
				  $dres = '';
				  if($CaseId)
				  {
					$sqlChatDelete = "DELETE FROM chat_history WHERE chatId = '".$chatId."'";
					$qryChatDelete = $this->conn->query($sqlChatDelete);
					if($qryChatDelete)
					{
						$dres = "Deleted";
					}
				  }

				  $response['chat_data'] = $dres;
				 
			   }


			}
		}

		
		
		 

		 


		$sql = "SELECT r.response_message,q.id from `questions` q inner join `responses` r on q.response_id = r.id where q.question Like '%{$message}%' ";
		$qry = $this->conn->query($sql);
	 
		if($qry->num_rows > 0){
			$result = $qry->fetch_array();
			// var_dump($result);
			$resp['status'] = "success";
			$cquestion = $result['response_message'];

			if($convert_lang)
			{               
				if(strtolower($convert_lang) != 'en')
				{          
					$cquestion = $this->translate($cquestion, "en", "$convert_lang");
				}
			}

			 
			$resp['message'] = $cquestion;


			$resp['sql'] = $sql;
			//$this->conn->query("INSERT INTO `frequent_asks` set question_id = '{$result['id']}' ");
			$resp = '{"status":"success","message":"Please share your name?"}';
			$resp = json_decode($resp);
			return json_encode($resp);
		}else{
			$resp['status'] = "success";
			$resp['message'] = $this->settings->info('no_result');
			$chk = $this->conn->query("SELECT * FROM `unanswered` where `question` = '{$message}' ");
			// if($chk->num_rows > 0){
			// 	$this->conn->query("UPDATE `unanswered` set no_asks = no_asks + 1 ");
			// }else{
			// 	$this->conn->query("INSERT INTO `unanswered` set question = '{$message}' ");
			// }

			// $resp = '{"status":"success","message":"Please share your name?"}';
			// $resp = json_decode($resp);
			// return json_encode($resp);

			 
			$response['status'] = "success";
			$response['end'] = "yes";
			$response['message'] = "Thank you for sharing the details, here is your reference number - #<strong> $CaseId </strong>, have a great day.";			
			return json_encode($response);
			 
		}
	}
	public function delete_unanswer(){
		extract($_POST);
		 $del = $this->conn->query("DELETE FROM `unanswered` where id = $id");
		 if($del){
			$this->settings->set_flashdata("success"," Data successfully deleted");
		 	return 1;
		 }else{
		 	$this->conn->error;
		 }
	}

	function translate($q, $sl, $tl){    
		$res= file_get_contents("https://translate.googleapis.com/translate_a/single?client=gtx&ie=UTF-8&oe=UTF-8&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&sl=".$sl."&tl=".$tl."&hl=hl&q=".urlencode($q), $_SERVER['DOCUMENT_ROOT']."/transes.html");
		$res=json_decode($res);
		return $res[0][0][0];
	}
	
	function get_lang()
	{
		$country_code = $this->ip_info("Visitor", "Country Code"); 
		$lang = $this->country_code_to_locale($country_code, $language_code = '');
		$selected_lang = str_replace("-".$country_code,"",$lang);
		$selected_lang = str_replace("_".$country_code,"",$selected_lang);
		return $selected_lang;
	}
	 
	 
	
	function country_code_to_locale($country_code, $language_code = '')
	{
		 
		$locales = array('af-ZA',
						'am-ET',
						'ar-AE',
						'ar-BH',
						'ar-DZ',
						'ar-EG',
						'ar-IQ',
						'ar-JO',
						'ar-KW',
						'ar-LB',
						'ar-LY',
						'ar-MA',
						'arn-CL',
						'ar-OM',
						'ar-QA',
						'ar-SA',
						'ar-SY',
						'ar-TN',
						'ar-YE',
						'as-IN',
						'az-Cyrl-AZ',
						'az-Latn-AZ',
						'ba-RU',
						'be-BY',
						'bg-BG',
						'bn-BD',
						'bn-IN',
						'bo-CN',
						'br-FR',
						'bs-Cyrl-BA',
						'bs-Latn-BA',
						'ca-ES',
						'co-FR',
						'cs-CZ',
						'cy-GB',
						'da-DK',
						'de-AT',
						'de-CH',
						'de-DE',
						'de-LI',
						'de-LU',
						'dsb-DE',
						'dv-MV',
						'el-GR',
						'en-029',
						'en-AU',
						'en-BZ',
						'en-CA',
						'en-GB',
						'en-IE',
						'en-IN',
						'en-JM',
						'en-MY',
						'en-NZ',
						'en-PH',
						'en-SG',
						'en-TT',
						'en-US',
						'en-ZA',
						'en-ZW',
						'es-AR',
						'es-BO',
						'es-CL',
						'es-CO',
						'es-CR',
						'es-DO',
						'es-EC',
						'es-ES',
						'es-GT',
						'es-HN',
						'es-MX',
						'es-NI',
						'es-PA',
						'es-PE',
						'es-PR',
						'es-PY',
						'es-SV',
						'es-US',
						'es-UY',
						'es-VE',
						'et-EE',
						'eu-ES',
						'fa-IR',
						'fi-FI',
						'fil-PH',
						'fo-FO',
						'fr-BE',
						'fr-CA',
						'fr-CH',
						'fr-FR',
						'fr-LU',
						'fr-MC',
						'fy-NL',
						'ga-IE',
						'gd-GB',
						'gl-ES',
						'gsw-FR',
						'gu-IN',
						'ha-Latn-NG',
						'he-IL',
						'hi-IN',
						'hr-BA',
						'hr-HR',
						'hsb-DE',
						'hu-HU',
						'hy-AM',
						'id-ID',
						'ig-NG',
						'ii-CN',
						'is-IS',
						'it-CH',
						'it-IT',
						'iu-Cans-CA',
						'iu-Latn-CA',
						'ja-JP',
						'ka-GE',
						'kk-KZ',
						'kl-GL',
						'km-KH',
						'kn-IN',
						'kok-IN',
						'ko-KR',
						'ky-KG',
						'lb-LU',
						'lo-LA',
						'lt-LT',
						'lv-LV',
						'mi-NZ',
						'mk-MK',
						'ml-IN',
						'mn-MN',
						'mn-Mong-CN',
						'moh-CA',
						'mr-IN',
						'ms-BN',
						'ms-MY',
						'mt-MT',
						'nb-NO',
						'ne-NP',
						'nl-BE',
						'nl-NL',
						'nn-NO',
						'nso-ZA',
						'oc-FR',
						'or-IN',
						'pa-IN',
						'pl-PL',
						'prs-AF',
						'ps-AF',
						'pt-BR',
						'pt-PT',
						'qut-GT',
						'quz-BO',
						'quz-EC',
						'quz-PE',
						'rm-CH',
						'ro-RO',
						'ru-RU',
						'rw-RW',
						'sah-RU',
						'sa-IN',
						'se-FI',
						'se-NO',
						'se-SE',
						'si-LK',
						'sk-SK',
						'sl-SI',
						'sma-NO',
						'sma-SE',
						'smj-NO',
						'smj-SE',
						'smn-FI',
						'sms-FI',
						'sq-AL',
						'sr-Cyrl-BA',
						'sr-Cyrl-CS',
						'sr-Cyrl-ME',
						'sr-Cyrl-RS',
						'sr-Latn-BA',
						'sr-Latn-CS',
						'sr-Latn-ME',
						'sr-Latn-RS',
						'sv-FI',
						'sv-SE',
						'sw-KE',
						'syr-SY',
						'ta-IN',
						'te-IN',
						'tg-Cyrl-TJ',
						'th-TH',
						'tk-TM',
						'tn-ZA',
						'tr-TR',
						'tt-RU',
						'tzm-Latn-DZ',
						'ug-CN',
						'uk-UA',
						'ur-PK',
						'uz-Cyrl-UZ',
						'uz-Latn-UZ',
						'vi-VN',
						'wo-SN',
						'xh-ZA',
						'yo-NG',
						'zh-CN',
						'zh-HK',
						'zh-MO',
						'zh-SG',
						'zh-TW',
						'zu-ZA',);
	
		foreach ($locales as $locale)
		{
			$locale_region = locale_get_region($locale);
			$locale_language = locale_get_primary_language($locale);
			$locale_array = array('language' => $locale_language,
								 'region' => $locale_region);
	
			if (strtoupper($country_code) == $locale_region &&
				$language_code == '')
			{
				return locale_compose($locale_array);
			}
			elseif (strtoupper($country_code) == $locale_region &&
					strtolower($language_code) == $locale_language)
			{
				return locale_compose($locale_array);
			}
		}
	
		return null;
	}
	
	
	
	function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
		$output = NULL;
		
		if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
			$ip = $_SERVER["REMOTE_ADDR"];
			if ($deep_detect) {
				if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
					$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
				if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
					$ip = $_SERVER['HTTP_CLIENT_IP'];
			}
		}
		$purpose    = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
		$support    = array("country", "countrycode", "state", "region", "city", "location", "address");
		$continents = array(
			"AF" => "Africa",
			"AN" => "Antarctica",
			"AS" => "Asia",
			"EU" => "Europe",
			"OC" => "Australia (Oceania)",
			"NA" => "North America",
			"SA" => "South America"
		);
	 
		if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
			$ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
			if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
				switch ($purpose) {
					case "location":
						$output = array(
							"city"           => @$ipdat->geoplugin_city,
							"state"          => @$ipdat->geoplugin_regionName,
							"country"        => @$ipdat->geoplugin_countryName,
							"country_code"   => @$ipdat->geoplugin_countryCode,
							"continent"      => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
							"continent_code" => @$ipdat->geoplugin_continentCode
						);
						break;
					case "address":
						$address = array($ipdat->geoplugin_countryName);
						if (@strlen($ipdat->geoplugin_regionName) >= 1)
							$address[] = $ipdat->geoplugin_regionName;
						if (@strlen($ipdat->geoplugin_city) >= 1)
							$address[] = $ipdat->geoplugin_city;
						$output = implode(", ", array_reverse($address));
						break;
					case "city":
						$output = @$ipdat->geoplugin_city;
						break;
					case "state":
						$output = @$ipdat->geoplugin_regionName;
						break;
					case "region":
						$output = @$ipdat->geoplugin_regionName;
						break;
					case "country":
						$output = @$ipdat->geoplugin_countryName;
						break;
					case "countrycode":
						$output = @$ipdat->geoplugin_countryCode;
						break;
				}
			}
		}
		return $output;
	}
}

$Master = new Master();
$action = !isset($_GET['f']) ? 'none' : strtolower($_GET['f']);
$sysset = new SystemSettings();
switch ($action) {
	case 'save_response':
		echo $Master->save_response();
	break;
	case 'delete_response':
		echo $Master->delete_response();
	break;
	case 'get_response':
		echo $Master->get_response();
	break;
	case 'delete_unanswer':
		echo $Master->delete_unanswer();
	break;
	default:
		// echo $sysset->index();
		break;
}


function getFactoryList()
{
	$curl = curl_init();
	curl_setopt_array($curl, array(
	CURLOPT_URL => 'https://labsinitiative--chatbot.sandbox.my.salesforce-sites.com/services/apexrest/getFactoryInformation',
	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_HTTPHEADER => array(
		'Cookie: CookieConsentPolicy=0:1; LSKey-c$CookieConsentPolicy=0:1; BrowserId=z9mjH4z7Ee2Ob-W8c40DpA'
	),
	));
	$response = curl_exec($curl);
	curl_close($curl);
	$factoryList = json_decode($response,true);
	return $factoryList;
}


//print_r($factoryList);

function htmlFactoryList($chatId='', $questionId = '')
{
	$factoryList = getFactoryList();
	$html = '';
	if(count($factoryList) > 0) 
	{
		 
  $html .= '<input class="form-control '.$questionId.'" list="browsers" name="browser" id="browser" onchange="selectFactoryName(this)">
  <datalist id="browsers">';
   
		for($k = 0; $k < count($factoryList); $k++)
		{
			$factoryData = $factoryList[$k];
			$factoryName = $factoryData['Name'];
			$BillingCity = $factoryData['BillingCity'];
			$BillingStreet = isset($factoryData['BillingStreet']) ? $factoryData['BillingStreet'] : '';

			
			$factoryId = $factoryData['Id'];
			
			$html .= '<option data-id="'.$factoryId.'" id="'.$factoryId.'" value="'.$factoryName.'" data-address="'.$BillingStreet.'">';
			 
		}
		 
		$html .= '</datalist>';
		
	}

	return $html;
}


function htmlFileUpload($chatId='', $questionId='')
{	 
	$html = '';	 
    //$html .= '<input class="form-control" type="file" name="fileToUpload" id="fileToUpload" onchange="fileUploadSubmit();"> <input type="button" value="Upload" id="btnFileUpload" class="btn btn-outline-success '.$questionId.'" onclick="fileUploadSubmit();">';

	$html .= '<input class="form-control" type="file" name="fileToUpload" id="fileToUpload" onchange="fileUploadSubmit();">';


// 	$html = '<div class="input-group">
// 	<input type="text" class="form-control" aria-label="Amount (to the nearest dollar)">
// 	<div class="input-group-append">
// 	  <span class="input-group-text">$</span>
// 	  <input  class="input-group-text" type="file" name="fileToUpload" id="fileToUpload" onchange="fileUploadSubmit();">
// 	</div>
//   </div>';

	return $html;
}