<?php

include_once("../include/dbglobal.inc.php");

$allCoords = array();

//$coords = XSfindAddress("D", "25469", "Halstenbek", "Friedrichshulder Weg", "81");
//echo $coords[0][1] . ", " . $coords[0][2] . "<br>\n";
//$allCoords[] = array($coords[0][1], $coords[0][2], 8*3600, 14*3600);
//$coords = XSfindAddress("D", "22848", "Norderstedt", "Ochsenzoller Straße", "31");
//echo $coords[0][1] . ", " . $coords[0][2] . "<br>\n";
//$allCoords[] = array($coords[0][1], $coords[0][2], 12.5*3600, 19*3600);
//$coords = XSfindAddress("D", "21502", "Geesthacht", "Gerhart-Hauptmann-Weg", "14");
//echo $coords[0][1] . ", " . $coords[0][2] . "<br>\n";
//$allCoords[] = array($coords[0][1], $coords[0][2], 8*3600, 14*3600);
//$coords = XSfindAddress("D", "25421", "Pinneberg", "Oeltingsallee", "1b");
//echo $coords[0][1] . ", " . $coords[0][2] . "<br>\n";
//$allCoords[] = array($coords[0][1], $coords[0][2], 13*3600, 19*3600);
//$coords = XSfindAddress("D", "22041", "Hamburg", "Holzmühlenstraße", "41");
//echo $coords[0][1] . ", " . $coords[0][2] . "<br>\n";
//$allCoords[] = array($coords[0][1], $coords[0][2], 8*3600, 14*3600);
//$coords = XSfindAddress("D", "22525", "Hamburg", "Ottensener Straße", "8");
//echo $coords[0][1] . ", " . $coords[0][2] . "<br>\n";
//$allCoords[] = array($coords[0][1], $coords[0][2], 13*3600, 19*3600);
//print_r(XSplanTimewindowTour($allCoords));

//XSplanTour(array(
//  array(843650, 4901137),
//  array(842164, 4901883),
//  array(843914, 4900754),
//  array(841020, 4900941),
//  array(841050, 4900578))
//);

function XSfindAddress($ad_country, $ad_zipcode, $ad_city, $ad_street, $tr_hsno)
{
//  $XS_HOST = 'localhost';
  $XS_HOST = '172.16.0.154';
  $XS_PORT = 50020;
  $XS_SERVICE = '/xlocate/ws/XLocate';

  $out = 
    '<?xml version="1.0" encoding="utf-8"?>' . "\n" .
    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' . "\n" .
    '    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' . "\n" .
    '    xmlns:xsd="http://www.w3.org/2001/XMLSchema">' . "\n" .
    '  <soap:Body>' . "\n" .
    '    <findAddress xmlns="http://types.xlocate.xserver.ptvag.com">' . "\n" .
    '      <Address_1' . "\n" .
    '        country="'. $ad_county . '"' . "\n" .
    '        postCode="'. $ad_zipcode . '"' . "\n" .
    '        city="'. utf8_encode($ad_city) . '"' . "\n" .
    '        city2=""' . "\n" .
    '        street="'. utf8_encode($ad_street) . '"' . "\n" .
    '        houseNumber="'. $tr_hsno . '"' . "\n" .
    '      />' . "\n" .
    '      <ArrayOfSearchOptionBase_2 xsi:nil="true" />' . "\n" .
    '      <ArrayOfSortOption_3 xsi:nil="true" />' . "\n" .
    '      <ArrayOfResultField_4 xsi:nil="true" />' . "\n" .
    '      <CallerContext_5 log1="" log2="" log3="">' . "\n" .
    '        <wrappedProperties xmlns="http://baseservices.service.jabba.ptvag.com">' . "\n" .
    '          <CallerContextProperty key="CoordFormat" value="PTV_GEODECIMAL" />' . "\n" .
    '          <CallerContextProperty key="Profile" value="default" />' . "\n" .
    '        </wrappedProperties>' . "\n" .
    '      </CallerContext_5>' . "\n" .
    '    </findAddress>' . "\n" .
    '  </soap:Body>' . "\n" .
    '</soap:Envelope>' . "\n" .
    "\n";
    
  $res = xmlRequest($XS_HOST, $XS_PORT, $XS_SERVICE, $out);
  $vals = $res[0];
  $index = $res[1];
  
  $log_txt = "********************************************************************************\n" . $out;
  $retA = array();
  if (array_key_exists('SOAP:FAULT', $index)) {
    echo $vals[$index['FAULTCODE'][0]]['value'] . " : " . $vals[$index['FAULTSTRING'][0]]['value'] . "\n";
    writeLog($log_txt, "xServer.inc");
    die();
  } else {
    $log_txt .= "ERRORCODE=" . $vals[$index['RESULT'][0]]['attributes']['ERRORCODE'] . "\n";
    $i = 0;
    for ($i = 0, $j = 0; $i < count($index['NS6:POINT']); $i++, $j += 2) {
      $log_txt .=  "\n";
      foreach ($vals[$index['NS2:RESULTADDRESS'][$j]]['attributes'] AS $attr => $val) {
        $log_txt .= "$attr: " . $val . "\n";
      }
      $log_txt .= "Y, X = " . $vals[$index['NS6:POINT'][$i]]['attributes']['Y'] . ", " . $vals[$index['NS6:POINT'][$i]]['attributes']['X'] . "\n";      
      $retA[] = array($vals[$index['NS2:RESULTADDRESS'][$j]]['attributes']['TOTALSCORE'], $vals[$index['NS6:POINT'][$i]]['attributes']['X'], $vals[$index['NS6:POINT'][$i]]['attributes']['Y']);
    }
//    echo "Index array\n";
//    print_r($index);
//    echo "\nVals array\n";
//    print_r($vals);
  }
  writeLog($log_txt, "xServer.inc");
  return $retA;
}

