<?php
/*=======================================================================
 *
 * distance.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

include_once ("../include/global.inc.php");
include_once ("../include/auth.inc.php");

include_once('../geo/geocode.inc.php');


function draw_route($target,$stationlist,&$GlobalRouteList,&$imageurl,&$imageurlT,$targetmap = false)
{
  global $Application,$map_width,$map_height;

  list($tcpip,$path,$requestname,$imageurl) = GetNextRequestParameter($tcpip,$path,$requestname,$imageurl2,$map,$language);

  $RouteObject=null;

  include_once($Application['OBJECT_BASE'].'alroute.inc.php'); 

  $RouteObject = new ALRoute;

  $RouteObject->BPUseTCPIP="TRUE";
  $RouteObject->BPMaxCalcWait=60000;

  if ($Application["COM_LOG"]) 
      $RouteObject->BPLogFilePath=$Application["COM_LOG_FILE"];
  
  $RouteObject->BPParaRequestFileName=$requestname;
  $RouteObject->BPMapsByStream=false;
  $RouteObject->BPStreamDirectory=$Application["MAP_PATH"];

  // Language-Code: D=7, F=12, GB=9, I=16, E=10, NL=19, PT=22, SW=29
  $GetLanguageCode="7";
	
  $RouteObject->BFAddParam("CLIENT","LANGUAGEID",$GetLanguageCode);
							
  $RouteObject->BPALS=$tcpip;
  
  $stationdelimiter="|";
	
  $RouteObject->BFAddParam("CLIENT","STATIONDELIMITER",$stationdelimiter);

  // $stationen=intval(count($stationlist)/3);  
  // Fixed, because always "start" and "finish"
  $stationen=2;

  for ($i=1; $i<=$stationen; $i=$i+1)
      $RouteObject->BFAddParam("CLIENT","STATION" . $i, "COORDINATES" . $stationdelimiter . $stationlist["x" . $i] . $stationdelimiter . $stationlist["y" . $i] . $stationdelimiter . $stationlist["l" . $i]);
  
  $RouteObject->RouteTableDefString="nothing";
  $RouteObject->RouteInfo=true;
  $RouteObject->RouteNodeLevel=5;
  $RouteObject->RouteDetailLimit=10000;
  $RouteObject->BFAddParam("CLIENT","PACKEDROUTELIST", "TRUE");
  $RouteObject->AddToMap=false;

  $result=$RouteObject->RouteRequest("");

  if ($result!=2)
  	 $logicalrect="0,0,0,0";
  else {
    if ($target=="")
        $logicalrect=$RouteObject->BFGetParam($RouteObject->eATAns,"SERVER","LOGICALRECT","0,0,0,0");
    else
	$logicalrect=$RouteObject->BFGetParam($RouteObject->eATAns,"SERVER","LOGICALTARGETRECT","0,0,0,0");

    $num_objects=intval($RouteObject->BFGetParam($RouteObject->eATAns,"RESULT","NUMNODES","0"));
    $rowcount=0;
 
    for ($i=1; $i<=$num_objects; $i=$i+1)
         $GlobalRouteList["NODE_".$i]=$RouteObject->BFGetParam($RouteObject->eATAns,"RESULT","NODE".$i,"nada");

    $GlobalRouteList["DISTTODRIVE"]=  $RouteObject->BFGetParam($RouteObject->eATAns,"SERVER","DISTTODRIVE","");
    $GlobalRouteList["TIMETODRIVE"]=  $RouteObject->BFGetParam($RouteObject->eATAns,"SERVER","TIMETODRIVE","");
    $GlobalRouteList["COSTS"]=  $RouteObject->BFGetParam($RouteObject->eATAns,"SERVER","COSTS","");
    $GlobalRouteList["ARRIVALTIME"]=  $RouteObject->BFGetParam($RouteObject->eATAns,"SERVER","ARRIVALTIME","");
    $GlobalRouteList["DEPARTURETIME"]=  $RouteObject->BFGetParam($RouteObject->eATAns,"SERVER","DEPARTURETIME","");
    $GlobalRouteList["ARRIVALDATE"]=  $RouteObject->BFGetParam($RouteObject->eATAns,"SERVER","ARRIVALDATE","");
    $GlobalRouteList["DEPARTUREDATE"]=  $RouteObject->BFGetParam($RouteObject->eATAns,"SERVER","DEPARTUREDATE","");
    $RouteObject=null;
    
    return $logicalrect;
  } // error while routing

$RouteObject=null;
return $logicalrect;

}


// Inserts the distance of a specified from- and a specified to-address
// REMARK: This function should not be called directly! Use the function "getDistance()", because
//         a specified tour (adress to address) will be checked there and if the distance does not
//         exist, the route-server would be contacted to get the data which are automatically stored
//         into the database for invoicing!
// $adStreet1   : street of the from-address
// $adZipcode1  : zipcode of the from-address
// $adCity1     : city of the from-address
// $adHsno1     : house-number of the from-address
// $adStreet2   : street of the to-address
// $adZipcode2  : zipcode of the to-address
// $adCity2     : city of the to-address
// $adHsno2     : house-number of the to-address
function insertDistance($distance, $adStreet1, $adZipcode1, $adCity1, $adCountry1 = "DE", $adHsno1, $adStreet2, $adZipcode2, $adCity2, $adCountry2 = "DE", $adHsno2) {
  global $db, $PHP_SELF;
 
  $ok = FALSE;
 
  $distance = trim($distance);
  $adStreet1 = trim($adStreet1);
  $adZipcode1 = trim($adZipcode1);
  $adCity1 = trim($adCity1);
  $adCountry1 = trim($adCountry1);
  $adHsno1 = trim($adHsno1);
  $adStreet2 = trim($adStreet2);
  $adZipcode2 = trim($adZipcode2);
  $adCity2 = trim($adCity2);
  $adCountry2 = trim($adCountry2);
  $adHsno2 = trim($adHsno2);
  
  if ($adStreet1 != "" && $adZipcode1 != "" && $adCity1 != "" && $adCountry1 != "" && $adHsno1 != "" &&
      $adStreet2 != "" && $adZipcode2 != "" && $adCity2 != "" && $adCountry2 != "" && $adHsno2 != "" && $distance != ""):

      // Insert first address or get the existing address-id
      $tmpArray = insertAddress($adStreet1, $adZipcode1, $adCity1, $adCountry1);
      $adId1 = $tmpArray[0];
      
      // Insert second address or get the existing address-id
      $tmpArray = insertAddress($adStreet2, $adZipcode2, $adCity2, $adCountry2);
      $adId2 = $tmpArray[0];      

      $distance = str_replace (",", ".", $distance);
      
      // Insert distance
      insertStmt("distance", array("ad_id_from", $adId1, "ds_hsno_from", $adHsno1, 
                                   "ad_id_to", $adId2, "ds_hsno_to", $adHsno2, 
                                   "ds_distance", $distance));
      $ok = TRUE;      
  endif;      
        
  return $ok;
}

// Returns the distance of a specified from- and a specified to-address
// $adStreet1   : street of the from-address
// $adZipcode1  : zipcode of the from-address
// $adCity1     : city of the from-address
// $adHsno1     : house-number of the from-address
// $adStreet2   : street of the to-address
// $adZipcode2  : zipcode of the to-address
// $adCity2     : city of the to-address
// $adHsno2     : house-number of the to-address
function getDistance($adStreet1, $adZipcode1, $adCity1, $adCountry1 = "DE", $adHsno1, $adStreet2, $adZipcode2, $adCity2, $adCountry2 = "DE", $adHsno2) {
  return 0;  
  global $db, $PHP_SELF, $statusMessage;
  global $MGObject;

  $distance = "";  
  
  $adStreet1 = trim($adStreet1);
  $adZipcode1 = trim($adZipcode1);
  $adCity1 = trim($adCity1);
  $adCountry1 = trim($adCountry1);
  $adHsno1 = trim($adHsno1);
  $adStreet2 = trim($adStreet2);
  $adZipcode2 = trim($adZipcode2);
  $adCity2 = trim($adCity2);
  $adCountry2 = trim($adCountry2);
  $adHsno2 = trim($adHsno2);
  
  if ($adStreet1 != "" && $adZipcode1 != "" && $adCity1 != "" && $adCountry1 != "" && $adHsno1 != "" &&
      $adStreet2 != "" && $adZipcode2 != "" && $adCity2 != "" && $adCountry2 != "" && $adHsno2 != ""): 
     
      $sqlquery = "SELECT ds.ds_distance"
                . " FROM distance AS ds, address AS ad1, address AS ad2"
                . " WHERE ds.ds_hsno_from = '$adHsno1'"
                . "   AND ds.ds_hsno_to = '$adHsno2'"
                . "   AND ds.ad_id_from = ad1.ad_id"
                . "   AND ds.ad_id_to = ad2.ad_id"
                . "   AND ad1.ad_street = '$adStreet1'"
                . "   AND ad1.ad_zipcode = '$adZipcode1'"
                . "   AND ad1.ad_city = '$adCity1'"
                . "   AND ad1.ad_country = '$adCountry1'"
                . "   AND ad2.ad_street = '$adStreet2'"
                . "   AND ad2.ad_zipcode = '$adZipcode2'"
                . "   AND ad2.ad_city = '$adCity2'"
                . "   AND ad2.ad_country = '$adCountry2'";

      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      
      if ($row = $result->fetch_assoc()):         
             $distance = $row[ds_distance];
      endif;
      $result->free();

      // if $distance = 0 then get distance-data from route-server
      // ...
      if ($distance == "") :
                  
         // *** START-ADDRESS ***

            $resultType = getGeoCode($adStreet1,$adZipcode1,$adCity1,$adHsno1,$adCountry1,"");
      
            // resultType == 2 -> exact match
            if ($resultType == 2) :   

               // Geo-Coordinates
               $xcoord=$MGObject->GeoCoordinateX;
               $ycoord=$MGObject->GeoCoordinateY;         	
         	                  
               // Check for existing entry in address (because of redundance)
               if ($xcoord == "" || $xcoord == 0 || $ycoord == "" || $ycoord == 0):

                  $statusMessage = "Die Startadresse konnte nicht geocodiert werden!";
               endif;         
               
               // Initialize object
               $MGObject=null;                   
            endif;
         
         // *** FINISH-ADDRESS ***

            $resultType = getGeoCode($adStreet2,$adZipcode2,$adCity2,$adHsno2,$adCountry2,"");
      
            // resultType == 2 -> exact match
            if ($resultType == 2) :   

               // Geo-Coordinates
               $xcoord2=$MGObject->GeoCoordinateX;
               $ycoord2=$MGObject->GeoCoordinateY;         	
         	                  
               // Check for existing entry in address (because of redundance)
               if ($xcoord2 == "" || $xcoord2 == 0 || $ycoord2 == "" || $ycoord2 == 0):

                  $statusMessage = "Die Zieladresse konnte nicht geocodiert werden!";
               endif;     
               
               // Initialize object
               $MGObject=null;    
            endif;         
         
         // *** Computation of the distance and storing into the database ***

            if ($statusMessage == ""):

	       $stationlist["x1"]=$xcoord;
	       $stationlist["y1"]=$ycoord;
	       $stationlist["x2"]=$xcoord2;
	       $stationlist["y2"]=$ycoord2;
	       $GlobalRouteList="";
	       $logicalrect=draw_route($target,$stationlist,$GlobalRouteList,$imageurl,$imageurlT);
	       $distance =$GlobalRouteList["DISTTODRIVE"];
	       // $drivingTime = $GlobalRouteList["TIMETODRIVE"];

               // Insert the new distance-data from the route-server into the database for invoicing later on
               if ($distance != ""):
                  insertDistance($distance, $adStreet1, $adZipcode1, $adCity1, $adCountry1, $adHsno1, $adStreet2, $adZipcode2, $adCity2, $adCountry2, $adHsno2);
               endif;
            endif;         
      endif;
  endif;
  
  $distance = str_replace (",", ".", $distance);
        
  return $distance;        
}


// Returns the distance of a specified from- and a specified to-address
// $adId1       : ID of the from-address
// $adHsno1     : house-number of the from-address
// $adId2       : ID of the to-address
// $adHsno2     : house-number of the to-address
function getDistancePerID($adId1, $adHsno1, $adId2, $adHsno2) {
  
  global $db, $PHP_SELF, $statusMessage;
  global $MGObject;

  $distance = "";  
  
  $adId1 = trim($adId1);  
  $adHsno1 = trim($adHsno1);
  $adId2 = trim($adId2);    
  $adHsno2 = trim($adHsno2);
  
  if ($adId1 != "" && $adHsno1 != "" && $adId2 != "" && $adHsno2 != ""): 
     
      $sqlquery = "SELECT ds.ds_distance"
                . " FROM distance AS ds"
                . " WHERE ds.ds_hsno_from = '$adHsno1'"
                . "   AND ds.ds_hsno_to = '$adHsno2'"
                . "   AND ds.ad_id_from = $adId1"
                . "   AND ds.ad_id_to = $adId2";

      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      
      if ($row = $result->fetch_assoc()):         
             $distance = $row[ds_distance];
      endif;
      $result->free();

      // if $distance = 0 then get distance-data from route-server
      // ...
      if ($distance == "") :
                  
         // Check existence of the address-entries in the table "address"

            // Check from-address
            $tmpFields = getFieldsValueFromId("address","ad_id",$adId1,array("ad_street","ad_zipcode","ad_city","ad_country"));
            $adStreet1 = $tmpFields[0];
            $adZipcode1 = $tmpFields[1];
            $adCity1 = $tmpFields[2];
            $adCountry1 = $tmpFields[3];

            // If from-address does not exist then to-address has not to be checked
           if ($adStreet1 != "" && $adZipcode1 != "" && $adCity1 != "" && $adCountry1 != "" && $adHsno1 != ""): 
              
              // Check to-address            
              $tmpFields = getFieldsValueFromId("address","ad_id",$adId2,array("ad_street","ad_zipcode","ad_city","ad_country"));
              $adStreet2 = $tmpFields[0];
              $adZipcode2 = $tmpFields[1];
              $adCity2 = $tmpFields[2];
              $adCountry2 = $tmpFields[3];              
           endif;


           if ($adStreet1 != "" && $adZipcode1 != "" && $adCity1 != "" && $adCountry1 != "" && $adHsno1 != "" &&
               $adStreet2 != "" && $adZipcode2 != "" && $adCity2 != "" && $adCountry2 != "" && $adHsno2 != ""): 
               
               // Both addresses are existent and the distance can be computed
               $distance = getDistance($adStreet1, $adZipcode1, $adCity1, $adCountry1, $adHsno1, $adStreet2, $adZipcode2, $adCity2, $adCountry2, $adHsno2);
           endif;
      endif;
  endif;
  
  $distance = str_replace (",", ".", $distance);
        
  return $distance;        
}




// ACTIVATE ONLY FOR TESTING!!!

// $distance = getDistance("Alsterdorfer Str.", "22297", "Hamburg", "D", "190", "Am Ochsenzoll", "22851", "Norderstedt", "D", "147");
// echo "Distanz: " . $distance . "<br><br>";
// $distance = getDistance("Langer Kamp", "22850", "Norderstedt", "D", "124a", "Langer Kamp", "22850", "Norderstedt", "D", "1");
// echo "Distanz: " . $distance . "<br><br>";
// $distance = getDistance("Alsterdorfer Str.", "22297", "Hamburg", "D", "190", "Friedrichshulder Weg", "25469", "Halstenbek", "D", "81");
// echo "Distanz: " . $distance . "<br><br>";
// $distance = getDistancePerID(1, "124", 2, "147");
// echo "Distanz: " . $distance . "<br><br>";

// $x = getAddressFromGeoCode(52, 13);
// echo "DISTANCE:  ";
// echo $x[0] . "  " . $x[1] . "  " . $x[2] . "<br>";

?>
