<!DOCTYPE html>
<?php
	include_once('../token.php');

	/*function mylog($info) {

		$t = microtime(true);
		
		$micro = sprintf("%06d",($t - floor($t)) * 1000000);
		
		$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
		
		$filename = "/var/log/linguistica/debug";
		
		// . date("Ymd") . ".log";
		
		$ipaddr='localhost';
		
		if(isset($_SERVER['REMOTE_ADDR']))
			
			$ipaddr = str_pad($_SERVER['REMOTE_ADDR'], 16);
		
		$rowstart = $d->format("Y/m/d H:i:s.u ") . $ipaddr . ' ' . str_pad(substr($_SERVER["PHP_SELF"], 1), 20) . ' ';
		
		error_log($rowstart . str_replace("\n", "\n" . $rowstart, $info) . "\n", 3, $filename);
		
	}*/

	if ($_SERVER['REQUEST_METHOD']=='POST') 
		$input = filter_input_array(INPUT_POST);
	else
		$input = filter_input_array(INPUT_GET);
	
	$server= strip_tags($input['s']);
	/*if(!empty($input['user']))
		$user = strip_tags($input['user']);*/
	
	function encrypt_decrypt($action, $string) {
		require('/var/www/privatekey.php');
		$output = false;
		$iv= '2017';
		$encrypt_method = "AES-256-CBC";
		$secret_key = $privatekey;
		$secret_iv = $iv;
		//error_log("Data: {$action}|{$string}|{$encrypt_method}|{$secret_key}|{$secret_iv}|");
		$key = hash('sha256', $secret_key);
		$iv = substr(hash('sha256', $secret_iv), 0, 16);
		if( $action == 'encrypt' ) {
			$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
			$output = base64_encode($output);
		}
		else if( $action == 'decrypt' ){
			$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
		}
		return $output;
	}
	$user=''; $nuser='';
	if(!empty($input['user'])) {
		$nuser = $input['user'];
		$user = encrypt_decrypt('decrypt', $input['user']);
		//error_log("User is "  . $user);
	}
	
	$nisagent=''; $isagent=0;
	//if($user=='mlara') echo "<br><br>Is Agent via Input: {$input['a']}";
	if(!empty($input['a'])) {
		$nisagent= $input['a'];
		$isagent = encrypt_decrypt('decrypt', $input['a']);
		//if($user=='mlara') echo "<br><br>Is Agent Decrypt: {$isagent}";
		//error_log("is Agent"  . $isagent);
	}
	
	echo getTableHud($user,$server,$isagent);

	function updateInfo($memid) {
		$lastupdate = "" . time();
		$hud = getTableHud ();
		shmop_write($memid, $lastupdate, 0);
		shmop_write($memid, $hud . "<EOF>", 10);
		return $hud;
	}

	function getTableHud($user,$server,$isagent) {
		$db = 'asterisk';
		$db_admin = 'asterisk';
		$db_password = 'V3WnZYY3';
		$con = new mysqli("localhost", $db_admin, $db_password, $db);
		$showqueues = "2,3,7,8,9";
		
		
		$con->query("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;");
		$sql = "SELECT concat_ws(' ', name, ifnull(lastname, '')) as Name, REPLACE(REPLACE(REPLACE(REPLACE(call_extension, 'PJSIP/', ''),'SIP/',''), 'Local/', ''), '@landagents', '') as Ext, ";
		$sql .= "case when a.status in ('IDLE', 'UNKNOWN') and length(call_extension)<10 then case e.status  when 'OK' then 'IDLE' else IFNULL(e.status, 'NOEXIST') end else a.status end as Status, ";
		$sql .= "timediff(now(), call_date) as 'Time', call_type as 'Call Type', ";
		$sql .= "login as Schedule, concat_ws(' ', call_calleridnum, call_calleridname) as CallerID, call_did as DID, call_uniqueid as UniqueID, IF(othlangs IS NULL, TRIM(queues),CONCAT(TRIM(queues),' Other Languages: ',othlangs)) AS Qeues, rt as RT, if(e.server='2', 'NYDOE',if(e.server='3', 'NYHH Spanish',if(e.server='4', 'Administrative',if(e.server='5', 'NYDOE I',if(e.server='6', 'NYDOE II',if(e.server='8', 'Phone App',if(e.server='1', 'Main',IF(e.server='7', 'NYDOE III','Unknown')))))))) as 'T. System',queueid as Division ";
		$sql .= " FROM agent a left join extension e on a.call_extension = e.device WHERE ";
		
		if (!((isset($_GET['showlogout'])?$_GET['showlogout']:"") == "1"))
			$sql .= " a.status <> 'LOGOUT' OR a.status = 'LOGOUT' and call_type NOT IN ('UNREACHABLE', 'UNKNOWN', 'LAGGED', '') ";
		$sql .= "order by queueid, login";
		$colagent=0;
		$colschedule=5;
		$coltotal=11;
		//$arrusers = array('mlara','noemiy','sebastianochoa','alejandrocb','pablod','joseem','dianaelizalde','martinperez','raymondhsu','RaymondHsu','mariaa','marcohernandez','alejandroh','walterc','FZepeda','Gabrielag','MarianaR','Danielgonzalez','Dianade','anagarcia','Danielhidalgo','anafu');

		$arrusers = array("danielgonzalez","smolina","danielhidalgo","admin","sabrinam","doram","mlara","mariaa","noemiy","walkerc","leobardoz","guisellef","alejandrocb","anafu","marcohernandez","dianaelizalde","pablod","magdaramirez","rebecap","almagarcia","joseem", "raymondhsu","alejandroh","leslienavarro","sarafranco","lfernanda","andresj","sebastianochoa","walterc","fzepeda","gabrielag","marianar","danielgonzalez","dianade","anagarcia","martinperez","sandrak","gonzalom","erikacastillo","MHernande4","sergiomeza","hectorlarios","OFrancisc"); 

		if(in_array(strtolower($user),$arrusers))

			$isagent=1;
			
		//if($user=='mlara') echo "<br><br>Is Agent for show logout: {$isagent}";
		if($isagent==1) {
		//if(in_array(strtolower($user),$arrusers)) {
			$coltotal=13;
			/*$user = encrypt_decrypt('encrypt', $user);
			$user = encrypt_decrypt('encrypt', $user);*/
			$colagent=1;	
			$colschedule=6;
				$sql="SELECT CASE WHEN a.status NOT IN ('IDLE','CALL') AND (f.state IN ('UNKNOWN','UNREACHABLE','LAGGED') OR f.state IS NULL) THEN CONCAT('<a href=\"javascript:popUp(\'poplogout.php?a=$user&u=',login,'&status=',a.status,'&reason=',call_type,'\')\">Logout</a>') END AS 'Action', ";
				
			$sql="SELECT CONCAT('<a href=\"javascript:popUp(\'poplogout.php?a=$user&u=',login,'&status=',a.status,'&reason=',call_type,'\')\">Logout</a>') AS 'Action', ";
			$sql .=" CONCAT_WS(' ', NAME, IFNULL(lastname, '')) AS 'Agent', REPLACE(REPLACE(REPLACE(REPLACE(call_extension, 'PJSIP/', ''),'SIP/',''), 'Local/', ''), '@landagents', '') AS Ext, CASE WHEN a.status IN ('IDLE', 'UNKNOWN') AND LENGTH(call_extension)<10 THEN CASE e.status  WHEN 'OK' THEN 'IDLE' ELSE IFNULL(e.status, 'NOEXIST') END ELSE a.status END AS 'Status',TIMEDIFF(NOW(), call_date) AS 'Time', call_type AS 'Call Type', login AS SCHEDULE, CONCAT_WS(' ', call_calleridnum, call_calleridname) AS CallerID, call_did AS DID, call_uniqueid AS UniqueID, IF(othlangs IS NULL, TRIM(queues),CONCAT(TRIM(queues),' Other Languages: ',othlangs)) AS Qeues, rt AS RT, if(e.server='2', 'NYDOE',if(e.server='3', 'NYHH Spanish',if(e.server='4', 'Administrative',if(e.server='5', 'NYDOE I',if(e.server='6', 'NYDOE II',if(e.server='8', 'Phone App',if(e.server='1', 'Main',IF(e.server='7', 'NYDOE III','Unknown')))))))) as 'T. System', queueid AS Division, IF(e.server=8,IF(a.status='IDLE','','Disconnect'),IF(f.state='OK','','Disconnected')) AS extstate, IF(e.server=8,IF(a.status='IDLE','OK',''),f.state) AS state FROM agent a LEFT JOIN extension e ON a.call_extension = e.device LEFT JOIN extension_state f ON e.device = f.extension WHERE a.status <> 'LOGOUT' OR a.status = 'LOGOUT' AND call_type NOT IN ('UNREACHABLE', 'UNKNOWN', 'LAGGED', '') ORDER BY queueid, login;";
		}

		//mylog("$user Query Agent Status: " . $sql);

		$title = "<h2 class=\"text-center\"><strong>Agents Status</strong></h2>";
		$query = $sql;
		$con->query("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");

		$res = "";
		$res.= "<h3>" . $title . ":</h3><hr>";
		$res.= "<small><table class=\"table table-striped table-condensed table-bordered\">";
		$result = $con->query($query)
			or die($query . "<br>" . $con->error);
		$fields_num = $result->field_count;
		$fieldnoshow = ['Division','extstate','state'];
		if($coltotal==11)
			array_push($fieldnoshow,'T. System');
			while ($field=$result->fetch_field())
			if(!in_array($field->name,$fieldnoshow))
				$res.= "<th style=\"padding: 2px;\">{$field->name}</th>";
				$res.= "</tr>\n";
			while($row = $result->fetch_assoc()) {
				$division = $row['Division'];
				switch ($division){
					case '1':
						$division = "OTP Spanish ONLY";
						break;
					case '2':
						$division = "OTP Other Languages";
						break;
					case '3':
						$division = "OTP NYHH Bria Interpreters";
						break;
					case '4':
						$division = "OTP NYHH Spanish Bria Interpreters";
						break;
					case '5':
						$division = "OTP NYHH Operators";
						break;
					case '6':
						$division = "OTP NYDOE Operators";
						break;
					case '7':
						$division = "Coordination";
						break;
					case '8':
						$division = "Human Resources";
						break;
					case '9':
						$division = "Other Status";
						break;
					default:
						$division = "";
						break;
				}
				if($division!=$lastdiv){
					$res .= "<tr><td colspan='10' style='text-align:center;'><p class='text-info' align='center'><strong>$division</strong></p></td></tr>";
				}
				switch ($row['Status']){
					case "LOGOUT":
					case "UNKNOWN":
						$res.= "<tr class=\"danger\">";
						break;
					case "IDLE":
						$res.= "<tr class=\"active\">";
						break;
					case "CALL":
						$res.= "<tr class=\"success\">";
						break;
					case "RING":
						$res.= "<tr class=\"warning\">";
						break;
					default:
						$res.= "<tr class=\"info\">\n";
				}
				if($row['extstate']=='Disconnected')
					$res.= "<tr class=\"danger\">";
				$col = 0;
				foreach($row as $cell) {
					$res.= "<td style=\"padding: 0px;\">";
					if ($col>=0 && $col<$coltotal){
						if($col==$colagent){
							if(preg_match('/Elizama Karin/i',$cell)) 
								$cell= str_replace("Elizama Karin", "Ellie", $cell);
							$arrname = explode(" ", trim($cell));
							if(count($arrname)>2)
								$cell = $arrname[0]. " " . $arrname[1] . " " . substr($arrname[2],0,1);
							if(count($arrname)<3)
								$cell = $arrname[0] . " " . substr($arrname[1],0,1);
								$cell .= " {$row['extstate']}";
						}
						if ($col==$colschedule) {
						  if (count($schedules[$cell])>0)
							switch ($row['Status']) {
							  case 'LOGOUT':
								$periodnow = floor((time() - strtotime("today"))/900);
								if ( $row['Call Type'] == 'Break' )
								  if (floor(strtotime('1970-01-01 ' . $schedules[$cell]['break_one'] . 'GMT') / 900) != $periodnow
									&& floor(strtotime('1970-01-01 ' . $schedules[$cell]['break_two'] . 'GMT') / 900) != $periodnow)
									if (floor(strtotime('1970-01-01 ' . $schedules[$cell]['break_one'] . 'GMT') / 900) > $periodnow )
									  $res .= 'Break 1 at ' . $schedules[$cell]['break_one'];
									else
									  $res .= 'Break 2 at ' . $schedules[$cell]['break_two'];

								if ( $row['Call Type'] == 'Lunch' )
								  if (floor(strtotime('1970-01-01 ' . $schedules[$cell]['meal'] . 'GMT') / 900) != $periodnow
									&& floor(strtotime('1970-01-01 ' . $schedules[$cell]['meal'] . 'GMT') / 900)+1 != $periodnow )
									$res .= 'Lunch at ' . $schedules[$cell]['meal'];
								break;

							  default:
								if ($schedules[$cell]['start_time'] > date("H:i:s", time()) || $schedules[$cell]['end_time'] < date("H:i:s", time()))
								  $res .= 'NOT SCHEDULED';
								}
						  else
							$res .= 'NOT SCHEDULED';
						  if($schedules[$cell]['start_time']!='00:00:00' && strlen($schedules[$cell]['start_time'])!=0)
							$res .= '<br>Shift: ' . substr($schedules[$cell]['start_time'],0,5).'-' . substr($schedules[$cell]['end_time'],0,5);
						} else
							$res .= $cell;
					$res.= "</td>";
					$col++;
					}
				}
				$res.= "</tr>\n";
				$lastdiv = $division;
			}
			$res.= "</table></small>";
			return $res;
	}
?>
