<!DOCTYPE html>
<?php
/*$initime = microtime(true);
$sysid = ftok(__FILE__, 'h');
$memid = shmop_open($sysid, "c", 0755, 65535);
if (!empty($memid)) {
  $lastupdate = shmop_read($memid, 0, 10);
  if (is_numeric($lastupdate))
  {
    if (time() - $lastupdate > 0)
    {
      echo updateInfo($memid);
    }
    else {
      $hud = shmop_read($memid, 10, 65525);
      $pos = strpos($hud, "<EOF>");
      $hud = substr($hud, 0, $pos);
      echo $hud;
    }
  }
  else {
    echo updateInfo($memid);
  }
} else {
    echo getTableHud();
}
shmop_close($memid);
$lapse = microtime(true) - $initime;*/

	if ($_SERVER['REQUEST_METHOD']=='POST') 
		$input = filter_input_array(INPUT_POST);
	else
		$input = filter_input_array(INPUT_GET);
	$server= strip_tags($input['s']);
	$user = strip_tags($input['user']);

echo getTableHud($user,$server);

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

function getTableHud($user,$server)
{
$db = 'asterisk';
$db_admin = 'asterisk';
$db_password = 'V3WnZYY3';
$con = new mysqli("localhost", $db_admin, $db_password, $db);
$showqueues = "2,3,7,8,9";
//$users = array('sabrinam','doram','mariaa','monicav','noemiy','elizabethdehaan');


$sql = "SELECT concat_ws(' ', name, ifnull(lastname, '')) as Name, REPLACE(REPLACE(REPLACE(call_extension, '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, queueid as Division, e.server";
$sql .= " FROM agent a left join extension e on a.call_extension = e.device WHERE ";
if(empty($user))
$sql .="(queueid IN ({$showqueues}) OR server='".$con->real_escape_string($server)."') AND ";
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";

echo "User is {$user} and Query is<br> $sql";

$title = "Agents status";
$query = $sql;

$schedules = json_decode(file_get_contents('https://mylinguistica.com/tests/schedule.php?action=getalltoday'), true);

//var_dump($schedules);
//$schedules = file_get_contents('https://mylinguistica.com/tests/schedule.php?action=getalltoday');

//$schedules = json_decode(file_get_contents('/tmp/schedules.json'), true);

$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 = array('Division','server');
	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";
        }
        $col = 0;
		foreach($row as $cell) {
            $res.= "<td style=\"padding: 0px;\">";
			if ($col>=0 && $col<12){
				/*if($col==0){
				//$name = $cell;
				if(preg_match('/Elizama Karin/i',$cell)) $cell= str_replace("Elizama Karin", "Ellie", $cell);
				//$cell= str_replace("Elizama Karin", "Ellie", $cell);
				}*/
				if($col==0){
					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);
				}
				if ($col==5) {
				  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;
}
?>
