<?php

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/inc_job.inc.php");
include_once ("../locating/xServer.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "objType", "objId", "result", "noMap"));

getLanguage(__FILE__);
$pageTitel = getLngt("SORTIERUNG");
getCurrentScript(__FILE__);

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


// Generic array for data chunks to be sorted
$debug = false;
$sortArray = array();
$coordArr = array();
$tabText = array();
if ($result != "") :
   $result = urldecode($result);
   $result = json_decode($result);
endif;
$objHeader = "";
$statusMessage = "";
if ($noMap == "") : $noMap = "0"; endif;  // Map will be displayed by default

if ($debug) :
   echo "objType = " . $objType . "<br>";
   echo "objId = " . $objId . "<br>";
   echo "result = " . $result . "<br>";
endif;

// **** SAVE NEW SORT SEQUENCE ****
if ($f_act == "save" && $objId != "" && is_numeric($objId) && $result != "") :

   // **** JOB ****
   // Store job with new sorting sequence
   if ($objType == "jb") :
      $trIdArray = array();
      $trSort = 1;
      foreach($result as $key => $value) {
          foreach($value as $innerKey => $innerValue) {
              $resultArray = explode(";",$innerValue);
              $result[$key][$innerKey] = array(0 => $resultArray[0], 1 => $resultArray[1]);
              $trIdArray[$resultArray[0]] = $trSort;  // $trIdArray[<tr_id>] = <tr_sort>
              $trSort++;
          }
      }
      $trIdArrayLen = count($trIdArray);
      if ($trIdArrayLen > 0) :
         $trIdKeyArray = array_keys($trIdArray);
         // Get jb_status   
         $jbId = getFieldValueFromId("tour", "tr_id", $trIdKeyArray[0], "jb_id");
         if ($jbId == $objId) :
            $jbStatus = getFieldValueFromId("job", "jb_id", $jbId, "jb_status");
            if ($jbStatus == "9" || $jbStatus == "8" || $jbStatus == "0" || $jbStatus == "1") :
               $trIdKeyArrayLen = count($trIdKeyArray);
               TA("B");
               $doCommit = true;
               for ($i = 0; $i < $trIdKeyArrayLen; $i++) :
                   $trSort = $trIdArray[$trIdKeyArray[$i]];
                   if ($trSort != "" && is_numeric($trSort)) :
                      $res  = updateStmt("tour","tr_id",$trIdKeyArray[$i],array("tr_sort", $trSort));
                      $res2 = updateStmt("jobcalculator","tr_id",$trIdKeyArray[$i],array("tr_sort", $trSort));
                      $res3 = updateStmt("tourarticle","tr_id",$trIdKeyArray[$i],array("tr_sort", $trSort));
                   else :
                      $doCommit = false;
                      break;
                   endif;
               endfor;
               if ($doCommit) :
                  mk_jb_tourdata($jbId);
                  // Final check for changing state
                  $jbStatus = getFieldValueFromId("job", "jb_id", $jbId, "jb_status");
                  if ($jbStatus == "9" || $jbStatus == "8" || $jbStatus == "0" || $jbStatus == "1") :
                     TA("C");  // OK, TA ended with the same state of the job
                  else :
                     TA("R");
                     $statusMessage = getLngt("Der Status des Auftrags wurde während der Verarbeitung durch einen anderen Prozess geändert! Es erfolgte keine Verarbeitung!");
                  endif;
               else :
                  TA("R");
               endif;
               TA("E");
            else :
               $statusMessage = getLngt("Der Auftrag muss den Zuweisungsstatus aufweisen, absonsten findet keine Verarbeitung statt!");
            endif;
         else :
            $statusMessage = getLngt("Anomalie: Die Station passt nicht zum Auftrag! Es erfolgte keine Verarbeitung!");
         endif;
      else :
         $statusMessage = getLngt("Keine Station vorhanden! Es erfolgte keine Verarbeitung!");
      endif;
   endif;
   
   // **** COURIERFILTER ****
   // Store filter with new sorting sequence
   if ($objType == "crf") :
      $crfIdArray = array();
      $crfSort = 1;
      foreach($result as $key => $value) {
          foreach($value as $innerKey => $innerValue) {
              $resultArray = explode(";",$innerValue);
              $result[$key][$innerKey] = array(0 => $resultArray[0], 1 => $resultArray[1]);
              $crfIdArray[$resultArray[0]] = $crfSort;  // $crfIdArray[<crf_id>] = <crfSort>
              $crfSort++;
          }
      }
      $crfIdArrayLen = count($crfIdArray);
      if ($crfIdArrayLen > 0) :
         $crfIdKeyArray = array_keys($crfIdArray);
         $crfIdKeyArrayLen = count($crfIdKeyArray);
         TA("B");
         $doCommit = true;
         for ($i = 0; $i < $crfIdKeyArrayLen; $i++) :
             $crfSort = $crfIdArray[$crfIdKeyArray[$i]];
             if ($crfSort != "" && is_numeric($crfSort)) :
                $res  = updateStmt("courierfilter","crf_id",$crfIdKeyArray[$i],array("crf_sort", $crfSort));
             else :
                $doCommit = false;
                break;
             endif;
         endfor;
         /*
         if ($doCommit) :
            // Final check for changing state
            $jbStatus = getFieldValueFromId("job", "jb_id", $jbId, "jb_status");
            if ($jbStatus == "9" || $jbStatus == "8" || $jbStatus == "0" || $jbStatus == "1") :
               TA("C");  // OK, TA ended with the same state of the job
            else :
               TA("R");
               $statusMessage = getLngt("Der Status des Auftrags wurde während der Verarbeitung durch einen anderen Prozess geändert! Es erfolgte keine Verarbeitung!");
            endif;
         else :
            TA("R");
         endif;
         */
         TA("E");
      else :
         $statusMessage = getLngt("Keine Station vorhanden! Es erfolgte keine Verarbeitung!");
      endif;
   endif;
endif;


// **** GET OBJECT DATA WITH CURRENT/NEW SORTING SEQUENCE ****
if ($objId != "" && is_numeric($objId)) :

   // **** JOB ****
   if ($objType == "jb" && $objId != "" && is_numeric($objId)) :
      $jobData = array();
      getDBData("job", $objId);
      getDBData("tour", $objId);
      // getDBData("tourarticle", $objId);
      // getDBData("genericdatacontainer", $objId);
      // print_r($jobData); echo "<br><br>";
      // $jbStatus = getFieldValueFromId("job", "jb_id", $jbId, "jb_status");
      // if (true || $jbStatus == "9") :   // !!!!!!!!
      if (true) :   // !!!!!!!!
         $numOfStations = count($jobData["tour"]);

         for ($i = 0; $i < $numOfStations; $i++) :
             $j = $i +1;
             $trId = $jobData["tour"][$j]["tr_id"];
         
             $htmlText = "<table>";
             $htmlText .= "<tr><td class=\"f8np1\">" . $jobData["tour"][$j]["tr_comp"] . "</td></tr>";
             $htmlText .= "<tr><td class=\"f8np1\">" . $jobData["tour"][$j]["ad_street"] . "&nbsp;" . $jobData["tour"][$j]["tr_hsno"] . "</td></tr>";
             $htmlText .= "<tr><td class=\"f8np1\">" . $jobData["tour"][$j]["ad_zipcode"] . "&nbsp;" . $jobData["tour"][$j]["ad_city"] . "</td></tr>";
             $htmlText .= "<tr><td class=\"f8np1\">" . $jobData["tour"][$j]["tr_person"] . "</td></tr>";
             $htmlText .= "<tr><td class=\"f8np1\">" . $jobData["tour"][$j]["tr_phone"] . "</td></tr>";
             /*
             $htmlText .= "<tr>";
             $htmlText .= "<td class=\"f8np1\" width=\"200\">" . $jobData["tour"][$j]["tr_comp"] . "</td>";
             $htmlText .= "<td class=\"f8np1\" width=\"200\">" . $jobData["tour"][$j]["ad_street"] . "&nbsp;" . $jobData["tour"][$j]["tr_hsno"] . "</td>";
             $htmlText .= "<td class=\"f8np1\" width=\"200\">" . $jobData["tour"][$j]["ad_zipcode"] . "&nbsp;" . $jobData["tour"][$j]["ad_city"] . "</td>";
             $htmlText .= "<td class=\"f8np1\" width=\"100\">" . $jobData["tour"][$j]["tr_person"] . "</td>";
             $htmlText .= "<td class=\"f8np1\" width=\"100\">" . $jobData["tour"][$j]["tr_phone"] . "</td>";
             $htmlText .= "</tr>";
             */
             $htmlText .= "</table>";
/*       
             $htmlText = $jobData["tour"][$j]["tr_comp"] . "<br>";
             $htmlText .= $jobData["tour"][$j]["ad_street"] . "&nbsp;" . $jobData["tour"][$j]["tr_hsno"] . "<br>";
             $htmlText .= $jobData["tour"][$j]["ad_zipcode"] . "&nbsp;" . $jobData["tour"][$j]["ad_city"] . "<br>";
             $htmlText .= $jobData["tour"][$j]["tr_person"] . "<br>";
             $htmlText .= $jobData["tour"][$j]["tr_phone"] . "<br>";
*/       
//             $htmlText = htmlspecialchars($htmlText);

             $urlText = $jobData["tour"][$j]["ad_street"] . " " . $jobData["tour"][$j]["tr_hsno"]. ", " . $jobData["tour"][$j]["ad_zipcode"] . " " . $jobData["tour"][$j]["ad_city"];
             $urlText = urlencode(utf8_encode($urlText));
             if ($j == 1) :
                $urlText = "&saddr=" . $urlText;
             elseif ($j == 2) :
                $urlText = "&daddr=" . $urlText;
             elseif ($j > 2) :
                $urlText = "+to:" . $urlText;
             endif;

             if ($f_act == "optimize") :
                $coordPairArr = get_coords($jobData["tour"][$j]["ad_country"], $jobData["tour"][$j]["ad_zipcode"], $jobData["tour"][$j]["ad_city"], $jobData["tour"][$j]["ad_street"], $jobData["tour"][$j]["tr_hsno"], false);
             endif;

             $sortArray[0][$i] = array($trId, $htmlText, $urlText, $coordPairArr);
             $coordArr[$i] = $coordPairArr;
             $tabText[$i] = getLngt("Auftrag") . " " . $objId;
         endfor;
         
         // Optimization
         if ($f_act == "optimize") :
            $optArr = get_zone_distance($coordArr, $hq_id, $objId, false, true);
            $optRouteArr = $optArr["optimizedRoute"];
if ($debug) :
   echo "<br><br>"; print_r($coordArr); echo "<br><br>";
   echo "<br><br>"; print_r($optRouteArr); echo "<br><br>";
   // echo "<br><br>"; print_r($optArr["legs"]); echo "<br><br>";
   echo "<br>sortArray PRE:<br>";print_r($sortArray); echo "</br>";
endif;
            $optRouteArrLen = count($optRouteArr);
            if ($optRouteArrLen > 0) :
               // Iterate stations for renewing optimized vector
               $tmpSortArr = $sortArray;
               for ($s = 0; $s < $optRouteArrLen; $s++) :
                   $sortArray[0][($s + 1)] = $tmpSortArr[0][($optRouteArr[$s] + 1)];  // Tricky, because $optRouteArr contains all intermediate stations only !!!! ([0] => 2, [1] => 1, [2] => 0)
               endfor;
            endif;
if ($debug) :
   echo "<br>sortArray POST:<br>";print_r($sortArray); echo "</br>";
endif;
         endif;
      else :
         $statusMessage = getLngt("Der Auftrag muss den Zuweisungsstatus aufweisen, absonsten findet keine Verarbeitung statt!");
      endif;
      $objHeader = getLngt("Sortierung der Stationsreihenfolge des Auftrags") . " " . $objId;
   endif;

   // **** COURIERFILTER ****
   if ($objType == "crf" && $objId != "" && is_numeric($objId)) :
      $crfData = getMatrixFromDbResultByStatement("SELECT " . getDBFields("courierfilter") . " FROM courierfilter AS crf ORDER BY crf.crf_sort");
      $crfDataLen = count($crfData);
      if ($crfDataLen > 0) :   // !!!!!!!!
         for ($i = 0; $i < $crfDataLen; $i++) :
             // $j = $i + 1;
             $j = $i;
             $crfId = $crfData[$j]["crf_id"];

             $htmlText = "<table>";
             $htmlText .= "<tr>";
             $htmlText .= "<td class=\"f8np1\" width=\"100\">" . $crfData[$j]["crf_sort"] . "</td>";
             $htmlText .= "<td class=\"f8np1\" width=\"200\">" . $crfData[$j]["crf_short"] . "</td>";
             $htmlText .= "<td class=\"f8np1\" width=\"100\">" . $crfData[$j]["crf_text"] . "</td>";
             $htmlText .= "</tr>";
             $htmlText .= "</table>";

//             $htmlText = htmlspecialchars($htmlText);
             $sortArray[0][$i] = array($crfId, $htmlText, "");
             $tabText[$i] = getLngt("Filter");
         endfor;
      else :
         $statusMessage = getLngt("Zur Zeit scheinen keine Filter existent!");
      endif;
      $objHeader = getLngt("Sortierung der Filter");
   endif;
endif;

$sortArrayLength = count($sortArray);
// echo "<br>sortArray:<br>";print_r($sortArray); echo "</br>"; echo "sortArrayLength = " . $sortArrayLength . "</br>";

function drawBoxes($sortArray, $tabText, $noMap = "0") {    

    if ($noMap == "0") :
       $mapUrl = "https://maps.google.com/maps?q=&hl=de&output=embed&source=s_d";
	     $mapAdArr = array();
	  endif;
    
    $html_output = "";
    foreach ($sortArray as $key => $value) {

        $html_output .= '    <div class="divBox" style="margin-left: 10px; margin-top: 10px; float:left;" id="id_reiter' . $key .'">' . "\n";
        $html_output .= '      <div class="panel-heading" style="height: 30px; margin-left:15px; margin-top:10px; background-color: #1b12b9;"><font color="white">' . $tabText[$key] . '</font></div>' . "\n";
        $html_output .= '      <div id="divBox1" style="float:left;">' . "\n";
        $html_output .= '          <ul class="itemContainer" id="original_items' . $key . '">' . "\n";

        foreach ($value as $boxValue) {
// echo "<br>boxValue:<br>";print_r($boxValue); echo "</br>";
          $html_output .= '             <li class="original_item_content" id="' . $boxValue[0] . ';' . "" . '">' . $boxValue[1] . '</li>' . "\n";
          if ($noMap == "0") :
             $mapAdArr[] = $boxValue[2];
          endif;
        }
// echo "<br>";
        $html_output .= '          </ul>' . "\n";
        $html_output .= '          <ul id="cloned_items' . $key . '"></ul>' . "\n";
        $html_output .= '      </div>' . "\n";
        $html_output .= '    </div>' . "\n";

        if ($noMap == "0") :
           $html_output .= '    <div id="divBoxMap" style="min-width:800px; min-height:800px; padding:10px;">' . "\n";
           $mapUrl .= implode("/", $mapAdArr);           
// echo $mapUrl . "<br>";
           $html_output .= '      <iframe class="sort_map" src="' . $mapUrl . '"></iframe>' . "\n";
           $html_output .= '    </div>' . "\n";
        endif;
    }
    return $html_output;
}
?>

<html>
<head>
<title><?php echo $pageTitel ?></title>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

<?php 
// include_once ("../include/js_framework.inc.php");

$frameworkFile = "../js/jquery.js";
if ($htmlDefaultCharset == "") : $htmlDefaultCharset = "iso-8859-1"; endif;
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" . $htmlDefaultCharset . "\">\n";

// echo "<meta http-equiv=\"Content-Security-Policy\" content=\"child-src=https://www.google.de/\">\n";
// echo "<meta http-equiv=\"Content-Security-Policy\" content=\"child-src=https://maps.google.com/\">\n";
echo '<meta name="referrer" content="origin"/>';
echo '<meta name="referrer" content="origin-when-crossorigin"/>';

echo "<script src=\"" . $frameworkFile . "\"></script>\n";
echo "<script type=\"text/javascript\" src=\"../js/jquery-ui.custom.min.js\"></script>\n";
echo "<link rel=\"stylesheet\" href=\"../css/jquery-ui.custom.min.css\" type=\"text/css\" />\n";
?>

<link href="../css/themes/assec.css" rel="stylesheet" type="text/css"/>

        <style>
            [id^=original_items] li {
                position: relative;
                z-index: 5;
            }

            [id^=original_items], [id^=cloned_items] {
                list-style: none;
            }
            
            [id^=cloned_items] {
                display: none;
            }

            [id^=cloned_items] li {
                position: absolute;
                border-radius: 20px;
                z-index: 1;
            }

            li {
                cursor: default;
                background-color:#CDD9FD;
                border-radius: 20px;
                text-align: center;
                line-height: 130px;
                margin-left: 10px;
                min-height: 30px;
                border: solid;
                min-width: 300px;
                margin-left: 50px;
                margin-right: 50px;
                margin-bottom: 10px;
                padding: 10px;
            }

            div {
                cursor: default;
            }

            ul, html, body {
                padding:0px;
                margin:0px;
            }

            ul {
                margin:0 auto;
            }

            .reiterBox {
                min-height: 800px;
                min-width: 800px;
                border-radius: 20px;
                border: solid 1px;
            }

            .divBox {
                cursor: default;
                min-height: 220px;
                border: solid 1px;
                border-radius: 20px;
                background-color: #1b12b9;
                overflow-y: scroll;
                max-height: 800px;
            }
            
            .sort_map {
                min-height: 800px;
                min-width: 800px;
                max-height: 800px;
                max-width: 800px;
                marginheight: 0px;
                marginwidth: 0px;
                scrolling: no;
            }
        </style>


<script type="text/javascript">

$(document).ready(function() {
    var arrayLength = <?php echo $sortArrayLength ?>;
    makeSortable(arrayLength);
});

function makeSortable(arrayLength) {
    for(var i = 0; i < arrayLength; i++) {
        $("#original_items" + i + " li").each(function () {
            var item = $(this);
            var item_clone = item.clone();
            item.data("clone", item_clone);
            var position = item.position();
            item_clone.css("left", position.left);
            item_clone.css("top", position.top);
            item_clone.css("top", position.top);
            $("#cloned_items" + i + "").append(item_clone);
        });

        $(".original_item_content").disableSelection();
        $(".panel-heading").disableSelection();
        $(".itemContainer").disableSelection();

        $("#original_items"+ i).sortable({
            tolerance: "pointer",
            cursorAt: {top: 50},
            revert: 500,
            axis: "y"
        });
    }
}

function sortFinishPage(f_act = '') {
	var textConf = '<?php echo getLngt("Wirklich speichern?") ?>';
	if (f_act == 'optimize') {textConf = '<?php echo getLngt("Wirklich optimieren?") ?>';};
  if (confirm(textConf)) {
	  $('#f_act').val(f_act);
    var arrayLenght = <?php echo $sortArrayLength ?>;
    var resultArray = [];
    var newBoxOrder;
    for(var j = 0; j < arrayLenght; j++) {
        newBoxOrder = ($( "#original_items"+j ).sortable("toArray"));
        resultArray[j] = newBoxOrder;
    }
    $('#result').val(encodeURIComponent(JSON.stringify(resultArray)));
    $('#myForm').submit();
  };
}
</script>
</head>

<body bgcolor="#CDD9FD">
    <div class="f12bp1_blue" style="margin-left: 10px; margin-top: 10px; height:30px;">
      <?php echo $objHeader ?>
    </div>
    <?php if ($statusMessage != "") : ?>
      <div class="f10bp1_red" style="margin-left: 10px; margin-top: 10px; height:30px;">
        <?php echo $statusMessage ?>
      </div>
    <?php endif; ?>
    <div style="margin-left: 10px; height:40px;">
      <input style="margin-top: 5px; width: 150px; height:25px; background-color: #1b12b9; color: white;" id="submit" type="button" value="<?php echo getLngt("Übernehmen") ?>" onclick="sortFinishPage('save')">
      <?php         
        if ($objType == "jb" && $objId != "" && is_numeric($objId)) :
           $numOfStations = getCountOfTable("phoenix.tour", "jb_id = '" . $objId . "'");
           if (is_numeric($numOfStations) && $numOfStations > 3 && $numOfStations <= 25) :
      ?>
             <input style="margin-top: 5px; width: 150px; height:25px; background-color: #1b12b9; color: white;" id="submit" type="button" value="<?php echo getLngt("Optimieren") ?>" onclick="sortFinishPage('optimize')">
      <?php 
           endif;
        endif;
      ?>
    </div>
    <form action="../admin/sort.php" method="POST" id="myForm">
    	  <input type="hidden" id="f_act" name="f_act" value="">
    	  <input type="hidden" name="objType" value="<?php echo $objType ?>">
    	  <input type="hidden" name="objId" value="<?php echo $objId ?>">
    	  <input type="hidden" id="result" name="result" value="">
    	  <input type="hidden" name="noMap" value="<?php echo $noMap ?>">
        <?php echo drawBoxes($sortArray, $tabText, $noMap); ?>
        <div style="clear: both;"></div>
    </form>
</body>
</html>