<?php

_setView(__FILE__);
_setTitle('Ultimate Support Chat');

check_login();

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

$PDO = PDO_CONNECT();

$limit = 10; $start = (PAGE-1)*$limit; $foundRows = '';

if (isset($_GET['delete_chat_id']) && $_GET['delete_chat_id'] != '' && is_numeric($_GET['delete_chat_id']) && $_SESSION['user']['permissions'] == 1) {

	// Delete chat data
	$command = "DELETE FROM `chats` WHERE `request_id` = '".sql_quote($_GET['delete_chat_id'])."' ";
	$result = $PDO->prepare($command);
	$result->execute();
	
	// Delete chat request
	$command = "DELETE FROM `chat_requests` WHERE `request_id` = '".sql_quote($_GET['delete_chat_id'])."' ";
	$result = $PDO->prepare($command);
	$result->execute();
	
	refresh('/'.$languageURL.'visitors/history');
	
}

if (isset($_POST['bulk_delete']) && $_POST['bulk_delete'] == 1 && $_SESSION['user']['permissions'] == 1){	
		
	if ($_POST['bulk_delete_chat_IDS'] ==  '' ){ // Delete entire history
		
		$command = "SELECT `request_id` FROM `chat_requests` WHERE `end_date` != '0000-00-00 00:00:00'";
		$result = $PDO->prepare($command);
		$result->execute();
	
		$rows = $result->fetchAll(PDO::FETCH_ASSOC);
		foreach ($rows as $row){		
			$chatIDArr[] = "`request_id` = '".sql_quote($row['request_id'])."' ";
		}
		// Delete chat data
		$command = "DELETE FROM `chats` WHERE ".implode(" OR ", $chatIDArr);	
		$result = $PDO->prepare($command);
		$result->execute();
	
		// Delete chat requests
		$command = "DELETE FROM `chat_requests` WHERE `end_date` != '0000-00-00 00:00:00'";
		$result = $PDO->prepare($command);
		$result->execute();
				
	} else { // Delete selected chats	 	
		$rows = explode(',', $_POST['bulk_delete_chat_IDS']);	
		foreach ($rows as $row){		
			$chatIDArr[] = "`request_id` = '".sql_quote($row)."' ";
		}	
		// Delete chat data
		$command = "DELETE FROM `chats` WHERE ".implode(" OR ", $chatIDArr);	
		$result = $PDO->prepare($command);
		$result->execute();	
	
		// Delete chat requests
		$command = "DELETE FROM `chat_requests` WHERE ".implode(" OR ", $chatIDArr);	
		$result = $PDO->prepare($command);
		$result->execute();		
	}
	
	refresh('/'.$languageURL.'visitors/history');
}