function XSplanTimewindowTour($stopCoordinates, $predPos = 0, $succPos = 0)
{
//  $XS_HOST = 'localhost';
  $XS_HOST = '172.16.0.154';
  $XS_PORT = 50050;
  $XS_SERVICE = '/xsequence/ws/XSequence';

//  if $predPos == 0
  if ($succPos == 0)
    $succPos = count($stopCoordinates) + 1;
  $outStops = '';
  $subStops = '';
  foreach ($stopCoordinates as $idx => $pairs) {
    $outStops .=
      '        <ns2:TimewindowStop stopID="' . ($idx + 1) . '" xsi:type="ns2:TimewindowStop">' . "\n" .
//      '        <ns2:TimewindowStop servicePeriod="900" stopID="' . ($idx + 1) . '" xsi:type="ns2:TimewindowStop">' . "\n" .
      '          <ns2:loc x="' . round($pairs[0]) . '" y="' . round($pairs[1]) . '"/>' . "\n" .
      '          <ns2:wrappedOpeningIntervals>' . "\n" .
      '            <ns2:Interval from="' . $pairs[2] . '" till="' . $pairs[3] . '"/>' . "\n" .
      '          </ns2:wrappedOpeningIntervals>' . "\n" .
      '        </ns2:TimewindowStop>' . "\n";
    $subStops .=  '          <ns2:InputTourPoint stopID="' . ($idx + 1) . '"/>' . "\n";
  }

//  $planningParams->costDistanceKm = 10;
//  $planningParams->costPeriodMinute = 50;
//  $planningParams->maxProcessorPeriod = 5;
//  $planningParams->distanceCalculation->dimaCoordFormat = 'GEODECIMAL';

  $out = 
    '<?xml version="1.0" encoding="utf-8"?>' . "\n" .
    '<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"' .
    ' xmlns:enc="http://schemas.xmlsoap.org/soap/encoding/"' .
    ' xmlns:ns0="http://exception.core.jabba.ptvag.com"' .
    ' xmlns:ns1="http://common.xserver.ptvag.com"' .
    ' xmlns:ns2="http://xsequence.xserver.ptvag.com"' .
    ' xmlns:ns3="http://types.xsequence.xserver.ptvag.com"' .
    ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' .
    ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' . "\n" .
    '  <env:Body>' . "\n" .
    '    <ns3:planTimewindowTour>' . "\n" .
    '      <ns3:ArrayOfTimewindowStop_1>' . "\n" .
    $outStops .
    '      </ns3:ArrayOfTimewindowStop_1>' . "\n" .
    '      <ns3:TimewindowPlanningParams_2 xsi:type="ns2:TimewindowPlanningParams">' . "\n" .
    '        <ns2:distanceCalculation dimaCoordFormat="GEODECIMAL" drivingPeriodFactor="1.0"/>' . "\n" .
    '        <ns2:wrappedOperatingIntervals>' . "\n" .
    '          <ns2:Interval from="25200" till="72000"/>' . "\n" .
    '        </ns2:wrappedOperatingIntervals>' . "\n" .
    '      </ns3:TimewindowPlanningParams_2>' . "\n" .
    '      <ns3:InputTour_3 xsi:type="ns2:InputTour">' . "\n" .
    '        <ns2:wrappedInputTourPoints>' . "\n" .
    $subStops .
    '        </ns2:wrappedInputTourPoints>' . "\n" .
    '        <ns2:subSequence predPos="' . $predPos . '" succPos="' . $succPos . '"/>' . "\n" .
    '      </ns3:InputTour_3>' . "\n" .
    '      <ns3:CallerContext_4 xsi:nil="1"/>' . "\n" .
    '    </ns3:planTimewindowTour>' . "\n" .
    '  </env:Body>' . "\n" .
    '</env:Envelope>' . "\n" .
    "\n";
//echo $out;

  $res = xmlRequest($XS_HOST, $XS_PORT, $XS_SERVICE, $out);
  $vals = $res[0];
  $index = $res[1];

  $log_txt = "********************************************************************************\n" . $out;
  $retA = array();
  if (array_key_exists('SOAP:FAULT', $index)) {
    $log_txt .= $vals[$index['FAULTCODE'][0]]['value'] . " : " . $vals[$index['FAULTSTRING'][0]]['value'] . "\n";
//    die();
  } else {  
    $log_txt .= "RESULT=" . $vals[$index['NS2:RESULT'][0]]['attributes']['RESULT'] . "\n\n";
    foreach ($vals[$index['NS17:TOUR'][0]]['attributes'] AS $attr => $val) {
      $log_txt .= "$attr: $val\n";
    }
    for ($i = 0; $i < count($index['NS17:OUTPUTTOURPOINT']); $i += 2) {
      $otp = $index['NS17:OUTPUTTOURPOINT'][$i];
      $log_txt .=  "\n";
      $retA[] = $vals[$otp]['attributes']['STOPID'];
      foreach ($vals[$otp]['attributes'] AS $attr => $val) {
        $log_txt .= "$attr: $val\n";
      }
    }
//    echo "Index array\n";
//    print_r($index);
//    echo "\nVals array\n";
//    print_r($vals);
  }
  writeLog($log_txt, "xServer.inc");
  return $retA;
}

