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

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

$autoMode = false;
$hq_id = "";
$hqId = "";
$locationZipcode = "";
if (!isset($argv[1]) || $argv[1] == "") :
   include_once ("../include/auth.inc.php");
   $autoMode = false;
else :
   if ($argv[1] == "acapella7890") : $autoMode = true; endif;
   if (isset($argv[2]) && $argv[2] != "") : $hqId = $argv[2]; endif;
   if (isset($argv[3]) && $argv[3] != "") : $locationZipcode = $argv[3]; endif;
endif;
$standalone = "YES";  // Needed for "ranking.inc.php"
include_once ("../include/ranking.inc.php");
include_once ("../include/pnpoly.inc.php");
include_once ('../include/email/htmlMimeMail.php');
$hq_id = $hqId;


// ***********************
// * General definitions *
// ***********************

// Proxy und Port fuer HTTPS
$proxy = "";

// $port = ":9883";  // D2 LBS-Testsystem
$port = ":705";   // D2 LBS-Live
$constPort = getParameterValue("0", "LOCATING_LBS_PORT", "0");
if ($constPort != "") : $port = $constPort; endif;

// $server = "213.148.156.83";     // D2 LBS-Testsystem
$server = "139.7.25.166";     // D2 LBS-Live
$constServer = getParameterValue("0", "LOCATING_LBS_SERVER", "0");
if ($constServer != "") : $server = $constServer; endif;

// Access to a special remote file
// $file = "ats/receiver";     // D2 LBS-Testsystem
$file = "LocationQueryService";     // D2 LBS-Live

// Request id
// $requestID = "1";
$requestID = rand(1,30000);

// User and password
$vaspID = "mi2ju GmbH";     // D2 Live
$constVaspID = getParameterValue("0", "LOCATING_LBS_VASP_ID", "0");
if ($constVaspID != "") : $vaspID = $constVaspID; endif;

$password = "mi2ju03#";     // D2 Live
$constPassword = getParameterValue("0", "LOCATING_LBS_PASSWORD", "0");
if ($constPassword != "") : $password = $constPassword; endif;

// Service ID
// $serviceId = "mi2juTest";   // D2 Testsystem
$serviceId = "mi2ju";       // D2 Live
$constServiceId = getParameterValue("0", "LOCATING_LBS_SERVICE_ID", "0");
if ($constServiceId != "") : $serviceId = $constServiceId; endif;

$constPort = getParameterValue("0", "LOCATING_LBS_PORT", "0");

// Only for output
$msg = "";

// Logging enabled
$loggingEnabled = TRUE;
$logFile = "../log/COM_LOG";

// Echo enabled
$echoEnabled = FALSE;


// *************
// * Functions *
// *************

function writeLocatingLog($file, $value) {
   global $loggingEnabled;
   if ($loggingEnabled) :
      writeToFile($file, $value);
   endif;
}

function connectD2($completeReq) {
	 global $server, $port;
   $response = "";
   $errno = "";
   $errstr = "";
   $fp = fsockopen ($server, substr($port, 1), @$errno, @$errstr, 10);
   if (!$fp) {
       $response = "$errstr ($errno)<br>\n";
   } else {
       fputs ($fp, $completeReq);
       if (fflush($fp)) :

          // Read header
          $httpHeader = "";
          $httpBodyLength = 0;
          if (!feof($fp)) :
             $line = trim(fgets ($fp,1024));
             $httpHeader .= trim($line);
             while (!feof($fp) && $line != "") {
          	     $line = trim(fgets ($fp,1024));
          	     $httpHeader .= $line;
          	     if (!(strpos($line, "Content-Length: ") === FALSE)) :
          	        $httpBodyLength = trim(substr($line, 16));
          	     endif;
             }
          endif;
          $count = 0;
          while (!feof($fp) && $count < $httpBodyLength) {
          	 $line = trim(fgets ($fp,2));
             $response .= $line;
             $count++;
          }
       else :
          $response = "ERR: " . $errno . " " . $errstr;
       endif;
       
       fclose ($fp);
   }
   return $response;
}

