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


// Check for authentication access and granted rights
// $usrAccessArray["hq"] = "1";
// authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
// authCheckEmployeeRights($emp_id, "1", "1");


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


function updateVehicleAvailabilityPAST ($crvhId, $csId, $startTimeslot = "", $hourTimeUnits = 6) {
  global $db, $PHP_SELF;
  $retVal = "";
                           
  if ($crvhId != "" && $startTimeslot != "" && $hourTimeUnits != "" && $csId != "") :
     $currDay = substr($startTimeslot, 0, 10);
     $vhaId = getFieldValueFromClause("vehicleavailability","vha_id","crvh_id = '" . $crvhId . "' AND vha_day = '" . $currDay . "'");

     if ($vhaId != "") :

        // Get current day (today) and current time (now) to compare it with $currDay (from $startTimeslot) ONLY
        // If it is the same day (today) then do not involve past timeunits !!!!
        $currentDay = getDateTime("3");   // "Y-m-d"
        $currentTime = getDateTime("4");  // Current time ("H:i:s")
        $currentTimeUnit = substr($currentTime,0,2) . "_" . pad(strval(ceil(intval(substr($currentTime,3,2)) * ($hourTimeUnits / 60))), 2);

        // Get week day from $currDay
        $weekDay = date("w", mktime(0, 0, 0, substr($currDay,5,2), substr($currDay,8,2), substr($currDay,0,4)));   // 0 = Sunday, 1 = Monday, etc.
        if ($weekDay == 0) : $weekDay = "7"; endif;   // Reformat to 1 = Monday, ... , 7 = Sunday

        // Get zone array depending on the week day
        $tmpDaytimeZoneArray = getDaytimeAvailabilityOfVehicle($crvhId, $weekDay, $csId, "1");  // $tmpDaytimeZoneArray[daytime] = zone

        // Get time slot array of day times of the specified customer REDUCED by the current vehicle is associated to the time slot being checked for any day time
        $tmpDayTimeSlots = metatypeGetMappedValues("day_time", $hourTimeUnits, $csId, "cs", "");
        $tmpDayTimeSlotsLen = count($tmpDayTimeSlots);
        $dayTimeSlots = array();
        $endOfWorkDay = "";
        for ($i = 0; $i < $tmpDayTimeSlotsLen; $i++) :
            if ($tmpDaytimeZoneArray[$i] != "9999") :
               $dayTimeSlots[$i] = $tmpDayTimeSlots[$i];
               $endOfWorkDay = $tmpDayTimeSlots[$i][1];  // Important because of whole day units have to be limited by max work time !!!!
            endif;
        endfor;
        $dayTimeSlotsLen = count($dayTimeSlots);

        // Remove all entries for the specified vehicle AND for the specified day in table "vehicleavailabilitytimeunits"
        deleteStmt("vehicleavailabilitytimeunits","vha_id = '" . $vhaId . "' AND cs_id = '" . $csId . "'");

        // Renew the timeslot structure regarding the values in table "vehicledisposition"
        // Get all time unit data of the current vehicle for the specified day, daytime and zone
        $timeUnitArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "'", "vhd_timeslot", "vhd_timeslot", "");
        $timeUnitArrayLen = count($timeUnitArray);

        if ($timeUnitArrayLen > 0) :

           // Init free capacity array ($countFreeTimeUnits) of the specified vehicle and specified customer and specified day for each daytime.
           $countFreeTimeUnits = array();
           $startTimeUnitOfFreeTimeSlot = array();
           $remCountFreeTimeUnits = array();

           // Init free capacity WITHOUT daytime restriction
           $countFreeTimeUnitsMoreDaytimes = array();
           $startTimeUnitOfFreeTimeSlotMoreDaytimes = array();
           $remCountFreeTimeUnitsMoreDaytimes = array();
           $remStartTimeUnitOfFreeTimeSlotMoreDaytimes = array();

           for ($k = 0; $k < $dayTimeSlotsLen; $k++) :
               $countFreeTimeUnits[$k] = 0;
               $startTimeUnitOfFreeTimeSlot[$k] = "";
               $remCountFreeTimeUnits[$k] = 0;
               
               $countFreeTimeUnitsMoreDaytimes[$k] = 0;
               $startTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = "";
               $remCountFreeTimeUnitsMoreDaytimes[$k] = 0;
               $remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = "";
           endfor;

           for ($i = 0; $i <= 23; $i++) :
               for ($j = 0; $j < $hourTimeUnits; $j++) :

                   $currHour = pad($i, 2);
                   $currTimeUnit = pad($j, 2);
                   $ctu = $currHour . '_' . $currTimeUnit;
                   $vhdTimeslot = $currDay . '_' . $ctu;

                   // Check SELECTED DAY in "$currDay" being in the future. All future day may not be restricted.
                   // If the selected day is "today" then continue with future timeunits of today only.
                   // Free timeunits can be counted from now to the future only
                   if ($currDay <= $currentDay) :

                      // * ITERATE FOR EACH DAYTIME *
                      // 1. It could be possible the intervals are NOT defined in order (e.g. daytime 0 <=> "12.30 - 15.59, 1 <=> 07.00 - 12.29")!!!!
                      // 2. It could be possible the intervals have intersections (e.g. daytime 0 <=> "12.30 - 15.59, 1 <=> 15.00 - 19.59" => Intersection 15.00 - 15.59)!!!!
                      // Therefore iterate ALL defined time slots defined for the customer with separated counters for free time units.
                      // Check for time unit being in any customer time slot the current vehicle is associated to (checked above)
                      for ($k = 0; $k < $dayTimeSlotsLen; $k++) :

                          // * Check for each daytime of the day *
                          if ($dayTimeSlots[$k][0] <= $ctu && $ctu < $dayTimeSlots[$k][1]) :

                             if ($startTimeUnitOfFreeTimeSlot[$k] == "") :
                                $startTimeUnitOfFreeTimeSlot[$k] = $ctu;
                             endif;

                             $doInsert = true;
                             $jbIdAssocInTimeUnit = $timeUnitArray[$vhdTimeslot];  // Get job ID potentially associated to the current time unit
                             if ($jbIdAssocInTimeUnit == "0") :  // No job is associated to this single time unit (array from table "vehicledisposition")
                                $countFreeTimeUnits[$k]++;
                                $doInsert = false;
                             endif;
                             if ($countFreeTimeUnits[$k] == 0) :
                                $startTimeUnitOfFreeTimeSlot[$k] = "";
                                $doInsert = false;
                             endif;

                             if ($doInsert) :  // Important to check for "$countFreeTimeUnits > 0" because next time units (after "$doInsert == true") having the same job have not to be inserted !!!!
                                insertStmt("vehicleavailabilitytimeunits", array("vha_id",$vhaId,"vhat_daytime",$k,"vhat_timeunits",$countFreeTimeUnits[$k],"cs_id",$csId,"vhat_srvz_no",$tmpDaytimeZoneArray[$k],"vhat_starttimeunit",$startTimeUnitOfFreeTimeSlot[$k]));
                                $retVal .= "(" . $k . ", " . $countFreeTimeUnits[$k] . ", " . $startTimeUnitOfFreeTimeSlot[$k] . ") ";
                                
                                if ($remCountFreeTimeUnits[$k] < $countFreeTimeUnits[$k]) :
                                   $remCountFreeTimeUnits[$k] = $countFreeTimeUnits[$k];
                                endif;
                                $countFreeTimeUnits[$k] = 0;
                                $startTimeUnitOfFreeTimeSlot[$k] = "";
                             endif;
                          endif;

                          // * Check for whole day *
                          if ($ctu >= $dayTimeSlots[$k][0] && $ctu < $endOfWorkDay) :

                             if ($remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k] == "") :
                                $remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = $ctu;
                             endif;
                             if ($startTimeUnitOfFreeTimeSlotMoreDaytimes[$k] == "") :
                                $startTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = $ctu;
                             endif;

                             $jbIdAssocInTimeUnit = $timeUnitArray[$vhdTimeslot];  // Get job ID potentially associated to the current time unit
                             if ($jbIdAssocInTimeUnit == "0") :  // No job is associated to this single time unit (array from table "vehicledisposition")
                                $countFreeTimeUnitsMoreDaytimes[$k]++;
                             else :
                                if ($remCountFreeTimeUnitsMoreDaytimes[$k] == 0 && $ctu >= $dayTimeSlots[$k][1] && $currDay <= $currentDay) :
                                   $remCountFreeTimeUnitsMoreDaytimes[$k] = $countFreeTimeUnitsMoreDaytimes[$k];
                                   $remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = $startTimeUnitOfFreeTimeSlotMoreDaytimes[$k];
                                endif;
                             
                                $countFreeTimeUnitsMoreDaytimes[$k] = 0;
                                $startTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = "";
                             endif;
                          endif;

                      endfor;
                   endif;  // Check for availavle timeunits from NOW() only
               endfor;
           endfor;
           // Store the rest of the free time units
           for ($k = 0; $k < $dayTimeSlotsLen; $k++) :
               if ($countFreeTimeUnits[$k] > 0) :  // Important to check for "$countFreeTimeUnits > 0" because next time units (after "$doInsert == true") having the same job have not to be inserted !!!!
                  insertStmt("vehicleavailabilitytimeunits", array("vha_id",$vhaId,"vhat_daytime",$k,"vhat_timeunits",$countFreeTimeUnits[$k],"cs_id",$csId,"vhat_srvz_no",$tmpDaytimeZoneArray[$k],"vhat_starttimeunit",$startTimeUnitOfFreeTimeSlot[$k]));
                  $retVal .= "(" . $k . ", " . $countFreeTimeUnits[$k] . ", " . $startTimeUnitOfFreeTimeSlot[$k] . ") ";

                  if ($remCountFreeTimeUnits[$k] < $countFreeTimeUnits[$k]) :
                     $remCountFreeTimeUnits[$k] = $countFreeTimeUnits[$k];
                  endif;
               endif;
           endfor;
           // Store the whole day time units
           for ($k = 0; $k < ($dayTimeSlotsLen - 1); $k++) :
               // Needed only if NO job is on the timeline
               if ($remCountFreeTimeUnitsMoreDaytimes[$k] == 0 && $currDay <= $currentDay) :
                   $remCountFreeTimeUnitsMoreDaytimes[$k] = $countFreeTimeUnitsMoreDaytimes[$k];
                   $remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = $startTimeUnitOfFreeTimeSlotMoreDaytimes[$k];
               endif;

               if ($remCountFreeTimeUnitsMoreDaytimes[$k] > $remCountFreeTimeUnits[$k]) :
                  insertStmt("vehicleavailabilitytimeunits", array("vha_id",$vhaId,"vhat_daytime",$k,"vhat_timeunits",$remCountFreeTimeUnitsMoreDaytimes[$k],"cs_id",$csId,"vhat_srvz_no",$tmpDaytimeZoneArray[$k],"vhat_starttimeunit",$remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k]));
                  $retVal .= "(" . $k . ", " . $countFreeTimeUnits[$k] . ", " . $startTimeUnitOfFreeTimeSlot[$k] . ") ";
               endif;
           endfor;
        endif;
     endif;
  endif;
  return $retVal;
}



// Activate buffering
ob_start();

// Current day
$pastDays = 10;
$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)


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

//    1 = Schnelsen
//    2 = Moorfleet
// 3534 = Ludwigsburg
// 3540 = Sindelfingen
$csIdArray = array("1","2","3534","3540");
$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();
    $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();
    $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 <= $pastDays; $k++) :
            $retVal = updateVehicleAvailabilityPAST($crvhId, $csId, $dateArray[$k]);            
            echo "CS = " . $csId . " | " . "CRVH = " . $crvhId . " | " . "DAY = " . $dateArray[$k] . " | " . " RET = [" . $retVal . "]";
            echo "<br>";
            ob_flush(); flush();
        endfor;
    endfor;
endfor;

// Deactivate buffering and flush data
ob_end_flush();
?>