function XSplanTourJob($jb_id_plan, $predPos = 0, $succPos = 0)
{
  global $db;

  $stopCoordinates = array();
  $sqlquery = "SELECT tr_cs_freetext, tr_commission_no FROM tour WHERE jb_id = $jb_id_plan ORDER BY tr_sort";  
  $res = $db->query($sqlquery);
  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery'" . $res->getMessage());
  $i = 0;
  while ($row = $res->fetch_assoc()):
    $interval = array();
    if ($row["tr_commission_no"] == "07 - 09 Uhr")
      $interval = array(7*3600, 9*3600);
    if ($row["tr_commission_no"] == "08 - 19 Uhr")
      $interval = array(8*3600, 19*3600);
    if ($row["tr_commission_no"] == "08 - 14 Uhr")
      $interval = array(8*3600, 14*3600);
    if ($row["tr_commission_no"] == "13 - 19 Uhr")
      $interval = array(13*3600, 19*3600);
    if ($row["tr_commission_no"] == "16 - 20 Uhr")
      $interval = array(16*3600, 20*3600);
    $coords = explode(",", $row["tr_cs_freetext"]);
    $stopCoordinates[$i++] = array($coords[0], $coords[1], $interval[0], $interval[1]);
  endwhile;
  $res->free();

  $stopIt = false;
  do {
    $planTour = XSplanTimewindowTour($stopCoordinates, $predPos, $succPos);
    if (count($planTour) == 0):
      for ($i = 1; $i < count($stopCoordinates); $i++):
        $stopCoordinates[$i][2] -= 300;
        $stopCoordinates[$i][3] += 300;
        if ($stopCoordinates[$i][2] < 0 OR $stopCoordinates[$i][3] > 86400):
          $stopIt = true;
          break;
        endif;
      endfor;
    endif;
  } while (count($planTour) == 0 && !$stopIt);

  if (count($planTour) > 0):
    // bestehenden tr_sort mit 100 addieren
    for ($i = 0; $i < count($planTour); $i++) {
      updateStmt("tour", "jb_id", $jb_id_plan, array("tr_sort", 100 + $i + 1), "tr_sort = " . ($i+1));
    }  
    // jetzt können die neuen tr_sort geschrieben werden
    for ($i = 0; $i < count($planTour); $i++) {
      updateStmt("tour", "jb_id", $jb_id_plan, array("tr_sort", $i + 1), "tr_sort = " . (100 + $planTour[$i]));
    }
    return true;
  endif;
  return false;
}

