<?php

include_once("../include/glob_defs.inc.php");
$dbhost="172.16.0.102:3391";
//writeLog("dbhost = '$dbhost'");

$mysql_db = mysql_connect($dbhost, $dblogin, $dbpassword) or die (mysql_error($mysql_db));
mysql_select_db("phoenix_log", $mysql_db) or die (mysql_error($mysql_db));
mysql_query('SET NAMES latin1', $mysql_db) or die ('SET NAMES latin1' . ": " . mysql_error($mysql_db));

XSplanTourJob(12809057);
XSplanTourJob(12809058);
XSplanTourJob(12809059);
XSplanTourJob(12809060);
XSplanTourJob(12809061);

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';
  
  mysql_connect("172.16.0.111:3711", "phoenix", "AdAdgkS13") or die (mysql_error());
  mysql_select_db("address_geo") or die (mysql_error());
  mysql_query('SET NAMES latin1') or die ('SET NAMES latin1');

  $sqlquery = "SELECT adg_gps_long, adg_gps_lat FROM address_geo.address AS ad, address_geo.address_geo AS adg WHERE " .
    "ad.ad_country = '$ad_country' AND ad.ad_zipcode = '$ad_zipcode' AND ad.ad_city = '$ad_city' AND ad.ad_street = '$ad_street' " . 
    "AND ad.ad_id = adg.ad_id AND adg.adg_hsno = '$tr_hsno'";
  $res = mysql_query($sqlquery) or die ($sqlquery);
  if ($row = mysql_fetch_array($res, MYSQL_ASSOC)):  
    writeLog("[$ad_country $ad_zipcode " . utf8_encode($ad_city) . " " . utf8_encode($ad_street) . " $tr_hsno] found in address_geo: " . $row["adg_gps_long"] . ", " . $row["adg_gps_lat"] . "\n");
    $retA[] = array(100, $row["adg_gps_long"], $row["adg_gps_lat"]);
    return $retA;
  endif;
  mysql_free_result($res);
 
  $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_country . '"' . "\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);
    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";
      }
      $score = $vals[$index['NS2:RESULTADDRESS'][$j]]['attributes']['TOTALSCORE'];
      $X = round($vals[$index['NS6:POINT'][$i]]['attributes']['X']) / 100000;
      $Y = round($vals[$index['NS6:POINT'][$i]]['attributes']['Y']) / 100000;
      $log_txt .= "Y, X = " . $X . ", " . $Y . "\n";
      $retA[] = array($score, $X, $Y);
      if ($score == 100 && count($retA) == 1):
        $ad_id = "";
        $sqlquery = "SELECT ad_id FROM address WHERE ad_street = '$ad_street' AND ad_zipcode = '$ad_zipcode' AND ad_city = '$ad_city' AND ad_country = '$ad_country'";
        $res = mysql_query($sqlquery) or die ($sqlquery);
        if ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
          $ad_id = $row["ad_id"];
        endif;
        mysql_free_result($res);
        if ($ad_id == ""):
          $sqlquery = "INSERT INTO address (ad_street, ad_zipcode, ad_city, ad_country) VALUES ('$ad_street', '$ad_zipcode', '$ad_city', '$ad_country')";
          mysql_query($sqlquery) or die ($sqlquery);
          $ad_id = mysql_insert_id();
        endif;
        $sqlquery = "INSERT INTO address_geo (ad_id, adg_hsno, adg_gps_long, adg_gps_lat) VALUES ('$ad_id', '$tr_hsno', '" . $X . "', '" . $Y . "')";
        mysql_query($sqlquery) or die ($sqlquery);
      endif;
    endfor;
//    echo "Index array\n";
//    print_r($index);
//    echo "\nVals array\n";
//    print_r($vals);
  endif;
  writeLog($log_txt);
  return $retA;
}

