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


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



// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual",
                  "f_ad_id", "f_street", "f_zipcode", "f_city", "f_country",
                  "f_jb_id", "f_tr_sort", "f_tr_hsno", "elemNo",
                  "orderClauseDefault", "statusMessage", "deactivateMenu", "checkCorrectAdressOk"));

// Select user-type for mode of security check 
$userType = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");
$userTypeName = getUserTypeName($userType);

// Check authentication verifying emmployee an his/her costcenter- and customer-association
if ( !( ($userType == "1") || authCheck($hq_id,$usr_id,$emp_id,$cscIdRoot,$customerId,$cscIdActual) ) ) :
   die ("$PHP_SELF: Access denied!");
endif;

getLanguage(__FILE__);

$deactivateMenuStatic = "1";
$pageTitel = getLngt("ADRESSENLISTE");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

$closeThisWindow = "0";
$numOfRows = 0;
$f_street = trim($f_street);
$f_zipcode = trim($f_zipcode);
$f_city = trim($f_city);
$f_country = trim($f_country);
if ($f_country == "") : $f_country = "DE"; endif;
$f_tr_hsno = trim($f_tr_hsno);

$searchValues = $f_street . $f_zipcode . $f_city;          // if called e.g. by the first time with empty search-fields
if ($checkCorrectAdressOk == "") : $checkCorrectAdressOk = "0"; endif;    // Default "Not checked"

// if any search-field has content then take default-city of the headquarter
$hqAddress = getAddress($hq_id, "hq");
if ($searchValues == "") :   
   $f_city = trim($hqAddress["city"]);
   // $searchValues = $f_street . $f_zipcode . $f_city;    // define again if no address is associated to headquarter
endif;

// Initialize output
$out = "";


// Check for address being correct (Map & Guide or so on)
if ($f_act == "checkCorrectAdress") :
   if ($f_street == "" || $f_zipcode == "" || $f_city == "" || $f_tr_hsno == "") :
      $statusMessage = getLngt("Bitte mindestens die Felder Straße, Hausnummer, PLZ und Ort ausfüllen !");
   else :
      $tmpBool = XScheckAddress($f_country, $f_zipcode, $f_city, $f_street, $f_tr_hsno);      
      if ($tmpBool) :
         $checkCorrectAdressOk = "1";
         $statusMessage = getLngt("Die Adresse ist OK!");
      else :
         $checkCorrectAdressOk = "0";
         $statusMessage = getLngt("Die Adresse scheint noch nicht korrekt zu sein!");
      endif;
   endif;
   $f_act = "search";  // Init
endif;

// Update the current address in "f_ad_id" with the specified address data
if ($f_act == "updateCurrentAddress") :
   if ($checkCorrectAdressOk != "" && $checkCorrectAdressOk != "0") :
      if ($f_ad_id != "" && is_numeric($f_ad_id) && $f_street != "" && $f_zipcode != "" && $f_city != "" &&
          $f_tr_hsno != "" && $f_jb_id != "" && is_numeric($f_jb_id) && $f_tr_sort != "" && is_numeric($f_tr_sort)) :
         // Update address
         updateStmt("address", "ad_id", $f_ad_id, array("ad_street", $f_street, "ad_zipcode", $f_zipcode, "ad_city", $f_city));
         // Update housenumber
         updateStmt("tour", "jb_id", $f_jb_id, array("tr_hsno", $f_tr_hsno, "tr_ware_from_to", "1"), "tr_sort = '" . $f_tr_sort . "'");
         // Close window
         $closeThisWindow = "1";
      else :
         $statusMessage = getLngt("ACHTUNG: Die Adresse wurde NICHT aktualisiert!");
      endif;
   endif;
endif;