function xmlRequest($host, $port, $service, $xmlReq)
{
  $fp = fsockopen($host, $port, $errno, $errstr, 30);

  if (!$fp) {
    echo "$errstr ($errno)<br />\n";
  } else {
    fputs ($fp, "POST $service HTTP/1.1\r\n");
    fputs ($fp, "Host: localhost\r\n");
    fputs ($fp, "Content-type: text/xml; charset=utf-8\r\n");
    fputs ($fp, "Content-length: " . strlen($xmlReq) . "\r\n");
    fputs ($fp, "Connection: close\r\n\r\n");
    fputs ($fp, $xmlReq);
    $line = "";
    while (substr($line, 0, 14) != "<soap:Envelope" && !feof($fp)) {
      $line = fgets($fp, 128);
    }
    $in = $line;
    while (!feof($fp)) {
      $in .= fgets($fp, 128);
    }
    fclose($fp);

//echo $in;
    $p = xml_parser_create();
    xml_parse_into_struct($p, $in, $vals, $index);
    xml_parser_free($p);
    
    return (array($vals, $index));
  }
}

function writeLog($log_text, $log_file) {
  $today = getdate();
  $fileHandle = @fopen("../log/" . $log_file . "_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
  @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] " . $log_text .  "\n");
  @fclose($fileHandle);
  return;
}


