<?php
/*=======================================================================
 *
 * autoranking_main.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

include_once ("../include/mcglobal.inc.php");
$standalone = "1";  // has to be set before including "ranking.inc.php"
include_once ("../include/ranking.inc.php");
include_once ("../include/inc_autoranking.inc.php");


// if (isRunning(3)):
//   exit();
// endif;

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


// $path = getParameterValue("0", "PATH_DOCROOT", "0");
$dirName = dirname(__FILE__);
$dirName = str_replace("\\", "/", $dirName);
$lastSlashPos = strrpos($dirName,"/");
$path = substr($dirName, 0, $lastSlashPos);


// Get single job for autoranking with the zipcode of the startaddress and other informations
function getLockedCouriersByAutoranking ($limit = "") {
  global $db;
  $retArray = array();
  $limitClause = "";
  if ($limit != "" && is_numeric($limit)) : $limitClause = "LIMIT 0," . $limit; endif;
  $sqlquery = "SELECT cr.cr_id, cr.cr_ar_jb_id FROM courier AS cr WHERE cr.cr_ar_jb_id > '0' ORDER BY cr.cr_ar_jb_id " . $limitClause;
  $result = $db->dbQ($sqlquery);
  while ($row = $result->fetch_assoc()):
        $retArray[] = array($row["cr_id"], $row["cr_ar_jb_id"]);
  endwhile;
  $result->free();
  return $retArray;
}  


// Endless loop
while (TRUE):

  // Set execution time for keepalive
  $currentTime = getDateTime("0");
  updateStmt("keepalive", "ka_process", "autoranking", array("ka_lastexecutiontime", $currentTime),"");


  // *******************
  // *** Assign jobs ***
  // *******************

  // Get next job(s) with status 8 for the specified headquarter (no storno)
  $jobArray = getAutoRankingJobs(40);

  // Loop all jobs (default one)
  $lenJobArray = count($jobArray);
  for ($i = 0; $i < $lenJobArray; $i++) :

      $jobId = $jobArray[$i][0];

      $system_result = "";
      $cmd = "php " . $path . "/include/autoranking_single.php " . $jobId . " >" . $path . "/log/autoranking.stdout+err 2>&1 &";
      $ausgabe = system($cmd, $system_result);

      // Set execution time for keepalive
      $currentTime = getDateTime("0");
      updateStmt("keepalive", "ka_process", "autoranking", array("ka_lastexecutiontime", $currentTime),"");

  endfor;  // Loop all jobs


  // *******************
  // *** Revoke jobs ***
  // *******************

  // Get job(s) to be revoked because timeout
  if (!isset($arRevokeJobModeToggler) || $arRevokeJobModeToggler == "") : $arRevokeJobModeToggler = "1"; else : $arRevokeJobModeToggler = ""; endif;
  $jobArray = getRevokeJobs(40, $arRevokeJobModeToggler);

  $jobArrayLen = count($jobArray);
  if ($jobArrayLen > 0) :

     for ($i = 0; $i < $jobArrayLen; $i++) :

         $jbId = $jobArray[$i][0];
         $currentHqId = $jobArray[$i][1];
         $jbAutoranking = $jobArray[$i][2];

         $logFile = getParameterValue("0", "AUTORANKING_LOGFILE", $currentHqId);
         if ($logFile == "") : writeToFile($logFile, "CONSTANT ERR.: AUTORANKING_LOGFILE [HQ: " . $currentHqId . "]"); endif;

         // Check REVOKING enabled
         $constArRevokingEnabled = getParameterValue("0", "AUTORANKING_REVOCATION_ENABLED", $currentHqId);
         if ($constArRevokingEnabled != "") :
            $constArRevokeJobMode = getParameterValue("0", "AUTORANKING_REVOKE_JOB_MODE", $currentHqId);         
            if (($constArRevokeJobMode == "1" && $jbAutoranking != "1") || ($constArRevokeJobMode == "2" && $jbAutoranking != "0")) :
               $constArRevokingEnabled = "";   // Do NOT revoke the current job (ATTENTION: $constArRevokingEnabled is set !!!)
            endif;
         endif;

         if ($constArRevokingEnabled == '1') :         

            $revokedData = revokeJobFromCourier($jbId);
            if (count($revokedData) > 0) :
               $currentHqId = $revokedData[8];
               
               $crSid = getFieldValueFromId("courier","cr_id",$revokedData[1],"cr_sid");
               $crUsrId = getFieldValueFromId("courier","cr_id",$revokedData[1],"usr_id");

               // UNLOCK courier regarding autoranking process
               updateStmt("courier", "cr_id", $revokedData[1], array("cr_ar_jb_id", "0"), "cr_ar_jb_id = '" . $jbId . "'");

               // Write logdata into log database
               writeToLogDB("8",$currentHqId,$revokedData[0],$crUsrId,$revokedData[1],$crSid,"",
                            "CR_VHT_ID=" . $revokedData[3] . "|JB_VHT_ID = " . $revokedData[4] .
                            "|LOST_RANKING=" . $revokedData[5] . "|JB_STATUS_NEW=" . $revokedData[6] . "|JB_RESERV=" . $revokedData[7]);
            
               // Write logdata into log file
               writeToFile($logFile, "Job " . $revokedData[0] . " revoked from courier " . $revokedData[1] . 
                                     " [SID: " . $crSid . "] [Time: " . $revokedData[2] . "]" .
                                     " [cr.vht_id = " . $revokedData[3] . "] [jb.vht_id = " . $revokedData[4] . "]" .
                                     " [Lost Ranking: " . $revokedData[5] . "]" .
                                     " [Set Status: " . $revokedData[6] . "]" .
                                     " [Reservation: " . $revokedData[7] . "]");
            endif;
         endif;  // AUTORANKING_REVOCATION_ENABLED
     endfor;
  endif;

  // Set execution time for keepalive
  $currentTime = getDateTime("0");
  updateStmt("keepalive", "ka_process", "autoranking", array("ka_lastexecutiontime", $currentTime),"");


  // ********************************************
  // *** Check occupied state of the couriers ***
  // ********************************************
  
  $crArray = getLockedCouriersByAutoranking();
  
  // Loop all jobs (default one)
  $lenCrArray = count($crArray);
  for ($i = 0; $i < $lenCrArray; $i++) :

      $crId = $crArray[$i][0];
      $jbId = $crArray[$i][1];

      $jbFields = getFieldsValueFromId("job", "jb_id", $jbId, array("jb_status","cr_id","cr_id_order"));
      if ( ($jbFields[0] > "0") || ($jbFields[1] != "" && $jbFields[1] != $crId) || ($jbFields[2] != $crId) ) :
         // UNLOCK courier regarding autoranking process
         updateStmt("courier", "cr_id", $crId, array("cr_ar_jb_id", "0"), "cr_ar_jb_id > '0'");
         
         // Write logdata into log file
         // writeToFile($logFile, " Courier UNLOCKED - " . "[CR_ID: " . $crId . "] [JB_ID: " . $jbId . "] [JB_STATUS: " . $jbFields[0] . "] [JB_CR_ID: " . $jbFields[1] . "] [JB_CR_ID_ORDER: " . $jbFields[2] . "]");
      else :
         // Write logdata into log file
         // writeToFile($logFile, " Courier NOT UNLOCKED - " . "[CR_ID: " . $crId . "] [JB_ID: " . $jbId . "] [JB_STATUS: " . $jbFields[0] . "] [JB_CR_ID: " . $jbFields[1] . "] [JB_CR_ID_ORDER: " . $jbFields[2] . "]");
      endif;
  endfor;  // Loop all jobs  

  // Set execution time for keepalive
  $currentTime = getDateTime("0");
  updateStmt("keepalive", "ka_process", "autoranking", array("ka_lastexecutiontime", $currentTime),"");

  sleep(15);

endwhile;  // Endless loop

?>
