<?php
/*=======================================================================
 *
 * autoranking_single.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");


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


// Get current job ID from the argument
$jobId = trim($argv[1]);

// Define constants
define("TA_STATUS", "1");


// Get single job for autoranking with the zipcode of the startaddress and other informations
function getSingleAutoRankingJob ($jobId) {
  global $db, $logFile;
  $retArray = array();

  $currentTime = getDateTime("0");

  
  $sqlquery = "SELECT jb.jb_id, jb.hq_id, jb.hq_id_dispo, ad.ad_zipcode, jb.jb_reserv, jb.jb_permanent, jb.cr_id_order, srvpt.srvpt_traveltime, jb.jb_globaljob"
            . " FROM tour AS tr, address AS ad LEFT JOIN serviceplz AS srvp ON ad.ad_zipcode = srvp.srvp_plz LEFT JOIN serviceplztraveltime AS srvpt ON srvp.srvp_id = srvpt.srvp_id, job AS jb"
            . " WHERE jb.jb_id = '" . $jobId . "'                   AND"
            . "       jb.jb_status = '8'                            AND"
            . "       (ISNULL(jb.jb_storno) OR jb.jb_storno = '0')  AND"
            . "       (jb.jb_globaljob != '1')                      AND"
            . "       ( (ISNULL(jb.jb_reserv) OR jb.jb_reserv = '0')  OR"
            . "         (jb_globaljob = '2' AND jb.jb_reserv = '1')   OR"
            . "         (jb.jb_reserv = '1' AND "
            . "           DATE_SUB(jb.jb_ordertime, INTERVAL GREATEST(srvpt.srvpt_traveltime,30) MINUTE) <= '" . $currentTime . "') ) AND"
            . " jb.jb_id = tr.jb_id                                          AND"
            . " tr.tr_sort = 1                                               AND"
            . " tr.ad_id = ad.ad_id                                          AND"
            . " (srvpt.hq_id = jb.hq_id_dispo OR srvpt.hq_id IS NULL)";

  $result = $db->dbQ($sqlquery);
  while ($row = $result->fetch_assoc()):
        // $retArray = array($row["jb_id"], $row["ad_zipcode"], $row["jb_reserv"], $row["jb_permanent"], $row["cr_id_order"], $row["hq_id"], $row["jb_globaljob"]);
        $retArray = array($row["jb_id"], $row["ad_zipcode"], $row["jb_reserv"], $row["jb_permanent"], $row["cr_id_order"], $row["hq_id_dispo"], $row["jb_globaljob"]);
  endwhile;
  $result->free();
  return $retArray;
}  

if ($jobId != "") :

   // Define assign status values for RANKING and LOG
   $assignStatusDefine[0]  = "ASSIGN_STATUS=RESERVED";
   $assignStatusDefine[1]  = "ASSIGN_STATUS=FAVOURED";
   $assignStatusDefine[2]  = "ASSIGN_STATUS=AREA";
   $assignStatusDefine[3]  = "ASSIGN_STATUS=NEIGHBOUR_AREA";
   $assignStatusDefine[4]  = "ASSIGN_STATUS=NEIGHBOUR_AREA_2";
   $assignStatusDefine[5]  = "ASSIGN_STATUS=NEIGHBOUR_AREA_3";
   $assignStatusDefine[6]  = "ASSIGN_STATUS=NEIGHBOUR_AREA_4";
   $assignStatusDefine[7]  = "ASSIGN_STATUS=NEIGHBOUR_AREA_5";
   $assignStatusDefine[8]  = "ASSIGN_STATUS=NEIGHBOUR_AREA_6";
   $assignStatusDefine[9]  = "ASSIGN_STATUS=NEIGHBOUR_AREA_7";
   $assignStatusDefine[10] = "ASSIGN_STATUS=NEIGHBOUR_AREA_8";
   $assignStatusDefine[11] = "ASSIGN_STATUS=NEIGHBOUR_AREA_9";


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


   // *************************
   // *** Assign single job ***
   // *************************

   // Get next job(s) with status 8 for the specified headquarter (no storno)
   $jobArray = getSingleAutoRankingJob($jobId);
   $lenJobArray = count($jobArray);

   if ($lenJobArray > 0) :
       
       // Initialization (important at this place only)
       $status = "";
       $enterRankingLists = TRUE;
   
       // $jobId = $jobArray[$i][0];
       $zipcode = $jobArray[1];
       $jobReserv = $jobArray[2];
       $jobPermanent = $jobArray[3];
       $jobCrIdOrder = $jobArray[4];
       $currentHqId = $jobArray[5];
       $jobGlobal = $jobArray[6];

       // Check AUTORANKING enabled
       $constArAssignmentEnabled = getParameterValue("0", "AUTORANKING_ASSIGNMENT_ENABLED", $currentHqId);
       if ($constArAssignmentEnabled == '1') :

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

          $logDebug = false;
          $parLogDebug = getParameterValue("0", "AUTORANKING_DEBUG_LOG", $currentHqId);
          if ($parLogDebug == "") : $parLogDebug = getParameterValue("0", "AUTORANKING_DEBUG_LOG", "0"); endif;
          if ($parLogDebug == "1") : 
             $logDebug = true;
             writeToFile($logFile, "AUTORANKING_DEBUG ENABLED!");
          endif;

          // Get the general mediation mode for the headquarter
          $mediationMode = getParameterValue("0", "MODE_INTERMEDIATION", $currentHqId);
          if ($mediationMode == "") : writeToFile($logFile, "CONSTANT ERR.: MODE_INTERMEDIATION [HQ: " . $currentHqId . "]"); endif;
          if ($mediationMode == "") : $mediationMode = getFieldValueFromId("headquarters", "hq_id", $currentHqId, "hq_invmode"); endif;

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

          // Get neighbour level for the number of neighbour areas of an area
          $neighbourLevel = "";
          if ($mediationMode == "3") :    // Currently set level ONLY if mediation area is combined mode
             $neighbourLevel = 3;
             if ($constNeighbourLevelPar != "" && is_numeric($constNeighbourLevelPar)) :
                $neighbourLevel = $constNeighbourLevelPar;
             endif;
          endif;

          // Check PDA locating enabled
          $locatingByPDA = getPDALocatingStatus($currentHqId);

          // Check customer regarding behavior according to (ONLY) favoured couriers
          $jobCsOnlyCrFavoured = getCustomerNeedsOnlyFavouredCouriers($jobId, $currentHqId);


          // If job is a reservation (or permanent) try to assign courier associated in $jobCrIdOrder, if $jobCrIdOrder is not empty
          if ($status == "" && ($jobReserv == "1" || $jobPermanent == "1") && ($jobCrIdOrder != "" && $jobCrIdOrder != "0")) :
             $status = assignCourierToJob($jobId, array($jobCrIdOrder), "1", "0", "0", "1", $zipcode);    // 0 = "ASSIGN_STATUS=RESERVED"
             $enterRankingLists = FALSE;    // Do not continue association because no other courier may take the job => Set jb_status = "9" directly
          endif;

          if ($enterRankingLists) :

             // Get number of iterations per AREA
             $constArNumOfIter = getParameterValue("0", "AUTORANKING_NUMBER_OF_ITERATIONS", $currentHqId);
             // Trace potential errors
             if ($constArNumOfIter == "" || $constArNumOfIter == "0") : 
                writeToFile($logFile, "CONSTANT ERR.: AUTORANKING_NUMBER_OF_ITERATIONS");
                $constArNumOfIter = 2;  // Default value of iterations of each AREA
             endif;

             // Get list of the favoured couriers
             if ($status == "") :

                // Check locating has to be activated because favoured have to be located explicitly by job defined in GDC
                $gdcJbIgnoreFavOnly = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jobId . "' AND gdc_gen_fieldname = 'jb_ignore_fav_only'");
                if ($gdcJbIgnoreFavOnly == "" || $gdcJbIgnoreFavOnly != "1") :
             
                   // Check for filter that only all couriers inside the areas will be involved
                   $constRankingFavCrAreaRestriction = getParameterValue("0", "RANKING_FAVOURED_COURIER_AREA_RESTRICTION", $currentHqId);
                   for ($iter = 0; $iter < $constArNumOfIter; $iter++) :
                       if ($constRankingFavCrAreaRestriction == "1") :
                          $favouredCourierArray = getCourierByRanking($zipcode, "0000000100", $jobId, "", $currentHqId);
                       else :
                          $favouredCourierArray = getCourierByRanking($zipcode, "0010000000", $jobId, "", $currentHqId);
                       endif;
                       // Check locating has to be activated because favoured have to be located explicitly by job defined in GDC
                       $tmpLocatingByPDA = "0";
                       /*
                       if ($locatingByPDA != "0") :
                          if ($gdcJbIgnoreFavOnly == "1") :
                             $tmpLocatingByPDA = $locatingByPDA;
                          endif;
                       endif;
                       */
                       $status = assignCourierToJob($jobId, $favouredCourierArray[2], "1", "1", $tmpLocatingByPDA, "0", $zipcode);    // 1 = "ASSIGN_STATUS=FAVOURED"
                       if ($status != "") : break; endif;
                   endfor;
                endif;
             endif;

             // Do NOT enter if customer needs ONLY FAVOURED couriers ("0" = normal mode, "1" = only favoured couriers) and
             // do NOT enter if the job is a potential global job ($jobGlobal = "2") to be converted into a real global job
             if ($jobCsOnlyCrFavoured == "0" && $jobGlobal != "2") :

                // Get list of the current mediation area
                if ($status == "") :
                   // Without blocked couriers
                   for ($iter = 0; $iter < $constArNumOfIter; $iter++) :
                       $currentAreaCourierArray = getCourierByRanking($zipcode, "0101000000", $jobId, "", $currentHqId);
                       $status = assignCourierToJob($jobId, $currentAreaCourierArray[3], "", "2", $locatingByPDA, "0", $zipcode);    // 2 = "ASSIGN_STATUS=AREA"
                       if ($status != "") : break; endif;
                   endfor;
                endif;

                // Get list of the neighbour mediation areas
                if ($neighbourLevel == "") :
                   if ($status == "") :
                      // Without blocked couriers
                      for ($iter = 0; $iter < $constArNumOfIter; $iter++) :
                          $currentAreaCourierArray = getCourierByRanking($zipcode, "0100100000", $jobId, "", $currentHqId);
                          $status = assignCourierToJob($jobId, $currentAreaCourierArray[4], "", "3", $locatingByPDA, "0", $zipcode);    // 3 = "ASSIGN_STATUS=NEIGHBOUR_AREA"
                          if ($status != "") : break; endif;
                      endfor;
                   endif;
                else :
                   if ($status == "") :
                      for ($nl = 1; $nl <= $constNeighbourLevelPar; $nl++) :
                          for ($iter = 0; $iter < $constArNumOfIter; $iter++) :
                              $currentAreaCourierArray = getCourierByRanking($zipcode, "0100100000", $jobId, $nl, $currentHqId);
                              $status = assignCourierToJob($jobId, $currentAreaCourierArray[4], "", ($nl + 2), $locatingByPDA, "0", $zipcode);   
                              if ($status != "") : break 2; endif;
                          endfor;
                      endfor;
                   endif;
                endif;
             endif;
          endif;

          // Update job for setting to jb_status = '9' because job could not be arbitrated by autoranking
          if ($status == "") :

             // Get status of resetting the cr_sid or not according to be displayed in list with jb_status = '9' (ONLY for reservations or permanent jobs)
             $constRankingNoResetCrSid = "";
             if ($jobReserv == "1" || $jobPermanent == "1") :
                $constRankingNoResetCrSid = getParameterValue("0", "RANKING_NORESET_CRSID", $currentHqId);
             endif;

             // Update current timestamp
             $currentTime = getDateTime("0");

             if ($jobGlobal == "2") :
                // Job is a potential global job and has to be converted into a real global job
                if ($constRankingNoResetCrSid == "1") :
                   $res = updateStmt("job", "jb_id", $jobId, array("jb_status", "0", "jb_global", "1"), "jb_status = '8'");
                else :
                   $res = updateStmt("job", "jb_id", $jobId, array("jb_status", "0", "jb_global", "1", "cr_sid", ""), "jb_status = '8'");
                endif;

                if ($db->affected_rows > 0) :
                   // Write logdata into log database
                   writeToLogDB("12",$currentHqId,$jobId,"","","","","CONVERTED_INTO_A_REAL_GLOBAL_JOB");
                    
                   // Write logdata into log file
                   writeToFile($logFile, "Job " . $jobId . " CONVERTED INTO A REAL GLOBAL JOB! [Time: " . $currentTime . "]");
                endif;
             else :
                if ($constRankingNoResetCrSid == "1") :
                   $res = updateStmt("job", "jb_id", $jobId, array("jb_status", "9"), "jb_status = '8'");
                else :
                   $res = updateStmt("job", "jb_id", $jobId, array("jb_status", "9", "cr_sid", ""), "jb_status = '8'");
                endif;
   
                if ($db->affected_rows > 0) :
                   // Write logdata into log database
                   writeToLogDB("12",$currentHqId,$jobId,"","","","","NOT_ASSOCIATED_PER_AUTORANKING");
   
                   // Write logdata into log file
                   writeToFile($logFile, "Job " . $jobId . " NOT ASSOCIATED! [Time: " . $currentTime . "]");
                endif;
             endif;
          endif;
       endif;  // AUTORANKING_ASSIGNMENT_ENABLED
   endif;
endif;

?>