// Generate search-resultset
if ($f_act == "search" && $searchValues != "") :
        
   if (strlen($f_street) > 4 || (strlen($f_street) > 1 && (strlen($f_zipcode) > 1 || strlen($f_city) > 1))) :

      // *********************************************************************
      // * Selection of the costcenters of the current customer for the list *
      // *********************************************************************
      
      // This part only for headquarter employees
      if (false && $userTypeName == "hq") :
      
         $whereClause = "";
         if ($f_street != "") : $whereClause .= "ad_street LIKE '" . $f_street . "%'"; endif;      
         if ($whereClause != "" && $f_zipcode != "") : $whereClause .= " AND "; endif;
         if ($f_zipcode != "") : $whereClause .= "ad_zipcode LIKE '" . $f_zipcode . "%'"; endif;                  
         if ($whereClause != "" && $f_city != "") : $whereClause .= " AND "; endif;      
         if ($f_city != "") : $whereClause .= "ad_city LIKE '" . $f_city . "%'"; endif;      
         if ($whereClause != "" && $f_country != "") : $whereClause .= " AND "; endif;      
         if ($f_country != "") : $whereClause .= "ad_country LIKE '" . $f_country . "%'"; endif;
         
         // if ($whereClause != "") : $whereClause = " AND " . $whereClause; endif;
    
         if ($orderClauseDefault == "") : 
            $orderClause = "ad_street, ad_zipcode";
         else :
            $orderClause = "ad_" . $orderClauseDefault;
         endif;
    
    
         // *****************************************************************************************************
         // * TABLE "serviceplzareaaddress" Selection of the costcenter based on a search by companyname-prefix *
         // *****************************************************************************************************
         $sqlquery = "SELECT CONCAT('BEREICH: ',srvpa.srvpa_name,' (',srvpa.srvpa_longname,')') AS ad_district,"
                      . "    ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country," 
                      . "    CONCAT(srvpaa.srvpaa_hsno_from,'-',srvpaa.srvpaa_hsno_to) AS srvpaa_hsno," 
                      . "    srvpaa_mode" 
                      . " FROM serviceplzareaaddress AS srvpaa, address AS ad, serviceplzarea AS srvpa"
                      . " WHERE ad.ad_id = srvpaa.ad_id            AND"
                      . "       srvpaa.srvpa_id = srvpa.srvpa_id"
                      .   ($whereClause != "" ? " AND " : "") . $whereClause
                      . " ORDER BY " . $orderClause;
    
         $result = $db->query($sqlquery);
         if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
    
         $lineToggler = 0;
         while ($row = $result->fetch_assoc()):            
               $numOfRows++;
    
   	           if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;                
               $cellColor = getListColor($numOfRows, $lineToggler);
    
               $v_ad_district  = $row["ad_district"];
               $v_ad_street    = $row["ad_street"];
               $v_ad_zipcode   = $row["ad_zipcode"];
               $v_ad_city      = $row["ad_city"];
               $v_ad_country   = $row["ad_country"];
               
               $v_srvpaa_hsno  = $row["srvpaa_hsno"];            
               $v_srvpaa_mode  = "";
               if ($row["srvpaa_mode"] == "1") : $v_srvpaa_mode = ", " . getLngt("nur ungerade"); endif;
               if ($row["srvpaa_mode"] == "2") : $v_srvpaa_mode = ", " . getLngt("nur gerade"); endif;
    
               $out .= "<tr class=\"f10bp1\">";
               $out .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . "<a href=\"javascript:selectAddressData('".my_str_check_js($v_ad_district)."','".my_str_check_js($v_ad_street)."','".my_str_check_js($v_ad_zipcode)."','".my_str_check_js($v_ad_city)."','".my_str_check_js($v_ad_country)."');\">"
                                        . $v_ad_street . " (" . $v_srvpaa_hsno . $v_srvpaa_mode . ")</a>" . "&nbsp;</td>";            
               $out .= "<td bgcolor=\"" . $cellColor ."\"> $v_ad_zipcode &nbsp;</td> ";
               $out .= "<td bgcolor=\"" . $cellColor ."\"> $v_ad_city &nbsp;</td> ";            
               $out .= "<td bgcolor=\"" . $cellColor ."\"> $v_ad_country &nbsp;</td> ";
               $out .= "<td class=\"f8np1_blue\"  bgcolor=\"" . $cellColor ."\"> $v_ad_district &nbsp;</td> ";
    
               $out .= "</tr>\n";
         endwhile;
         $result->free();
    
         // Empty line if $out is not empty
         if ($out != "") :
            $out .= "<tr><td colspan=\"5\">&nbsp;</td></tr>";
         endif;
      endif;


      // **************************************************************************************
      // * TABLE "street" Selection of the costcenter based on a search by companyname-prefix *
      // **************************************************************************************

      $f_country = "";    // RESET because of the fact table "street" has no "DE" !!!

      $whereClause = "";
      if ($f_street != "") : $whereClause .= "st_street LIKE '" . $f_street . "%'"; endif;      
      if ($whereClause != "" && $f_zipcode != "") : $whereClause .= " AND "; endif;
      if ($f_zipcode != "") : $whereClause .= "st_zipcode LIKE '" . $f_zipcode . "%'"; endif;                  
      if ($whereClause != "" && $f_city != "") : $whereClause .= " AND "; endif;      
      if ($f_city != "") : $whereClause .= "st_city LIKE '" . $f_city . "%'"; endif;      
      if ($whereClause != "" && $f_country != "") : $whereClause .= " AND "; endif;      
      if ($f_country != "") : $whereClause .= "st_country LIKE '" . $f_country . "%'"; endif;
      
      // if ($whereClause != "") : $whereClause = " AND " . $whereClause; endif;

      if ($orderClauseDefault == "") : 
         $orderClause = "st_street, st_no_from, st_no_to, st_zipcode";
      else :
         $orderClause = "st_" . $orderClauseDefault;
      endif;      
      if ($orderClause == "st_street")
        $orderClause .= ", st_no_from, st_no_to";
      
      $sqlquery = "SELECT st_district, st_street, st_zipcode, st_city, st_country, st_no_from, st_no_to" 
                   . " FROM phoenix_special.street"
                   . " WHERE "    . $whereClause
                   . " ORDER BY " . $orderClause;

      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

      $numOfRows = 0;
      $lineToggler = 0;
      while ($row = $result->fetch_assoc()):            
            $numOfRows++;

            if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;                
            $cellColor = getListColor($numOfRows, $lineToggler);

            $v_ad_district  = $row["st_district"];
            $v_ad_street    = $row["st_street"];
            $v_ad_no        = $row["st_no_from"] . "-" . $row["st_no_to"];
            $v_ad_zipcode   = $row["st_zipcode"];
            $v_ad_city      = $row["st_city"];
            $v_ad_country   = $row["st_country"];

            $out .= "<tr class=\"f10bp1\">";
            // $out .= "<td class=\"f10bp1_red\" bgcolor=\"" . $cellColor ."\"> $v_csc_name </td> ";
            $out .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . "<a href=\"javascript:selectAddressData('".my_str_check_js($v_ad_district)."','".my_str_check_js($v_ad_street)."','".my_str_check_js($v_ad_zipcode)."','".my_str_check_js($v_ad_city)."','".my_str_check_js($v_ad_country)."');\">"
                               . $v_ad_street . "</a>" . " " . $v_ad_no . "&nbsp;</td>";            
            $out .= "<td bgcolor=\"" . $cellColor ."\"> $v_ad_zipcode &nbsp;</td> ";
            $out .= "<td bgcolor=\"" . $cellColor ."\"> $v_ad_city &nbsp;</td> ";            
            $out .= "<td bgcolor=\"" . $cellColor ."\"> $v_ad_country &nbsp;</td> ";
            $out .= "<td bgcolor=\"" . $cellColor ."\"> $v_ad_district &nbsp;</td> ";

            $out .= "</tr>\n";
      endwhile;
      $result->free();
   else :
      $statusMessage = getLngt("Eingabe entw. mind. 5 Zeichen bei Straße oder mind. 2 Zeichen bei Straße in Verbindung mit mind. 2 Zeichen bei Ort oder PLZ!");
   endif;