if (!isset($_GET['request_id'])) {
	
	if(isset($_POST['search_visitor_history'])){
		$command = "SELECT *, (SELECT COUNT(*) FROM `chat_requests` WHERE `name` LIKE CONCAT('%', :name, '%') AND `end_date` != '0000-00-00 00:00:00') `total_count` FROM `chat_requests` WHERE `name` LIKE CONCAT('%', :name, '%') AND `end_date` != '0000-00-00 00:00:00' ORDER BY `end_date` DESC LIMIT $start,$limit";
		$result = $PDO->prepare($command);
		$result->bindParam(':name', $_POST['history_table_search']);
		$result->execute();
		$rows = $result->fetchAll(PDO::FETCH_ASSOC);
		if (isset($rows[0]['total_count'])){
			$foundRows = $rows[0]['total_count'];
		}	
	}
	else{
		$command = "SELECT *, (SELECT COUNT(*) FROM `chat_requests` WHERE `end_date` != '0000-00-00 00:00:00') `total_count` FROM `chat_requests` WHERE `end_date` != '0000-00-00 00:00:00' ORDER BY `end_date` DESC LIMIT $start,$limit";
	    $result = $PDO->prepare($command);
	    $result->execute();
		$rows = $result->fetchAll(PDO::FETCH_ASSOC);
		if (isset($rows[0]['total_count'])){
			$foundRows = $rows[0]['total_count'];
		}		
	}
    
    foreach ($rows as $row){

        if (isset($row['country_name'])) {
            $row['country_name'] = ucfirst(strtolower($row['country_name']));
        }
        if (isset($row['os'])) {
            $row['os'] = str_replace("_", ".", $row['os']);
        }
        if (isset($row['browser'])) {
            $row['browser'] = preg_replace('/\d+/u', '', $row['browser']);
            $row['browser'] = preg_replace('/[^A-Za-z0-9\-]/', '', $row['browser']);
            $row['browser'] = trim($row['browser']);
        }

        $users[] = $row;
    }
	
    if (isset($users)) {
        foreach ($users as $k => $u) {
            $specific = array('start' => $u['start_date'], 'end' => $u['end_date']);
            $chat_len = getChatDateAndTime('', $specific);
            $users[$k]['chat_length'] = $chat_len['chat_length'];
        }
		
        abr('users', $users);
		abr('paging', paging('/'.$languageURL.'visitors/history'.DELIMITER.'p=', '', PAGE, $limit, $foundRows));		
    }

} else {
	
    $command = "SELECT * FROM chats JOIN chat_requests ON chats.request_id = chat_requests.request_id WHERE chats.request_id = :request_id ORDER BY date ASC";
    $result = $PDO->prepare($command);
    $result->bindParam(':request_id', $_GET['request_id']);
    $result->execute();


    if($result->rowCount() == 0) {
        refresh('/'.$languageURL.'visitors/history');
    }

    $data = array();
	$visitor_email = '';

    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $data['full_array'][] = $row;
		
		if (isset($row['email']) && $row['email'] != ''){
			$visitor_email = $row['email'];
		}
		
        $prefix = 'a';
        if ($row['operator_name'] == '') {
            $row['operator_name'] = 'Support Team';
        }
        $sentBy = $row['operator_name'];
        if ($row['operator_id'] == 0) {
            $prefix = 'u';
            $sentBy = 'Anonymous';
            if ($row['name'] != 'utc_client') {
                $sentBy = $row['name'];
            }
        }

        $date = date_create($row['date']);
        $formated_date =  date_format($date, 'F jS Y, g:ia');
		
		$row['content'] = htmlspecialchars_decode($row['content']);

        $data['history'][] = '<div class="' . $prefix . '_reply"><span class="' . $prefix . '_1"></span><span class="' . $prefix . '_2"><b/>' . $sentBy . '</b></span><span class="' . $prefix . '_3">' . $formated_date . '</span><span class="' . $prefix . '_4">' . replaceEmoticons($row['content']) . '</span></div>';
        $data['operator_id'][] = $row['operator_id'];
    }
	
    $return = getChatDateAndTime($data);

    $data['chat_date'] = $return['chat_date'];
    $data['chat_length'] = $return['chat_length'];


    if (isset($data['full_array'])) {

        foreach ($data['full_array'] as $k => $d) {
			
            if ($k == 0) {
				if(isset($data['full_array'][$k]['uri'])){
					 $data['visitors_path'][] = $data['full_array'][$k]['uri'];
				}             
            } else {				
                if (isset($data['full_array'][$k]['uri']) && $data['full_array'][$k]['uri'] != '' && $data['full_array'][$k]['uri'] != $data['full_array'][$k - 1]['uri']) {
                    $data['visitors_path'][] = $data['full_array'][$k]['uri'];
                }
            }			
        }
		
    }
			
	abr('visitor_email', $visitor_email);	
    abr('data', $data);	
		
	if (isset($_POST['email_transcript']) || isset($_POST['download_transcript'])){
		
		  require_once('email_transcript.php');
		  
		  /* styles */
		  
		  $h4_style = ' style="display: block;-webkit-margin-before: 1.33em;-webkit-margin-after: 1.33em;-webkit-margin-start: 0px;-webkit-margin-end: 0px;font-weight: bold;"';
		  		  		  	  
		  $content = '<div style="margin-bottom:20px; border-bottom:1px solid #666666">			
  	        <h4'.$h4_style.'>Chat Information:</h4>
		    <span>ID: '.$_GET['request_id'].', </span>
  	        <span>Date: '.$data['chat_date'].', </span>
  	        <span>Length: '.$data['chat_length'].'</span>';
			
  			if ($visitor_email != ''){
  				$content .= '<h4'.$h4_style.'>Visitors email:</h4><p>'.$visitor_email.'</p>';
  			}
  				
			if ($data['visitors_path'] != ''){
	  	        $content .= '<h4'.$h4_style.'>Visitors path:</h4>';
	            foreach ($data['visitors_path'] as $i){
					$i = str_replace("http://","",$i);
					$i = str_replace("https://","",$i);					
				  $content .= '<span style="display:block;">'.$i.'</span>';
	            }
			}		
		  $content .= '</div>';
		  $content .= '<h4'.$h4_style.'>Chat Transcript:</h4><br/>';
		  
          foreach ($data['history'] as $i){
 
			  $i = str_replace('class="a_2"','class="a_2" style="color:red;margin-right:10px;color:#000000"',$i);
			  $i = str_replace('class="u_2"','class="u_2" style="color:red;margin-right:10px;color:#000000"',$i);
			  $i = str_replace('class="a_4"','class="a_4" style="display:block;color:#666666"',$i);
			  $i = str_replace('class="u_4"','class="u_4" style="display:block;color:#666666"',$i);
			  
			  if (strpos($i, 'class="usc_emoji_lg"') !== false) {
			  	$i = str_replace('class="usc_emoji_lg"','class="usc_emoji_lg" style="max-width: 20px;width: auto;vertical-align:middle;margin-right:5px;margin-left: 5px;"',$i);
				$i = str_replace('src="//','src="https://',$i);
			  }
			  $content .= $i.'<br/>'; 
          }
		  
		  $footer_content = '<p>Ultimate Support Chat &copy; '.date("Y").'&nbsp;</p>';
		  		  
		  $message = $html.$content.$html2.$footer_content.$html3;
		 
  	  	  if (isset($_POST['email_transcript'])){
			  			  
			  if(trim($_POST['email_addresses']) == '' ){
				  $error[] = 'Please enter a valid email address.';			  			
			  }
			  else{
				  $addressArr = explode(',', $_POST['email_addresses']);
				  foreach ($addressArr as $ad){
			  			if(check_email($ad) == false) {
			  				$error[] = $ad.' is not a valid email address.';
			  			}
				  }
			  }
			  
			  if (isset($error)){
	  				$message = '<ul>';
	  				foreach($error as $e) {
	  					$message .= '<li>'.$e.'</li>';
	  				}
	  				$message .= '</ul>';
	  				addErrorMessage($message, '', 'danger');
			  }
			  else{					  		  	
				  $to = trim($_POST['email_addresses']);
				  $subject = "Chat transcript - ID: ".$_GET['request_id'];
				  $headers = "MIME-Version: 1.0" . "\r\n";
				  $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
				  $headers .= 'From: <zak.soulam@gmail.com>' . "\r\n";
				  mail($to,$subject,$message,$headers);
				  refresh('/'.$languageURL.'visitors/history', 'The chat transcript was emailed', 'success');	
			  }
  	  	  }
		  
	  	  if (isset($_POST['download_transcript'])){	
			  	  
		      $filename = "Chat transcript - ID: ".$_GET['request_id'].".html";
		      header('Content-disposition: attachment; filename=' . $filename);
		      header('Content-type: text/html');
		      print_r($message);
		      die();
			  
	  	}
		 		  
	}
			
}

