<?php
/*=======================================================================
 *
 * checkAndUpdateFDSVehicleWeights.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");
include_once ("../include/html.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "vehicles"));


// 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);

// Constants
$constListBgCol1 = "#AAAAFF";
$constListBgCol2 = "#AAAAFF";
$constListBgCol3 = "#CCCCFF";
$constListBgCol4 = "#CCCCFF";

// Current day
$selDay = getDateTime("day");
$selMonth = getDateTime("month");
$selYear = getDateTime("year");

// Get last day defined in FDS
$currentDay = getDateTime("3");   // "Y-m-d"
$lastVhaDay = getOneStmt("SELECT vha_day FROM vehicleavailability ORDER BY vha_day DESC", "vha_day");
$date1 = new DateTime($lastVhaDay);
$date2 = new DateTime($currentDay);
$diff = $date1->diff($date2);
$numOfDays = $diff->days;
if ($numOfDays == "") : $numOfDays = 2; endif;

// 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;

// Iterate the next x days
$line = 0;
$cellColor = getListColor(1, 1);
$td0 = "align=\"center\" bgcolor=\"" . $cellColor . "\"";
$output = "<center>";
$output .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
$output .= "<tr><td colspan=\"3\">" . defineButtonType08("Bereinigen", "action_clean", "finishPage('clean');", "150", "left", "2") . "</td>";
$output .= "    <td colspan=\"4\">" . "<input type=\"text\" name=\"vehicles\" value=\"" . $vehicles . "\" maxlength=\"20\" size=\"20\">" . "</td></tr>";
$output .= "<tr><td colspan=\"7\"><img src=\"../images/spacer_darkgrey.jpg\" width=\"100%\" height=\"10\" border=\"0\"></td></tr>";
$output .= "<tr><td " . $td0 . "><b>&nbsp;&nbsp;TAG&nbsp;&nbsp;</b></td><td " . $td0 . "><b>&nbsp;&nbsp;FAHRZEUG&nbsp;&nbsp;</b></td><td " . $td0 . "><b>&nbsp;&nbsp;MAX.NUTZLAST [crvh]&nbsp;&nbsp;</b></td>"
        .      "<td " . $td0 . "><b>&nbsp;&nbsp;AKT.LADEGEWICHT [trat]&nbsp;&nbsp;</b></td><td " . $td0 . "><b>&nbsp;&nbsp;AKT.KAPAZITÄT [vha]&nbsp;&nbsp;</b></td>"
        .      "<td " . $td0 . "><b>&nbsp;&nbsp;(NUTZLAST - LADEGEWICHT)&nbsp;&nbsp;</b></td><td " . $td0 . "><b>&nbsp;&nbsp;(DIFFERENZ KAPAZITÄT - (NUTZLAST - LADEGEWICHT))&nbsp;&nbsp;</b></td></tr>";
$output .= "<tr><td colspan=\"7\"><img src=\"../images/spacer_darkgrey.jpg\" width=\"100%\" height=\"10\" border=\"0\"></td></tr>";
for ($k = 0; $k < $numOfDays; $k++) :
    // Get vehicle for the day
    $vhaCrvhIdArray = getColVectorFromDB2ArrayByClause("vehicleavailability", "crvh_id", "vha_day = '" . $dateArray[$k] . "'", "vha_id", "crvh_id", "");
    $vhaWeightArray = getColVectorFromDB2ArrayByClause("vehicleavailability", "vha_weight", "vha_day = '" . $dateArray[$k] . "'", "vha_id", "crvh_id", "");

    $arrKeys = array_keys($vhaCrvhIdArray);
    $arrKeysLen = count($arrKeys);
    
    if ($arrKeysLen > 0) :
       for ($i = 0; $i < $arrKeysLen; $i++) :
           $vhaId = $arrKeys[$i];
           $crvhId = $vhaCrvhIdArray[$vhaId];
           $crvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");
   
           // Get payload vaklue of the vehicle from master data
           $crvhPayload = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_payload");
   
           // Get available capacity freom "vehicleavailability"
           $crvhCapacityAvailable = $vhaWeightArray[$vhaId];
   
           // Get jobs associated to the cartage note of the vehicle of the day
           $sqlquery = "SELECT DISTINCT jb_id FROM vehicledisposition AS vhd WHERE LEFT(vhd.vhd_timeslot,10) = '" . $dateArray[$k] . "' AND vhd.crvh_id = '" . $crvhId . "' AND vhd.jb_id != '0'";
// echo $sqlquery . "<br><br>\n\n";
           $result = $db->query($sqlquery);
           if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
           $jbArray = array();
           while ($row = $result->fetch_assoc()):
                 $jbArray[] = $row["jb_id"];
           endwhile;
           $result->free();
// print_r($jbArray);
           // Get sum of article weights of the cartage note of the vehicle of the day from distinct jobs
           $sumTratWeight = 0;
           if (count($jbArray) > 0) :
              $sqlquery = "SELECT SUM(trat.trat_weight) AS sum_weight FROM tourarticle AS trat WHERE trat.jb_id IN (" . implode(",", $jbArray) . ")";
// echo $sqlquery . "<br><br>\n\n";
              $result = $db->query($sqlquery);
              if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
              $jbArray = array();
              while ($row = $result->fetch_assoc()):
                    $sumTratWeight = $row["sum_weight"];
              endwhile;
              $result->free();
           endif;
   
           $crvhPayloadMinusSumTratWeight = $crvhPayload - $sumTratWeight;   // (NUTZLAST - LADEGEWICHT)
           $diff = $crvhCapacityAvailable - $crvhPayloadMinusSumTratWeight;  // (DIFFERENZ KAPAZITÄT - (NUTZLAST - LADEGEWICHT))        
   
           // UPDATE if requested
           if ($f_act == "clean") :
              if ($diff != 0) :
                 updateStmt("vehicleavailability","vha_id",$vhaId,array("vha_weight", $crvhPayloadMinusSumTratWeight));
              endif;
           endif;
   
           // Format output
           $crvhPayload = number_format(round($crvhPayload,2), 2, ",", ".");
           $sumTratWeight = number_format(round($sumTratWeight,2), 2, ",", ".");
           $crvhCapacityAvailable = number_format(round($crvhCapacityAvailable,2), 2, ",", ".");
           $crvhPayloadMinusSumTratWeight = number_format(round($crvhPayloadMinusSumTratWeight,2), 2, ",", ".");
           $diff = number_format(round($diff,2), 2, ",", ".");
   
           $cellColor = getListColor($i, $line);
           $td1 = "align=\"center\"" . " bgcolor=\"" . $cellColor . "\"";
           $td2 = "align=\"center\"" . " bgcolor=\"" . $cellColor . "\"";
           $td3 = "align=\"right\"" . " bgcolor=\"" . $cellColor . "\"";
           $td4 = "align=\"right\"" . " bgcolor=\"" . $cellColor . "\"";
           $td5 = "align=\"right\"" . " bgcolor=\"" . $cellColor . "\"";
           $td6 = "align=\"right\"" . " bgcolor=\"" . $cellColor . "\"";
           $td7 = "align=\"right\"" . " bgcolor=\"" . $cellColor . "\"";
   
           $output .= "<tr><td " . $td1 . ">" . ($remDay != $dateArray[$k] ? $dateArray[$k] : "") . "</td><td " . $td2 . ">" . $crvhSid . "</td><td " . $td3 . ">" . $crvhPayload . "</td>"
                   .      "<td " . $td4 . ">" . $sumTratWeight . "</td><td " . $td5 . ">" . $crvhCapacityAvailable . "</td>"
                   .      "<td " . $td6 . ">" . $crvhPayloadMinusSumTratWeight . "</td><td " . $td7 . ">" . $diff . "</td></tr>";
   
           $remDay = $dateArray[$k];
       endfor;
       $output .= "<tr><td colspan=\"7\"><img src=\"../images/spacer_darkgrey.jpg\" width=\"100%\" height=\"10\" border=\"0\"></td></tr>";
       if ($line == 0) : $line = 1; else : $line = 0; endif;
    endif;
endfor;
$output .= "</table>";
$output .= "</center>";
?>

<html>
<head>
<title>GEWICHTE</title>
<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
<!--
.verysmall
{ font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 2pt; font-weight: normal; padding: 0px}
-->
</style>
<script type="text/javascript">
<!--
function finishPage(f_act) {
  document.forms[0].f_act.value = f_act;
  document.forms[0].submit();
};

function popupWindow(url,title,config) {
  popup = window.open(url,title,config);
}
-->
</script>
</head>
<body>
	
<form action="../tools/checkAndUpdateFDSVehicleWeights.php" method="post">
  <input type="hidden" name="f_act" value="">

	<div>
	  <?php echo $output; ?>
	</div>
</form>
</body>
</html>
