<?php

/*=======================================================================
 *
 * logout_cr_by_autorevokes.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/


include_once ("../include/mcglobal.inc.php");


if (!isset($argv[1]) || $argv[1] == "") :
   $isCron = false;
   include_once ("../include/auth.inc.php");
   getSecHttpVars("1",array("f_act", "crId"));
   $usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "0";
   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
   authCheckEmployeeRights($emp_id, "1", "1");
else :
   // Init parameters
   $f_act = "";
   $title = ""; 
   $isCron = true;
   if ($argv[1] != "acapella7890") : 
      die("Aborted by wrong password!");
   endif;
   // if ($autoMode) :
   //    if (isset($argv[2]) && $argv[2] != "") : $csId = $argv[2]; endif;
   // endif;
endif;

// Set timezone
// date_default_timezone_set('Europe/Berlin');

// Execution-Time for script
set_time_limit(90);


/*
3 	job 	accepted_courier 	Kurierannahme
8 	job 	revoked_autom 	Automatisch entzogen
11 	job 	cancelled_man 	Abgelehnt

INTEGER IN DB FIELD ONLY => REGEXP ('^[0-9]+$')
DECIMAL IN DB FIELD ONLY => ('^[0-9]*[.]?[0-9]+$')

SELECT 
    cr.cr_id,
    cr.cr_eid,
    log.logo_id,
    COUNT(*) AS num,
    cr.cr_availabletime,
    cr.cr_occupied,
    cr.cr_logintime    
  FROM
    phoenix.courier AS cr,
    phoenix_log.log AS log
  WHERE
    cr.cr_available = '1' AND
    cr.hq_id = '3' AND
    cr.cr_locationzipcode REGEXP ('^[0-9]+$') AND
    log.cr_id = cr.cr_id AND
    log.log_createtime >= DATE_SUB(NOW(), INTERVAL 30 MINUTE) AND
    log.logo_id IN (3,8,11)
  GROUP BY
    cr.cr_id, log.logo_id
  ORDER BY cr.cr_id, log.logo_id
*/

$sqlquery = "SELECT 
               cr.cr_id,
               cr.cr_eid,
               cr.hq_id,
               log.logo_id,
               COUNT(*) AS num,
               cr.cr_availabletime,
               cr.cr_occupied,
               cr.cr_logintime    
             FROM
               phoenix.courier AS cr,
               phoenix_log.log AS log
             WHERE
               cr.cr_available = '1' AND
               cr.hq_id = '3' AND
               cr.cr_locationzipcode REGEXP ('^[0-9]+$') AND
               log.cr_id = cr.cr_id AND
               log.log_createtime >= DATE_SUB(NOW(), INTERVAL 30 MINUTE) AND
               log.logo_id IN (3,8,11)
             GROUP BY
               cr.cr_id, log.logo_id
             ORDER BY cr.cr_id, log.logo_id";
// echo $sqlquery . "<br><br>";

$outData = "";
$crIdArray = array();
$crEidArray = array();
$crHqIdArray = array();
$remCrId = "";
$crLogArray = array();

if ($sqlquery != "") :
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   while ($row = $result->fetch_assoc()):
         $crId = $row["cr_id"];
         $crEid = $row["cr_eid"];
         $hqId = $row["hq_id"];
         $logoId = $row["logo_id"];
         $num = $row["num"];
         
         if ($remCrId != $crId) :
            $crIdArray[] = $crId;
            $crEidArray[$crId] = $crEid;
            $crHqIdArray[$crId] = $hqId;
         endif;
         $remCrId = $crId;
         
         $crLogArray[$crId][$logoId] = $num;
   endwhile;
   $result->free();

   // Current timestamp
   $currentTime = getDateTime("0");
   $execTimelimit = getDateTime("datetime_plus_offset", array(0,16,0,0,0,0), $formatStr = "Y-m-d H:i:s");

   $crIdArrayLen = count($crIdArray);
   for ($i = 0; $i < $crIdArrayLen; $i++) :
       $crId = $crIdArray[$i];

       // Check courier is occupied
       $crIsOccupied = crIsOccupied($crId);
       
       if (!$crIsOccupied && 
           ($crLogArray[$crId]["3"] == "" || $crLogArray[$crId]["3"] == "0") &&
           ($crLogArray[$crId]["11"] == "" || $crLogArray[$crId]["11"] == "0") &&
           ($crLogArray[$crId]["8"] != "" && $crLogArray[$crId]["8"] >= "2")) :

           // For output only
           $outData .= $crEidArray[$crId] . ($isCron ? "    " : "&nbsp;&nbsp;&nbsp;&nbsp;") . $crLogArray[$crId]["8"] . ($isCron ? "\n" : "<br>");

           // Update availability status
           updateStmt("courier","cr_id",$crId,array("cr_availabletime",$currentTime,"cr_locationzipcode","LOGOUT"));
           
           // Insert PDA command to quit application
           insertPDACommand($crHqIdArray[$crId], $crId, "2", "1", "", $currentTime, $execTimelimit);
           
           // Write logdata into log database            
           writeToLogDB("143",$crHqIdArray[$crId],"","0",$crId,"","","STATUS_LOGOUT=PDA-LOGOUT DURCH AUTOREVOKES");
       endif;
   endfor;
endif;

?>

<?php if (!$isCron) : ?>

<html>
<head>
</head>
<body>
  <?php echo $outData; ?>
</body>
</html>

<?php else : ?>

<?php echo $outData; ?>

<?php endif; ?>