endif;   

function get_name() {
  global $db, $f_jb_id, $f_tr_sort;
  
  if ($f_jb_id == "" || $f_tr_sort == "")
    return;    
    
  $sqlquery = "SELECT tr_comp, tr_person FROM tour WHERE jb_id = $f_jb_id AND tr_sort = $f_tr_sort";
  $result = $db->query($sqlquery);
  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
  if ($row = $result->fetch_assoc()):
    if (trim($row["tr_person"]) != ""):
      return $row["tr_comp"] . ", " . $row["tr_person"];
    endif;
    return $row["tr_comp"];
  endif;
}

function get_google_coords() {
  global $f_tr_sort, $f_street, $f_zipcode, $f_city, $f_country, $f_tr_hsno;

  $error_codes = array(
    "200" => "G_GEO_SUCCESS",	            //Keine Fehler aufgetreten; die Adresse wurde erfolgreich analysiert. Der Geocode wurde zurückgegeben.
    "500" => "G_GEO_SERVER_ERROR",        //Eine Geocodierungs- oder Routenanforderung konnte nicht erfolgreich verarbeitet werden, da der genaue Grund für den Fehler nicht bekannt ist.
    "601" => "G_GEO_MISSING_QUERY",	      //Für den HTTP Parameter q wurde eine leere Adresse angegeben.
    "602" => "G_GEO_UNKNOWN_ADDRESS",	    //Zu der angegebenen Adresse wurde keine geografische Entsprechung gefunden. Möglicherweise ist die Adresse relativ neu oder nicht richtig.
    "603" => "G_GEO_UNAVAILABLE_ADDRESS",	//Der Geocode für die angegebene Adresse oder die Route für die angegebene Richtungsanfrage kann aus rechtlichen oder Vertragsgründen nicht zurückgegeben werden.
    "610" => "G_GEO_BAD_KEY",	            //Der angegebene Schlüssel ist entweder ungültig oder passt nicht zur Domain, für die er angegeben wurde.
    "620" => "G_GEO_TOO_MANY_QUERIES"	    //Der angegebene Schlüssel hat innerhalb des Zeitraums von 24 Stunden das Limit für Anforderungen überschritten oder zu viele Anforderungen in einem zu kurzen Zeitraum übermittelt. Wenn Sie zahlreiche Anforderungen gleichzeitig oder kurz hintereinander übermitteln, verwenden Sie in Ihrem Code einen Timer oder eine Pause, damit die Anforderungen nicht zu schnell übermittelt werden. 
  );

  $accuracy = array(
    '0' => 'Genauigkeit unbekannt',
    '1' => 'Land',
    '2' => 'Region (Bundesland/Bundesstaat, Provinz, Präfektur usw. )',
    '3' => 'Kreis (Bezirk, Gemeinde usw. )',
    '4' => 'Ortschaft (Stadt, Dorf)',
    '5' => 'Postleitzahl (PLZ)',
    '6' => 'Straße',
    '7' => 'Kreuzung',
    '8' => 'Adresse',
    '9' => 'Grundstück (Name des Gebäude/Grundstücks, Einkaufszentrum usw.)'
  );


//echo "http://maps.google.com/maps/geo?q=" . rawurlencode($f_street . " " . $f_tr_hsno) . "," . rawurlencode($f_zipcode . " " . $f_city) . "&output=csv";
  $lines = file ("http://maps.google.com/maps/geo?q=" . rawurlencode($f_street . " " . $f_tr_hsno) . "," . rawurlencode($f_zipcode . " " . $f_city) . "&output=csv");
  $result = explode(",", $lines[0]);
  if ($result[0] == "200"):
    return $result[2] . ", " . $result[3] . " (Genauigkeit: " . $accuracy[$result[1]] . ")";
  else:
    return $error_codes[$result[0]];
  endif;
}