function getChatDateAndTime($data = '', $specific = '') { // Get chat date and tim//e

    $chatDateArr = array();

    if ($specific == '') {
        foreach ($data['full_array'] as $d) {
            $chatDateArr[] = $d['date'];
        }

        $strStart = $chatDateArr[0];
        $strEnd = end($chatDateArr);
    } else {
        $strStart = $specific['start'];
        $strEnd = $specific['end'];
    }

    $dteStart = new DateTime($strStart);
    $dteEnd = new DateTime($strEnd);
	
    if(version_compare('5.3', phpversion(), '>=')) {	   
   	   $php_early_diff = diff_php_less_then_5_3($strStart, $strEnd);
   	   $chatLength = gmdate("H:i:s", $php_early_diff);
       $return['chat_length'] = $chatLength;	
	   if (isset($chatDateArr) && !empty($chatDateArr)) {
           $dateOnlyArr = explode(' ', $chatDateArr[0]);
           $return['chat_date'] = $dateOnlyArr[0];
       }
       return $return;	   
	}
	else{
		$dteDiff = $dteStart->diff($dteEnd);
	    $lenHourToSec = $dteDiff->h * 60 * 60;
	    $lenMinToSec = $dteDiff->i * 60;
	    $lenSec = $dteDiff->s;

	    $TotalSec = $lenHourToSec + $lenMinToSec + $lenSec;

	    if ($lenHourToSec != 0) {
	        $chatLength = gmdate("H:i:s", $TotalSec);
	    } else {
	        $chatLength = gmdate("i:s", $TotalSec);
	    }

	    $return = array();

	    if (isset($chatDateArr) && !empty($chatDateArr)) {
	        $dateOnlyArr = explode(' ', $chatDateArr[0]);
	        $return['chat_date'] = $dateOnlyArr[0];
	    }

	    $return['chat_length'] = $chatLength;	
	    return $return;
	}
	
}

