<!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;


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

function getTableHud()
{
$db = 'asterisk';
$db_admin = 'asterisk';
$db_password = 'V3WnZYY3';
$con = new mysqli("localhost", $db_admin, $db_password, $db);


$sql = "select concat_ws(name, ifnull(lastname, ''), ' ') as Name, status as Status, call_extension as Ext, call_account as Account, Queues, ";
$sql .= "concat_ws(' ', call_calleridnum, call_calleridname) as Phone, call_did as DID, call_uniqueid as UniqueID, call_date as 'Last Call' ";
$sql .= "from agent ";
$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";
$sql .= " FROM agent a left join extension e on a.call_extension = e.device ";
if (!((isset($_GET['showlogout'])?$_GET['showlogout']:"") == "1"))
    $sql .= " WHERE a.status <> 'LOGOUT' OR a.status = 'LOGOUT' and call_type NOT IN ('UNREACHABLE', 'UNKNOWN', 'LAGGED', '') ";
$sql .= "order by queueid, login";

$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;

while ($field=$result->fetch_field())
if(($field->name!="Division"))
  $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 NYHH Bria Interpreters";
				break;
			case '3':
				$division = "OTP NYHH Operators";
				break;
			 case '4':
                                $division = "OTP NYDOE Operators";
                                break;
			case '5':
				$division = "Coordination";
				break;
			 case '6':
                                $division = "OTP Other Languages";
                                break;
			case '7':
				$division = "Human Resources";
				break;
			case '8':
				$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<11)
            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';


              //gmdate("H:i:s", $_POST['start']);
              //$res .= $schedules[$cell]['start_time']; //['username'];
              //$res .= date("H:i:s", time());
            }
            else
              $res .= $cell;
            $res.= "</td>";
            $col++;
        }
		$res.= "</tr>\n";
		$lastdiv = $division;
	}
$res.= "</table></small>";
return $res;
}
?>
