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

include_once ("../include/mcglobal.inc.php");
// include_once ("../include/auth.inc.php");
include_once ("../include/inc_filters.inc.php");
include_once ("../include/inc_vehicle.inc.php");



$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
   $isCron = false;
   include_once ("../include/auth.inc.php");

   getSecHttpVars("1",array("crvhId"));
   $autoMode = true;
   $usrAccessArray["hq"] = "1";
   $usrAccessArray["cs"] = "1";
   $usrAccessArray["cr"] = "1";
   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
else :
   // Init parameters
   $crvhId = "";
   $isCron = true;
   if ($argv[1] == "tornado") : $autoMode = true; endif;
   if ($autoMode) :
      if (isset($argv[2]) && $argv[2] != "") : $crvhId = $argv[2]; endif;
   endif;
endif;

if ($crvhId != "" && is_numeric($crvhId)) :

   // Execution-Time for script
   set_time_limit(0);
   
   // Activate buffering
   ob_start();
   
   // Current day
   $numOfDays = 60;
   $selDay = getDateTime("day");
   $selMonth = getDateTime("month");
   $selYear = getDateTime("year");

   $hourTimeUnits = 6;   // Time units of a hour (e.g. 12 units per 5 minutes <=> 6 units per 10 minutes <=> one hour)


   // Remove all entries older than a week
   /*
   $deleteToDate = getDateTime("format", array(0,0,0,$selMonth,$selDay - 30,$selYear), "Y-m-d");
   deleteStmt("vehicleavailability","vha_day < '" . $deleteToDate . "'");
   $vhaIdMin = getMinOfField("vehicleavailability", "vha_id", "");
   deleteStmt("vehicleavailabilitytimeunits","vha_id < '" . $vhaIdMin . "'");
   deleteStmt("vehicledisposition","LEFT(vhd_timeslot, 10) < '" . $deleteToDate . "'");
   */


   // Generate date array
   $dateArray = array();
   for ($k = 0; $k < $numOfDays; $k++) :
       $dateArray[] = getDateTime("format", array(0,0,0,$selMonth,$selDay + $k,$selYear), "Y-m-d");
   endfor;

   // Get customers belonging to meta customer
   /*
   $csIdMetaArray = array("16537", "14975");
   $csIdArray = getColVectorFromDB2ArrayByClause("customer", "cs_id", "cs_id_parent IN (" . implode(",", $csIdMetaArray) . ")", "", "", "");
   $csIdArrayLen = count($csIdArray);
   */
   // Get ALL customers (of ALL headquarters AND ALL mandators) belonging to the "STATIC" groups !!!!
   /*
   $sqlquery = "SELECT cs.cs_id"
             . "  FROM customer AS cs, company AS cmp"
             . "  WHERE (cs.cs_group LIKE '%,101,%' OR cs.cs_group LIKE '%,102,%' OR cs.cs_group LIKE '%,103,%' OR cs.cs_group LIKE '%,104,%' OR cs.cs_group LIKE '%,105,%' OR cs.cs_group LIKE '%,106,%' OR cs.cs_group LIKE '%,107,%' OR cs.cs_group LIKE '%,108,%' OR"
             . "         cs.cs_group LIKE '%,109,%' OR cs.cs_group LIKE '%,110,%' OR cs.cs_group LIKE '%,111,%' OR cs.cs_group LIKE '%,112,%') AND "
             . "         cmp.cmp_id = cs.cmp_id AND cmp.cmp_comp != 'EXTERN' AND cmp.cmp_visible = '1' AND cs.cs_id_parent != '0' AND NOT isnull(cs.cs_id_parent)";
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   $csIdArray = array();
   while ($row = $result->fetch_assoc()):
         $csIdArray[] = $row["cs_id"];
   endwhile;
   $result->free();
   $csIdArrayLen = count($csIdArray);
   */
   
   // Get all related customer the vehicle is associated to
   $csIdArray = getColVectorFromDB2ArrayByClause("customervehicle", "cs_id", "crvh_id = '" . $crvhId . "'", "", "", "DISTINCT");
   $csIdArrayLen = count($csIdArray);
   
   
   // Iterate all customers
   for ($i = 0; $i < $csIdArrayLen; $i++) :
   
       $csId = $csIdArray[$i];
   
       // Get array of day times of the current customer
       $dayTimes = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "'", "", "mt_sort", "");
       $dayTimeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "'", "", "mt_sort", "");
       $dayTimeMappedValues = getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "'", "", "mt_sort", "");
       $dayTimesLen = count($dayTimes);
   
       // Get the vehicles for the current customer
       $crvhList = array();
       if ($crvhId != "") :
          $crvhList = array($crvhId);
       else :
          $sqlquery = getStmtCustomerVehicleRelation("", $csId);
          $result = $db->query($sqlquery);
          if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
          while ($row = $result->fetch_assoc()):
                $crvhList[] = $row["crvh_id"];
          endwhile;
          $result->free();
       endif;
       $crvhListLen = count($crvhList);
   
       // Check for each vehicle displayed the existence of entries in "vehicledisposition", "vehicleavailability" and "vehicleavailabilitytimeunits".
       // If it does not exist then generate it to handle the drag and dropping the jobs etc.
       for ($v = 0; $v < $crvhListLen; $v++) :
           $crvhId = $crvhList[$v];
   
           // Iterate the next x days
           for ($k = 0; $k < $numOfDays; $k++) :
           
               if (!existsEntry("vehicledisposition",array("crvh_id",$crvhId,"LEFT(vhd_timeslot, 10)",$dateArray[$k]))) :
                  // Generate all new timeslot entries for the vehicle for the specified day
                  generatePersistentTimeslots($crvhId, $dateArray[$k], $hourTimeUnits, $csId);
                  echo "CS = " . $csId . " | " . "CRVH = " . $crvhId . " | " . "DAY = " . $dateArray[$k];
               else :            
                  $retVal = updateVehicleAvailability ($crvhId, $csId, $dateArray[$k]);
                  echo "CS = " . $csId . " | " . "CRVH = " . $crvhId . " | " . "DAY = " . $dateArray[$k] . " | " . " RET = [" . $retVal . "]";
               endif;
   
               
               echo "<br>";
               ob_flush(); flush();
           endfor;
       endfor;
   endfor;
   
   // Deactivate buffering and flush data
   ob_end_flush();
endif;
?>