<?php
$host = "https://bodi4life.com";
$ftp_user = "qboxes";
$ftp_password = "Alan'12an";

$action = '';
if (isset($_GET['action'])) {
	$action = $_GET['action'];
}

switch ($action) {
	case 'GetCustomerChat':
		$customer_id = '';
		$msg_content = [];
		if(isset($_POST['customer_id']) && $_POST['customer_id'] != '') {
			$customer_id = htmlentities(strip_tags($_POST['customer_id']));
			$CustomerFile = '../ChatRoom/userChats/'.$customer_id.'.json';
	        $file_exists = file_exists($CustomerFile);
	        if ($file_exists) {
	        	$msg_content = json_decode(file_get_contents($CustomerFile), true);
	        }
		}
		//pr($msg_content);
	    echo json_encode($msg_content);
		break;
	case 'ChatNotification':
		// read user_out.json from bodi server
	    $data = file_get_contents($host."/chat/user_out.json");
	    if ($data === FALSE) {
	        $msg_content = [];
	    } else {
	        $msg_content = json_decode($data, true);
	    }
	    //pr($msg_content); die('aa');
	    if(!empty($msg_content)) {
	    	$isblankFound=false;
			foreach($msg_content as $msgKey => $msgRow) {
				if($msgRow['msg'] == '') {
					
					//Debuging START------------------
					$saveToHistoryData = array(
						'function' => 'ChatNotification-EMPTY',
						'data' => $msgRow
					);
					writeHistoryLog($saveToHistoryData);
					//Debuging END------------------
					
					$isblankFound=true;
					$CustomerFile = '../ChatRoom/userChats/'.$msgRow['customer_id'].'.json';
	        		$file_exists = file_exists($CustomerFile);
				    
		        	$user = isset($msgRow['user'])?htmlentities(strip_tags($msgRow['user'])):'';
				    $ip = isset($msgRow['ip'])?htmlentities(strip_tags($msgRow['ip'])):'';
				    $location = isset($msgRow['location'])?htmlentities(strip_tags($msgRow['location'])):'';
				    $last_visited = isset($msgRow['last_visited'])?htmlentities(strip_tags($msgRow['last_visited'])):'';
				    $device = isset($msgRow['device'])?htmlentities(strip_tags($msgRow['device'])):'';
				    $chat_status = isset($msgRow['chat_status'])?htmlentities(strip_tags($msgRow['chat_status'])):'';
				    $timestamp = isset($msgRow['timestamp'])?htmlentities(strip_tags($msgRow['timestamp'])):'';
				    $message = array("timestamp"=>$timestamp, "user"=>$user, "msg"=>'', "customer_id"=>$msgRow['customer_id']);
	        		// get current contents of json file
			        if (!$file_exists) {
			        	$data = array(
			            	"chat_start_date"=>$timestamp, 
			            	"ip"=>$ip, 
			            	"user"=>$user, 
			            	"location"=>$location, 
			            	"last_visited"=>$last_visited, 
			            	"device"=>$device, 
			            	"last_updated"=>$timestamp, 
			            	"customer_id"=>$msgRow['customer_id'],
			            	"chat_status"=>$chat_status
			            );
			            $data['messages'] = array();
			            array_push($data['messages'],$message);
			            
			            $json = json_encode($data, JSON_PRETTY_PRINT);
				        file_put_contents($CustomerFile, $json);
			            
			        }
			        else {
						$data = json_decode(file_get_contents($CustomerFile), true);
			            // make sure dictionary values aren't empty	
			            if($last_visited!='') {
							$data['last_visited'] = $last_visited;
						}		            
			            if($device!='') {
			            	$data['device'] = $device;
						}		            
			            if($timestamp!='') {
			            	$data['last_updated'] = $timestamp;
						}		            
			            if($chat_status!='') {
			            	$data['chat_status'] = $chat_status;
						}
			            
			            $json = json_encode($data, JSON_PRETTY_PRINT);
				        file_put_contents($CustomerFile, $json);
					}			    
				    
					array_splice($msg_content, $msgKey, 1);
					break;
				}
			}
			if($isblankFound) {
				$user_outFile = '../ChatRoom/user_out.json';
		        // create the file on the server if it doesn't exist
		        if (!file_exists($user_outFile)) {
		            file_put_contents($user_outFile, json_encode($msg_content));
		        }

		        $fp = fopen($user_outFile, 'r');
		        $ch = curl_init();
		        curl_setopt($ch, CURLOPT_USERPWD, $ftp_user.":".$ftp_password);
		        curl_setopt($ch, CURLOPT_URL, 'ftp://162.213.248.101/public_html/chat/user_out.json');
		        curl_setopt($ch, CURLOPT_UPLOAD, 1);
		        curl_setopt($ch, CURLOPT_TIMEOUT, 86400);
		        curl_setopt($ch, CURLOPT_INFILE, $fp);
		        curl_setopt($ch, CURLOPT_NOPROGRESS, false);
		        curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
		        curl_setopt($ch, CURLOPT_INFILESIZE, filesize($user_outFile));
		        curl_exec ($ch);
		        curl_close ($ch);
			}
			
		}
	    //die('STOP');
	    echo json_encode($msg_content);
		break;
	case 'UpdateChat':
		$customer_id = '';
		$new_DataToUpdate = '';
		if(isset($_POST['customer_id']) && $_POST['customer_id'] != '') {
			$customer_id = htmlentities(strip_tags($_POST['customer_id']));
			
			$data = file_get_contents($host."/chat/user_out.json");
		    if ($data === FALSE) {
		        $msg_content = [];
		    } else {
		        $msg_content = json_decode($data, true);
		    }
			if(!empty($msg_content)) {
				foreach($msg_content as $msgKey => $msgRow) {
					if($msgRow['customer_id'] == $customer_id) {
						$new_DataToUpdate = $msgRow;
						array_splice($msg_content, $msgKey, 1);
						break;
					}
				}
				
				$user_outFile = '../ChatRoom/user_out.json';
		        // create the file on the server if it doesn't exist
		        if (!file_exists($user_outFile)) {
		            file_put_contents($user_outFile, json_encode($msg_content));
		        }

		        $fp = fopen($user_outFile, 'r');
		        $ch = curl_init();
		        curl_setopt($ch, CURLOPT_USERPWD, $ftp_user.":".$ftp_password);
		        curl_setopt($ch, CURLOPT_URL, 'ftp://162.213.248.101/public_html/chat/user_out.json');
		        curl_setopt($ch, CURLOPT_UPLOAD, 1);
		        curl_setopt($ch, CURLOPT_TIMEOUT, 86400);
		        curl_setopt($ch, CURLOPT_INFILE, $fp);
		        curl_setopt($ch, CURLOPT_NOPROGRESS, false);
		        curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
		        curl_setopt($ch, CURLOPT_INFILESIZE, filesize($user_outFile));
		        curl_exec ($ch);
		        curl_close ($ch);
		        
		        if(!empty($new_DataToUpdate)) {
		        	$msg = htmlentities(strip_tags($new_DataToUpdate['msg']));
		        	$user = htmlentities(strip_tags($new_DataToUpdate['user']));
				    $ip = htmlentities(strip_tags($new_DataToUpdate['ip']));
				    $location = '';
				    $last_visited = htmlentities(strip_tags($new_DataToUpdate['last_visited']));
				    $device = htmlentities(strip_tags($new_DataToUpdate['device']));
				    $chat_status = htmlentities(strip_tags($new_DataToUpdate['chat_status']));
				    $timestamp = htmlentities(strip_tags($new_DataToUpdate['timestamp']));
				    $message = array("timestamp"=>$timestamp, "user"=>$user, "msg"=>$msg, "customer_id"=>$customer_id);
				    
				    $CustomerFile = '../ChatRoom/userChats/'.$customer_id.'.json';
	        		$file_exists = file_exists($CustomerFile);
	        		
	        		// get current contents of json file
			        if ($file_exists) {
			            $data = json_decode(file_get_contents($CustomerFile), true);
			            // make sure dictionary values aren't empty
			            $data['ip'] = $data['ip'] == "" ? $ip : $data['ip'];
			            $data['location'] = $data['location'] == "" ? $location : $data['location'];
			            $data['last_visited'] = $data['last_visited'] == "" ? $last_visited : $data['last_visited'];
			            $data['device'] = $data['device'] == "" ? $device : $data['device'];
			            $data['user'] = $data['user'] == "" ? $user : $data['user'];
			        } 
			        else {
			            // if first message, set chat_started value from timestamp
			            $data = array(
			            	"chat_start_date"=>$timestamp, 
			            	"ip"=>$ip, "user"=>$user, 
			            	"location"=>$location, 
			            	"last_visited"=>$last_visited, 
			            	"device"=>$device, 
			            	"last_updated"=>$timestamp, 
			            	"customer_id"=>$customer_id
			            );
			            $data['messages'] = [];
			        }
					// always update chat_status, last_updated, last_visited, device, user
			        $data['chat_status'] = $chat_status;
			        $data['last_updated'] = $timestamp;
			        $data['user'] = $data['user'] == "" ? $user : $data['user'];
			        $data['last_visited'] = $last_visited;
			        // $data['device'] = $device;

			        // push new message to message array
			        array_push($data['messages'], $message);
			        $json = json_encode($data, JSON_PRETTY_PRINT);
			        
			        // write data contents to json file
			        file_put_contents($CustomerFile, $json);
				}
			}			
		}
		break;
	default:
		break;
}
function pr($var) {
	$template = php_sapi_name() !== 'cli' ? '<pre>%s</pre>' : "\n%s\n";
	printf($template, print_r($var, true));
}
function writeHistoryLog($saveToHistoryData=null){
	$dateTime = date('Y-m-d H:i:s');
	$ip_address = $_SERVER['REMOTE_ADDR'];
	$browserName = '';
	$browser = getBrowser();
	if(isset($browser['name']) && $browser['name']!=''){
		$browserName = $browser['name'];
		if(isset($browser['version']) && $browser['version']!=''){
			$browserName .= '|'.$browser['version'];
		}
	}
	else {
		$browserName = $_SERVER['HTTP_USER_AGENT'];
	}
	$requestSer = '';
	if(isset($saveToHistoryData) && !empty($saveToHistoryData)){
		$requestSer = serialize($saveToHistoryData);
	}
	$message = '';
	$message .= $dateTime.'|'.$ip_address.'|'.$browserName.'|'.$requestSer;
	$cDate = date('Y-m-d');
	$HistoryLogFile = '../ChatRoom/HistoryLog/'.$cDate.'.txt';	
	$fh = fopen($HistoryLogFile, (file_exists($HistoryLogFile)) ? 'a' : 'w');
	fwrite($fh, $message."\n");
	fclose($fh);
}
function getBrowser() {
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }
   
    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }
   
    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }
   
    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }
   
    // check if we have a number
    if ($version==null || $version=="") {$version="?";}
   
    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}
?>