function diff_php_less_then_5_3($date1, $date2) {
 	$diff = abs(strtotime($date2) - strtotime($date1));
 	$years = floor($diff / (365*60*60*24));
 	$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
 	$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24) / (60*60*24));
 	return $diff;
}


function replaceEmoticons($text) {
		
	//Emoticons
	$emoji['emoticons'] = array(

		':)' => 'happy.png',
		':(' => 'sad.png',
		':P' => 'tongue.png',
		';)' => 'wink.png',
		':x' => 'angry.png',
	
		':|' => 'expressionless.png',
		':D' => 'laugh.png',
		':S' => 'puzzled.png',
		'8-)' => 'cool.png',
		':O' => 'surprised.png',
	
		':asleep:' => 'asleep.png',
		':bashful:' => 'bashful.png',
		':bashfulcute:' => 'bashfulcute.png',
		':bigevilgrin:' => 'bigevilgrin.png',
		':bigsmile:' => 'bigsmile.png',
	
		':bigwink:' => 'bigwink.png',
		':chuckle:' => 'chuckle.png',
		':crying:' => 'crying.png',
		':confused:' => 'confused.png',
		':confusedsad:' => 'confusedsad.png',
	
		':dead:' => 'dead.png',
		':delicious:' => 'delicious.png',
		':depressed:' => 'depressed.png',
		':evil:' => 'evil.png',
		':evilgrin' => 'evilgrin.png',

		':grin:' => 'grin.png',
		':impatient:' => 'impatient.png',
		':inlove:' => 'inlove.png',
		':kiss:' => 'kiss.png',
		':mad:' => 'mad.png',
	
	
		':nerdy:' => 'nerdy.png',
		':notfunny:' => 'notfunny.png',
		'ohrly:' => 'ohrly.png',
		':reallyevil:' => 'reallyevil.png',
		':sarcasm:' => 'sarcasm.png',
	 

		':shocked:' => 'shocked.png',
		':sick:' => 'sick.png',
		':silly:' => 'silly.png',
		':sing:' => 'sing.png',
		':smitten:' => 'smitten.png',
	
		':smug:' => 'smug.png',
		':stress:' => 'stress.png',
		':sunglasses:' => 'sunglasses.png',
		':sunglasses2:' => 'sunglasses2.png',
		':superbashfulcute:' => 'superbashfulcute.png',
	
		':tired:' => 'tired.png',
		':whistle:' => 'whistle.png',
		':winktongue:' => 'winktongue.png',
		':yawn:' => 'yawn.png',
		':zipped:' => 'zipped.png',

	);
	
	
	$codes = array_keys($emoji['emoticons']);
	$images = array_values($emoji['emoticons']);
		
	$tmp = array ();
	foreach ( $images as $k => $v ) {
		$tmp [$k] = '<img class="usc_emoji" style="vertical-align: sub;" src="widget/emoji/img/' . $v . '" alt="emoticon" />';
	}
	
	return str_ireplace ( $codes, $tmp, $text );
}

function check_email($address) {
	return (preg_match ( '/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`{|}~]+' . '@' . '([-0-9A-Z]+\.)+' . '([0-9A-Z]){2,4}$/i', trim ( $address ) ));
}