?>

<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"); ?>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

var v_district = '';
var v_street = '';
var v_zipcode = '';
var v_city = '';
var v_country = '';


function selectAddressData(district,street,zipcode,city,country) {
  document.forms[0].f_street.value = street;
  document.forms[0].f_zipcode.value = zipcode;
  document.forms[0].f_city.value = city;
  document.forms[0].f_country.value = country;
  document.forms[0].f_district.value = district;
  
  document.forms[0].checkCorrectAdressOk.value = '0';  // Reset value !!!
};

function clearFields() {
  document.forms[0].f_street.value = '';
  document.forms[0].f_zipcode.value = '';
  document.forms[0].f_city.value = '<?php echo $hqAddress["city"] ?>';
  document.forms[0].f_country.value = '';
  document.forms[0].f_district.value = '';
  
  document.forms[0].checkCorrectAdressOk.value = '0';  // Reset value !!!
};

function finishPageCheckAddress(f_act) {
	document.forms[0].f_act.value = f_act;
	document.forms[0].submit();
};

function finishPage() {
  var checkCorrectAdressOk = '<?php echo $checkCorrectAdressOk ?>';
  var elemNo = '<?php echo $elemNo ?>';
  // var f_ad_id = '<?php echo $f_ad_id ?>';
  var tmpField;

  if (checkCorrectAdressOk == '0') {
     alert('<?php echo getLngt("Bitte prüfen Sie die eingetragenen Adressdaten über die nebenstehende Schaltfläche") ?>');
  } else {
  	 tmpField = eval('opener.document.forms[0].jobDataTarget_' + elemNo + '_address');
  	 tmpField.value = document.forms[0].f_zipcode.value + ' ' + document.forms[0].f_city.value + ', ' + document.forms[0].f_street.value + ' ' + document.forms[0].f_tr_hsno.value;
     finishPageCheckAddress("updateCurrentAddress");
  }  
};

function checkForCloseWindow() {
  var closeThisWindow = '<?php echo $closeThisWindow ?>';
  if (closeThisWindow == '1') {
  	 self.close();
  }
};
-->
</script>
</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>checkForCloseWindow();displayStatusMessage();">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="maincontent" name="maincontent" id="maincontent">