if ($hq_id != "" && is_numeric($hq_id) && $locationZipcode != "" && ($autoMode || $usr_id == "00000")) :
   // Get user
   if (!$autoMode) :
      $usrName = getFieldValueFromId("user","usr_id",$usr_id,"usr_name");
      $usrFirstname = getFieldValueFromId("user","usr_id",$usr_id,"usr_firstname");
   endif;

   // Init
   $sendPerMail = false;
   $f_secretFileName = "";
   $constCountryModePrefix = getParameterValue("0", "COUNTRY_FON_PREFIX", $hq_id);

   $currentDate = getDateTime("1");
   $currentDateTime = getDateTime("6");
   
   $triggerArray = array();

   $sqlquery = "SELECT hq.hq_mnemonic, cr.cr_sid, usr.usr_name, usr.usr_firstname"
             . " FROM courier AS cr, user AS usr, headquarters AS hq"
             . " WHERE cr.hq_id = '" . $hq_id . "' AND"
             . "       cr.cr_available = '1' AND"
             . "       cr.cr_locationzipcode = '" . $locationZipcode . "' AND"
             . "       cr.usr_id = usr.usr_id AND"
             . "       cr.hq_id = hq.hq_id";
   $result = $db->query($sqlquery);   
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   while ($row = $result->fetch_assoc()):
         $triggerArray[] = array($row["hq_mnemonic"], $row["cr_sid"], $row["usr_firstname"], $row["usr_name"]);
   endwhile;
   $result->free();

   $triggerArrayLen = count($triggerArray);
   $triggerOut = "";
   if ($triggerArrayLen > 0) :
      $sendPerMail = true;  // At least one event to be mailed
      $triggerOut .= "<html>\n";
      $triggerOut .= "<body>\n";
      $triggerOut .= "<table>\n";
      for ($i = 0; $i < $triggerArrayLen; $i++) :
          $tmpArray = $triggerArray[$i];
          $tmpArrayLen = count($tmpArray);
          $triggerOut .= "<tr>\n";
          for ($j = 0; $j < $tmpArrayLen; $j++) :
              $triggerOut .= "<td>" . $tmpArray[$j] . "&nbsp;&nbsp;&nbsp;</td>\n";

              if ($j == 1) :
                 // Init locating per cr_sid in $tmpArray[1]
                 // Get courier-id from the courier-sid (e.g. SIDs: 1013, 1019, etc.)
                 $cr_id = getFieldValueFromId("courier","cr_sid",$tmpArray[$j],"cr_id");
                 $msisdn = getFieldValueFromId("courier","cr_id",$cr_id,"cr_mobile_pda");
                 $msisdn = ereg_replace (" ", "", $msisdn);
                 $msisdn = str_replace("+", "", $msisdn);
                 if (!ereg("^" . $constCountryModePrefix, $msisdn)) : 
                    if (ereg("^0", $msisdn)) :
                       $msisdn = substr($msisdn, 1);
                    endif;
                    $msisdn = $constCountryModePrefix . $msisdn;
                 endif;
                 
                 // Check necessity of new locating process
                 $locatingStateArray = checkLocatingState($cr_id);
                 
                 if ($locatingStateArray[0] == "1") :
                    // Define header request
                    $requestheaderOrg = "POST /" . $file . " HTTP/1.1\r\n" .
                    "Host: $server$port\r\n" .
                    "Content-Type: application/x-www-form-urlencoded\r\n" .
                    "Content-Length: LENGTH\r\n\r\n";
                    // Connection request
                    $requestContext = "<?xml version='1.0'?><!DOCTYPE HDR SYSTEM 'MLEP_HDR.DTD'><HDR ver='1.0'><CLIENT><ID>$vaspID</ID><PWD>$password</PWD><SERVICEID>$serviceId</SERVICEID><SERVICE_TYPE service_type_type='PASSIVE'/></CLIENT></HDR>";
                    $requestMethod = "SLIR";
                    $requestBody = "<?xml version='1.0'?><!DOCTYPE SLIR SYSTEM 'MLEP_SLIR.DTD'><SLIR ver='1.0'><MSIDS><MSID>" . $msisdn . "</MSID></MSIDS></SLIR>";
                    $requestContext = urlencode($requestContext);
                    $requestBody = urlencode($requestBody);
                    // Merge "Context", "Method" and "Body"
                    $requestContext = "Context=" . $requestContext . "&Method=" . $requestMethod . "&Body=" . $requestBody;
                    $laenge = strlen($requestContext);
                    $requestheader = $requestheaderOrg;
                    $requestheader = str_replace ("LENGTH", $laenge, $requestheader);
                    if ($echoEnabled) : echo $requestheader . $requestContext . "\n\n\n"; endif;
                    writeLocatingLog($logFile, $requestheader . $requestContext . "\r\n");
                    $currentTime = getDateTime("0");
                    writeLocatingLog($logFile, "Time begin: " . $currentTime . "\r\n");
                    $response = connectD2($requestheader.$requestContext."\r\n");
                    $currentTime = getDateTime("0");
                    writeLocatingLog($logFile, "Time end: " . $currentTime . "\r\n");
                    if ($echoEnabled) : echo $response . "\n\n\n"; endif;
                    writeLocatingLog($logFile, $response . "\r\n");
                 else :
                   $longitude = $locatingStateArray[1];
                   $latitude  = $locatingStateArray[2];
                
                   // Generate a faked response to be parsed correctly
                   $response = "";
                   $response .= "<POINT>";
                   $response .= "  <LL_POINT>";
                   $response .= "    <LAT>" . $locatingStateArray[2] . "</LAT>";
                   $response .= "    <LONG>" . $locatingStateArray[1] . "</LONG>";
                   $response .= "  </LL_POINT>";
                   $response .= "</POINT>";
                   $response .= "<RAD>XXXX</RAD>";
                 endif;

                 if ($response == "") :
                    $msg = "Es wurde keine Antwort geliefert!";
                 else :
                    if (FALSE && !(strpos($response, "<POSERR>") === FALSE)) :
                       $msg = "Die Nummer konnte nicht geortet werden!";
                    else :
                       if ((strpos($response, "<POINT>") === FALSE)) :
                          $msg = "Die Lokalisierung war nicht möglich!";
                       else :
                          if ($locatingStateArray[0] == "1") :
                             // Get latitude from connection request
                             $beginPos = strpos($response, "<LAT>") + 5;
                             $endPos = strpos($response, "</LAT>");
                             $latitudeRaw = substr($response, $beginPos, $endPos - $beginPos);
                             if ($echoEnabled) : echo "CoordPair: " . $coordPair . "<br>"; endif;
                             
                             // Get longitude from connection request
                             $beginPos = strpos($response, "<LONG>") + 6;
                             $endPos = strpos($response, "</LONG>");
                             $longitudeRaw = substr($response, $beginPos, $endPos - $beginPos);
                             if ($echoEnabled) : echo "CoordPair: " . $coordPair . "<br>"; endif;
                             
                             // Get radius from connection request
                             $beginPos = strpos($response, "<RAD>") + 5;
                             $endPos = strpos($response, "</RAD>");
                             $radius = substr($response, $beginPos, $endPos - $beginPos);
                             if ($echoEnabled) : echo "CoordPair: " . $coordPair . "<br>"; endif;
                             
                             $latitudeRawArray = array();
                             $tmpPos = strpos($latitudeRaw, ".");
                             if (!($tmpPos === FALSE)) :
                                $latitudeRawArray[0] = substr($latitudeRaw, 0, $tmpPos);
                                $latitudeRawArray[1] = substr($latitudeRaw, $tmpPos);
                             else :
                                $latitudeRawArray[0] = $latitudeRaw;
                                $latitudeRawArray[1] = "0";
                             endif;
                             $longitudeRawArray = array();
                             $tmpPos = strpos($longitudeRaw, ".");
                             if (!($tmpPos === FALSE)) :
                                $longitudeRawArray[0] = substr($longitudeRaw, 0, $tmpPos);
                                $longitudeRawArray[1] = substr($longitudeRaw, $tmpPos);
                             else :
                                $longitudeRawArray[0] = $longitudeRaw;
                                $longitudeRawArray[1] = "0";
                             endif;
                             
                             $latitudeRawArray[0] = pad($latitudeRawArray[0], 6, "0");    // if less than 6 chars
                             $longitudeRawArray[0] = pad($longitudeRawArray[0], 6, "0");  // if less than 6 chars
                             
                             if ($latitudeRawArray[1] == "") : $latitudeRawArray[1] = "0"; endif;
                             if ($longitudeRawArray[1] == "") : $longitudeRawArray[1] = "0"; endif;
                             
                             $x_coord_array[0] = substr($latitudeRawArray[0], 0, 2);
                             $x_coord_array[1] = substr($latitudeRawArray[0], 2, 2);
                             $x_coord_array[2] = substr($latitudeRawArray[0], 4);
                             
                             $y_coord_array[0] = substr($longitudeRawArray[0], 0, 2);
                             $y_coord_array[1] = substr($longitudeRawArray[0], 2, 2);
                             $y_coord_array[2] = substr($longitudeRawArray[0], 4);
                                 
                             // Compute longitude and latitude (transformation)
                             $longitude = $y_coord_array[0] + $y_coord_array[1] / 60 + ($y_coord_array[2] + $longitudeRawArray[1]) / 3600;
                             $latitude  = $x_coord_array[0] + $x_coord_array[1] / 60 + ($x_coord_array[2] + $latitudeRawArray[1]) / 3600;
                             writeLocatingLog($logFile, "-->" . $latitude . " " . $longitude . "<-- \r\n");
                          endif;
              
                          // Get zipcode from coordinates
                          $constLocatingMode = getParameterValue("0", "LOCATING_MODE", $hq_id);
                          if ($constLocatingMode == "0") :
                             $zipcode = findZipcodeArea($longitude, $latitude);
                             if (trim($zipcode) == "") :
                                $constLocatingMode = "1";
                             endif;
                          endif;
                          if ($constLocatingMode == "1") :
                             // Get nearest coordinates
                             $sqlquery = "SELECT srvp.srvp_id, srvp.srvp_plz, srvp.srvp_latitude, srvp.srvp_longitude, "
                                         .      "SQRT(POW(ABS(srvp.srvp_latitude - $latitude),2) + POW(ABS(srvp.srvp_longitude - $longitude),2)) AS nb"
                                         . " FROM serviceplz AS srvp"
                                         . " ORDER BY nb"
                                         . " LIMIT 0,1";
                             $result = $db->query($sqlquery);
                             if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
                             // all defined db-fields an titles shall become content of the following arrays
                             while ($row = $result->fetch_assoc()):   
                                $f_srvp_plz		= $row["srvp_plz"];         // Zipcode to be displayed
                             endwhile;
                             $result->free();
                             $zipcode = $f_srvp_plz;
                          endif;
                          $msg = "<b>REALE Standort-PLZ des Kuriers: " . $zipcode . "</b>" . "   (" . $longitude . " / " . $latitude . ")";

                          // Update zipcode of the courier
                          $updateRankingTime = TRUE;
                       
                          // Get current zipcode of the courier out of the table "courier" (cr_locationzipcode) to compare with locating zipcode
                          $crLocationZipcode = getFieldValueFromId("courier","cr_id",$cr_id,"cr_locationzipcode");
                       
                          $msg .= "&nbsp;&nbsp;&nbsp;<b>(Freimeldung des Kuriers: " . $crLocationZipcode . ")</b>&nbsp;";
                       
                          if ($zipcode != "" && $crLocationZipcode != "" && is_numeric($crLocationZipcode)) :
                             // Check current zipcode with locating zipcode
                             if ($zipcode == $crLocationZipcode) :
                                $updateRankingTime = FALSE;
                             else :
                                // Check locating zipcode is in neighbourhood
                                // If true then ok => do not update ranking time
                                // Get the general mediation mode for the headquarter
                                $mediationMode = getParameterValue("0", "MODE_INTERMEDIATION", $hq_id);
                                if ($mediationMode == "") :
                                   $mediationMode = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_invmode");
                                endif;

                                // Get all neighbours for the current zipcode(area)
                                if ($mediationMode == "1") :
                                   $zicodeArray = getCourierByRanking($crLocationZipcode, "0000010000", "", "");
                                   $zicodeArray = $zicodeArray[5];
                                else :
                                   $areaIdArray = getCourierByRanking($crLocationZipcode, "0000010000", "", "");
                                   $areaIdArray = $areaIdArray[5];
                 
                                   // Add ID of the main mediation area
                                   $srvpIdZipcode = getFieldValueFromId("serviceplz","srvp_plz",$crLocationZipcode,"srvp_id");
                                   // $srvpaIdMain = getFieldValueFromId("serviceplzareamapping","srvp_id",$srvpIdZipcode,"srvpa_id");
                                   $srvpaIdMain = $db->getOne("SELECT srvpam.srvpa_id FROM serviceplzarea AS srvpa, serviceplzareamapping AS srvpam" .
                                                              "  WHERE srvpam.srvp_id = '" . $srvpIdZipcode . "' AND srvpa.srvpa_id = srvpam.srvpa_id AND srvpa.hq_id = '" . $hq_id . "'");
                 
                                   if ($areaIdArray == "") : $areaIdArray = array(); endif;
                                   array_push($areaIdArray, $srvpaIdMain);
                                   $areaIdArrayLen = count($areaIdArray);
                                   $zicodeArray = array();
                                   for ($k = 0; $k < $areaIdArrayLen; $k++) :
                                      $sqlquery = "SELECT srvp.srvp_plz"
                                                . " FROM serviceplzareamapping AS srvpam, serviceplz AS srvp"
                                                . " WHERE srvpam.srvp_id = srvp.srvp_id AND srvpam.srvpa_id = '" . $areaIdArray[$k] . "'";
                                       
                                      $result = $db->query($sqlquery);
                                      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
                                                               
                                      while ($row = $result->fetch_assoc()):
                                         $zicodeArray[] = $row[srvp_plz];                                                   
                                      endwhile;
                                      $result->free();
                                   endfor;
                                endif;

                                $zicodeArrayLen = count($zicodeArray);
                                for ($k = 0; $k < $zicodeArrayLen; $k++) :
                                    if ($zipcode == $zicodeArray[$k]) :
                                       $updateRankingTime = FALSE;
                                    endif;
                                endfor;
                             endif;

                             $currentTime = getDateTime("0");
                             if ($updateRankingTime) :               
                                updateStmt("courier", "cr_id", $cr_id, array("cr_locationzipcode", $zipcode, "cr_availabletime", $currentTime));
                                $msg .= "Die Rankingposition ging verloren!";
                             else :
                                $msg .= "Die Rankingposition bleibt erhalten!";
                             endif;
                          else :
                             $currentTime = getDateTime("0");
                          endif;

                          // Update current position to courier with timestamp
                          if ($longitude != "" && $latitude != "" && 
                              substr($longitude , 0, 1) != "0" && substr($latitude , 0, 1) != "0" &&
                              is_numeric($longitude) && is_numeric($latitude)) :

                              updateStmt("courier", "cr_id", $cr_id, array("cr_gps_long", $longitude, "cr_gps_lat", $latitude, "cr_gps_time", $currentTime));
                          endif;
                 
                 
                          // ***********
                          // * LOGGING *
                          // ***********
                          
                          // Get usr_id of the current employee (session)
                          $currentSessionUsrId = getFieldValueFromId("employee", "emp_id", $emp_id, "usr_id");
                       
                          // Loose Ranking yes/no
                          $looseRanking = "NO";
                          if ($updateRankingTime) : $looseRanking = "YES"; endif;
                       
                          // Write logdata into log database
                          writeToLogDB("27",$hq_id,"0",$currentSessionUsrId,$cr_id,$tmpArray[$j],"","LONG=".$longitude."|LAT=".$latitude."|ZIP_REAL=".$zipcode."|ZIP_FREE=".$crLocationZipcode."|NO=".$msisdn."|LRANK=".$looseRanking."|LMODE=".$constLocatingMode);
                 
                 
                          // ********************
                          // * Close connection *
                          // ********************
                          
                          $requestID++;
                          $requestConnectionRelease = "<MESSAGE_TYPE=3><REQUEST_ID=" . $requestID . "><SESSION_HANDLE=" . $sessionHandle . ">";
                          
                          $laenge = strlen($requestConnectionRelease);
                          $requestheader = $requestheaderOrg;
                          $requestheader = str_replace ("LENGTH", $laenge, $requestheader);
                          if ($echoEnabled) : echo $requestheader.$requestConnectionRelease . "<br><br><br>"; endif;

                       endif;
                    endif;
                 endif;
                 $triggerOut .= "<td>" . $msg . "&nbsp;&nbsp;&nbsp;</td>\n";
              endif;
          endfor;
          $triggerOut .= "</tr>\n";
      endfor;
      $triggerOut .= "</table>\n";
      $triggerOut .= "</body>\n";
      $triggerOut .= "</html>\n";
   endif;
   
   
   // Send via email
   if ($sendPerMail) :

      $mailSenderAddress = "support@assecutor.de";
      $mailReceiverAddressArray = array("frankfurt@stadtbote.de","harald.krieger@stadtbote.de");
      $mailSubject = "Automatische Ortung";
      $mailCcAddress = "";
      $mailBccAddress = "support@assecutor.de";
      
      $currentTime = getDateTime("0");
      $mailtext = "AUTOMATISCHE ORTUNG <br> - PLZ: " . $locationZipcode . "<br>- ZEIT: " . $currentTime . "<br><br>";
      if (!$autoMode) :
         $mailtext .= "Ausgeführt von: " . $usrFirstname . " " . $usrName;
      endif;
      $mailtext .= $triggerOut;
   
      $mailObj = new htmlMimeMail();
   
      // Set From address
      $mailObj->setFrom($mailSenderAddress);
      
      // Set Cc address
      if ($mailCcAddress != "") :
         $mailObj->setCc($mailCcAddress);
      endif;
      
      // Set Bcc address
      if ($mailBccAddress != "") :
         $mailObj->setBcc($mailBccAddress);
      endif;
   
      // Subject of the mail
      $mailObj->setSubject($mailSubject);
   
      // Mail text
      $mailObj->setHtml($mailtext, null, "./");
   
      if ($f_secretFileName != "") :
         if (file_exists("../temp/download/" . $f_secretFileName)) :
            $attachment = $mailObj->getFile("../temp/download/" . $f_secretFileName);
            $mailObj->addAttachment($attachment, $f_secretFileName, $f_mimetype . $f_charset);
         endif;
      endif;

      $mailResult = $mailObj->send($mailReceiverAddressArray, 'smtp');
            
      $out = "Der Sendevorgang wurde abgeschlossen! Bitte prüfen Sie Ihren Email-Eingangsordner!";
   endif;
else :
   $out = "Leider haben Sie zur Ausführung keine Berechtigung!";
endif;
?>

<?php if (!$autoMode) : ?>

<html>

<head>

</head>
	
	
<body>

<center>
	
<br><br><br>

<b><?php echo $triggerOut ?></b>

</center>

</body>	
	
</html>

<?php endif; ?>