/*******************************************************************************

Working:

<?xml version="1.0" encoding="utf-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns0="http://exception.core.jabba.ptvag.com" xmlns:ns1="http://common.xserver.ptvag.com" xmlns:ns2="http://xsequence.xserver.ptvag.com" xmlns:ns3="http://types.xsequence.xserver.ptvag.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <env:Body>
    <ns3:planTimewindowTour>
      <ns3:ArrayOfTimewindowStop_1>
        <ns2:TimewindowStop servicePeriod="1800" stopID="1" xsi:type="ns2:TimewindowStop">
          <ns2:loc x="983547" y="5362310"/>
          <ns2:wrappedOpeningIntervals>
            <ns2:Interval from="28800" till="50400"/>
          </ns2:wrappedOpeningIntervals>
        </ns2:TimewindowStop>
        <ns2:TimewindowStop servicePeriod="1800" stopID="2" xsi:type="ns2:TimewindowStop">
          <ns2:loc x="997272" y="5367644"/>
          <ns2:wrappedOpeningIntervals>
            <ns2:Interval from="46061" till="68400"/>
          </ns2:wrappedOpeningIntervals>
        </ns2:TimewindowStop>
        <ns2:TimewindowStop servicePeriod="1800" stopID="3" xsi:type="ns2:TimewindowStop">
          <ns2:loc x="1043632" y="5341378"/>
          <ns2:wrappedOpeningIntervals>
            <ns2:Interval from="28800" till="50400"/>
          </ns2:wrappedOpeningIntervals>
        </ns2:TimewindowStop>
      </ns3:ArrayOfTimewindowStop_1>
      <ns3:TimewindowPlanningParams_2 xsi:type="ns2:TimewindowPlanningParams">
        <ns2:distanceCalculation dimaCoordFormat="GEODECIMAL" drivingPeriodFactor="1.0"/>
      </ns3:TimewindowPlanningParams_2>
      <ns3:InputTour_3 xsi:type="ns2:InputTour">
        <ns2:wrappedInputTourPoints>
          <ns2:InputTourPoint stopID="1"/>
          <ns2:InputTourPoint stopID="2"/>
          <ns2:InputTourPoint stopID="3"/>
        </ns2:wrappedInputTourPoints>
        <ns2:subSequence predPos="0" succPos="4"/>
      </ns3:InputTour_3>
      <ns3:CallerContext_4 xsi:nil="1"/>
    </ns3:planTimewindowTour>
  </env:Body>
</env:Envelope>

Not working:

<?xml version="1.0" encoding="utf-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns0="http://exception.core.jabba.ptvag.com" xmlns:ns1="http://common.xserver.ptvag.com" xmlns:ns2="http://xsequence.xserver.ptvag.com" xmlns:ns3="http://types.xsequence.xserver.ptvag.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <env:Body>
    <ns3:planTimewindowTour>
      <ns3:ArrayOfTimewindowStop_1>
        <ns2:TimewindowStop servicePeriod="1800" stopID="1" xsi:type="ns2:TimewindowStop">
          <ns2:loc x="983547" y="5362310"/>
          <ns2:wrappedOpeningIntervals>
            <ns2:Interval from="28800" till="50400"/>
          </ns2:wrappedOpeningIntervals>
        </ns2:TimewindowStop>
        <ns2:TimewindowStop servicePeriod="1800" stopID="2" xsi:type="ns2:TimewindowStop">
          <ns2:loc x="997272" y="5367644"/>
          <ns2:wrappedOpeningIntervals>
            <ns2:Interval from="46062" till="68400"/>
          </ns2:wrappedOpeningIntervals>
        </ns2:TimewindowStop>
        <ns2:TimewindowStop servicePeriod="1800" stopID="3" xsi:type="ns2:TimewindowStop">
          <ns2:loc x="1043632" y="5341378"/>
          <ns2:wrappedOpeningIntervals>
            <ns2:Interval from="28800" till="50400"/>
          </ns2:wrappedOpeningIntervals>
        </ns2:TimewindowStop>
      </ns3:ArrayOfTimewindowStop_1>
      <ns3:TimewindowPlanningParams_2 xsi:type="ns2:TimewindowPlanningParams">
        <ns2:distanceCalculation dimaCoordFormat="GEODECIMAL" drivingPeriodFactor="1.0"/>
      </ns3:TimewindowPlanningParams_2>
      <ns3:InputTour_3 xsi:type="ns2:InputTour">
        <ns2:wrappedInputTourPoints>
          <ns2:InputTourPoint stopID="1"/>
          <ns2:InputTourPoint stopID="2"/>
          <ns2:InputTourPoint stopID="3"/>
        </ns2:wrappedInputTourPoints>
        <ns2:subSequence predPos="0" succPos="4"/>
      </ns3:InputTour_3>
      <ns3:CallerContext_4 xsi:nil="1"/>
    </ns3:planTimewindowTour>
  </env:Body>
</env:Envelope>
*******************************************************************************/

?>