<form action="ad_list2.php" method="post">
  <input type="hidden" name="f_act" value="">  
  <input type="hidden" name="customerId" value="<?php echo $customerId ?>">
  <input type="hidden" name="cscIdRoot" value="<?php echo $cscIdRoot ?>">
  <input type="hidden" name="cscIdActual" value="<?php echo $cscIdActual ?>">  
  <input type="hidden" name="orderClauseDefault" value="<?php echo $orderClauseDefault ?>">
  <input type="hidden" name="elemNo" value="<?php echo $elemNo ?>">
  <input type="hidden" name="f_ad_id" value="<?php echo $f_ad_id ?>">
  <input type="hidden" name="checkCorrectAdressOk" value="<?php echo $checkCorrectAdressOk ?>">
  <input type="hidden" name="f_jb_id" value="<?php echo $f_jb_id ?>">
  <input type="hidden" name="f_tr_sort" value="<?php echo $f_tr_sort ?>">

  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

  <?php echo htmlDivLineSpacer("20px"); ?>

  <div>
    <div class="f12bp1_blue"><?php echo getLngt("Adressen") ?></div>
  </div>
  <?php echo htmlDivLineSpacer("20px"); ?>
  
  <div>
    <a href="javascript:document.forms[0].f_act.value='search';document.forms[0].submit();"><?php echo getLngt("Suchen") ?></a>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="javascript:clearFields();"><?php echo getLngt("Felder zurücksetzen") ?></a>
  </div>
  <?php echo htmlDivLineSpacer("15px"); ?>

  <div>
    Name:<b> <?php echo get_name(); ?></b>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  
  <div>
    <table class="f8np1" border="0" cellpadding="0">
      <tr>
        <td><input type="text" name="f_street" value="<?php echo $f_street ?>" size="25"></td>
        <td><input type="text" name="f_zipcode" value="<?php echo $f_zipcode ?>" size="5"></td>
        <td><input type="text" name="f_city" value="<?php echo $f_city ?>" size="20"></td>                  
        <td><input type="text" name="f_country" value="<?php echo $f_country ?>" size="3"></td>
        <td><input type="text" name="f_district" value="<?php echo $f_district ?>" size="20"></td>
        <td><input type="text" name="f_tr_hsno" value="<?php echo $f_tr_hsno ?>" size="20"></td>
        <td><input type="button" name="f_button_check" value="<?php echo getLngt("Prüfen") ?>" size="30" onclick="finishPageCheckAddress('checkCorrectAdress')"></td>
        <?php if ($checkCorrectAdressOk != "0") : ?>
          <td><input type="button" name="f_button_take" value="<?php echo getLngt("Übernehmen") ?>" size="30" onclick="finishPage()"></td>
        <?php else :?>
          <td><input type="button" name="f_button_take" value="<?php echo getLngt("Übernehmen") ?>" size="30" disabled></td>
        <?php endif; ?>
      </tr>             
      <tr>
        <td><a href="javascript:document.forms[0].orderClauseDefault.value='street';document.forms[0].f_act.value='search';document.forms[0].submit();"><?php echo getLngt("Straße") ?></a></td>
        <td><a href="javascript:document.forms[0].orderClauseDefault.value='zipcode';document.forms[0].f_act.value='search';document.forms[0].submit();"><?php echo getLngt("PLZ") ?></a></td>
        <td><a href="javascript:document.forms[0].orderClauseDefault.value='city';document.forms[0].f_act.value='search';document.forms[0].submit();"><?php echo getLngt("Ort") ?></a></td>                  
        <td><a href="javascript:document.forms[0].orderClauseDefault.value='country';document.forms[0].f_act.value='search';document.forms[0].submit();"><?php echo getLngt("Land") ?></a></td>
        <td><a href="javascript:document.forms[0].orderClauseDefault.value='district';document.forms[0].f_act.value='search';document.forms[0].submit();"><?php echo getLngt("Ortsteil") ?></a></td>
        <td><?php echo getLngt("Hausnummer") ?></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>             
//      <?php echo get_google_coords(); ?>                   
      <?php echo $out ?>      
    </table>
  </div>
  <?php echo htmlDivLineSpacer("15px"); ?>

  <div>
    <?php echo getLngt("Anzahl Einträge:") ?> <?php echo $numOfRows ?><?php if ($numOfRows == "0" && $f_act == "search" && $statusMessage == "") : echo " " . getLngt("(Keine Einträge gefunden.)"); endif; ?>
  </div>

</form>
</div>
</body>

</html>