function XSplanTour($stopCoordinates)
{
//  $XS_HOST = 'localhost';
  $XS_HOST = '172.16.0.154';
  $XS_PORT = 50050;
  $XS_SERVICE = '/xsequence/ws/XSequence';

  $outStops = '';
  $subStops = '';
  foreach ($stopCoordinates as $idx => $pair) {
    $outStops .=
      '    <ns2:Stop servicePeriod="0" stopID="' . ($idx + 1) . '" xsi:type="ns2:Stop">' . "\n" .
      '      <ns2:loc x="' . round($pair[0]) . '" y="' . round($pair[1]) . '"/>' . "\n" .
      '    </ns2:Stop>' . "\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:planTour>' . "\n" .
    '      <ns3:ArrayOfStop_1>' . "\n" .
    $outStops .
    '      </ns3:ArrayOfStop_1>' . "\n" .
    '      <ns3:PlanningParams_2 xsi:type="ns2:PlanningParams">' . "\n" .
    '        <ns2:distanceCalculation dimaCoordFormat="GEODECIMAL" drivingPeriodFactor="1.0" geometricSpeed="60"/>' . "\n" .
    '      </ns3:PlanningParams_2>' . "\n" .
    '      <ns3:InputTour_3 xsi:type="ns2:InputTour">' . "\n" .
    '        <ns2:wrappedInputTourPoints>' . "\n" .
    $subStops .
    '        </ns2:wrappedInputTourPoints>' . "\n" .
    '        <ns2:subSequence predPos="1" succPos="' . (count($stopCoordinates)  + 1) . '"/>' . "\n" .
    '      </ns3:InputTour_3>' . "\n" .
    '      <ns3:CallerContext_4 xsi:nil="1"/>' . "\n" .
    '    </ns3:planTour>' . "\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)) {
    echo $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";
    }
    foreach ($index['NS17:OUTPUTTOURPOINT'] AS $otp) {
      $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);
  return $retA;
}

function XSplanTourJob($jb_id_plan)
{
  global $mysql_db;

  $stopCoordinates = array();
  $sqlquery = "SELECT ad_country, ad_zipcode, ad_city, ad_street, tr_hsno FROM phoenix.tour As tr, phoenix.address AS ad WHERE jb_id = $jb_id_plan AND tr.ad_id = ad.ad_id ORDER BY tr_sort";  
  $res = mysql_query($sqlquery, $mysql_db) or die ($sqlquery . ": " . mysql_error($mysql_db));
  $i = 0;  
  while ($row = mysql_fetch_array($res, MYSQL_ASSOC)):
    $coords = XSfindAddress("D", $row["ad_zipcode"], $row["ad_city"], $row["ad_street"], $row["tr_hsno"]);
    if ($coords[0][0] != 100) {
       echo " kein exakter Match<br>\n"; flush();
       echo "<b>Routenoptmierung nicht m&ouml;glich!</b><br>\n";
       die();
//    } else {
//       echo " ok<br>\n"; flush();
    }
    $stopCoordinates[$i++] = array($coords[0][1] * 100000, $coords[0][2] * 100000);
  endwhile;
  mysql_free_result($res);
//print_r($stopCoordinates);
//die();
  $planTour = XSplanTour($stopCoordinates);

  if (count($planTour) > 0):
    // bestehenden tr_sort mit 100 addieren
    for ($i = 0; $i < count($planTour); $i++) {
	    exec_query("UPDATE phoenix.tour SET tr_sort = " . (100 + $i + 1) . " WHERE jb_id = $jb_id_plan AND tr_sort = " . ($i+1));
      exec_query("UPDATE phoenix.tourarticle SET tr_sort = " . (100 + $i + 1) . " WHERE jb_id = $jb_id_plan AND tr_sort = " . ($i+1));
	    
    }  
    // jetzt k�n die neuen tr_sort geschrieben werden
    for ($i = 0; $i < count($planTour); $i++) {
	    exec_query("UPDATE phoenix.tour SET tr_sort = " . ($i + 1) . " WHERE jb_id = $jb_id_plan AND tr_sort = " . (100 + $planTour[$i]));
      exec_query("UPDATE phoenix.tourarticle SET tr_sort = " . ($i + 1) . " WHERE jb_id = $jb_id_plan AND 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 exec_query($sqlquery) {
	global $mysql_db;
//	echo $sqlquery . "\n";
  mysql_query($sqlquery, $mysql_db) or die ($sqlquery . ": " . mysql_error($mysql_db));	
}

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

?>