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


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


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual",
                  "f_srvpa_name", "f_ad_street", "f_srvpaa_hsno_from", "f_srvpaa_hsno_to", 
                  "f_ad_zipcode", "f_ad_city", "f_ad_country", "f_srvpaa_mode", "f_del_assoc", 
                  "orderClause", "statusMessage", "tourno", "deactivateMenu"));

$pageTitel = "BEREICHSADRESSEN";
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");

// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
authCheckEmployeeRights($emp_id, "2", "1");

$numOfRows = 0;
mcTrim($f_ad_street); mcTrim($f_ad_zipcode); mcTrim($f_ad_city); mcTrim($f_ad_country);
mcTrim($f_srvpa_name); mcTrim($f_srvpaa_hsno_from); mcTrim($f_srvpaa_hsno_to);

if ($f_del_assoc == "") : $f_del_assoc = array(); endif;
$out = "";
$out_remarks = "";


// NEW association between area and address
if ($f_act == "newAreaAddress") :

   if (ZIPCODEAREA_PADLENGTH != "" && is_numeric(ZIPCODEAREA_PADLENGTH)) :
      $f_srvpa_name = trim($f_srvpa_name);
      if ($f_srvpa_name != "") :
         $f_srvpa_name = pad($f_srvpa_name,ZIPCODEAREA_PADLENGTH);
      endif;
   endif;
   // Get the id of the area
   // $f_srvpa_id = getFieldValueFromId("serviceplzarea","srvpa_name",$f_srvpa_name,"srvpa_id");
   $f_srvpa_id = getFieldValueFromClause("serviceplzarea","srvpa_id","srvpa_name = '" . $f_srvpa_name . "' AND hq_id = '" . $hq_id . "'");

   // Check existence zipcode 
   $f_srvp_id = getFieldValueFromId("serviceplz","srvp_plz",$f_ad_zipcode,"srvp_id");
   
   // Try to get name of the city if does not exist
   if ($f_ad_city == "") :
      $sqlStmt = "SELECT st_city FROM phoenix_special.street WHERE st_zipcode = '$f_ad_zipcode'";
      $f_ad_city = $db->getOne($sqlStmt);     
   endif;

   // Check ranges of hsno´s
   // ... To be done to be beautiful... !!!

   if ($f_srvpa_id != "" && $f_srvp_id != "" && $f_ad_street != "") :
   
      // Get ad_id of the new address
      insertStmt("address", array("ad_street", $f_ad_street, "ad_zipcode", $f_ad_zipcode, "ad_city", $f_ad_city, "ad_country", $f_ad_country));
      $ad_id_new = getLastInsertID();   
   
      // Insert relation
      insertStmt("serviceplzareaaddress", array("hq_id", $hq_id, "srvpa_id", $f_srvpa_id, "ad_id", $ad_id_new, "srvpaa_hsno_from", $f_srvpaa_hsno_from, "srvpaa_hsno_to", $f_srvpaa_hsno_to, "srvpaa_mode", $f_srvpaa_mode));
      
      $f_act = "search";
   else :      
      if ($f_srvpa_id == "") :
         $statusMessage = "Der angegebene Bereich existiert nicht!";
      elseif ($f_srvp_id == "") :
         $statusMessage = "Die angegebene PLZ ist nicht gültig!";
      elseif ($f_ad_street == "") :
         $statusMessage = "Es ist keine Straße angegeben!";
      else :
         $statusMessage = "Der Datensatz konnte nicht eingestellt werden! Bitte alle Felder vollständig ausfüllen!";
      endif;
   endif;
endif;

// REMOVE association between area and address
if ($f_act == "removeAreaAddress") :

   TA("B");       

   // Entries to be deleted?
   $fieldsLength = count($f_del_assoc);

   if ($fieldsLength > 0 && $f_del_assoc[0] != "") :
   
      // Remove all associations according to the zipcode nested in array $f_del_zipcode_id
      for ($i = 0; $i < $fieldsLength; $i++) :
          deleteStmt("serviceplzareaaddress","srvpaa_id = '" . $f_del_assoc[$i] . "' AND hq_id = '" . $hq_id . "'");
      endfor;
      
      $f_act = "search";
   else :
      $statusMessage = "Bitte markieren Sie zu löschende Beziehungen durch anklicken der jeweiligen Checkbox hinter dem Eintrag!";
   endif;

   TA("C");
   TA("E");
endif;


// Generate search-resultset
// if ($f_act == "search" && $searchValues != "") :
if ($f_act == "search") :
        
   if (strlen($f_srvpa_name) > 0 || strlen($f_ad_street) > 0 || strlen($f_ad_zipcode) > 0 || strlen($f_ad_city) > 0 ||
       strlen($f_srvpaa_hsno_from) > 0 || strlen($f_srvpaa_hsno_to) > 0) :

      if (ZIPCODEAREA_PADLENGTH != "" && is_numeric(ZIPCODEAREA_PADLENGTH)) :
         $f_srvpa_name = trim($f_srvpa_name);
         if ($f_srvpa_name != "") :
            $f_srvpa_name = pad($f_srvpa_name,ZIPCODEAREA_PADLENGTH);
         endif;
      endif;
      // Get the id of the area
      // $f_srvpa_id = getFieldValueFromId("serviceplzarea","srvpa_name",$f_srvpa_name,"srvpa_id");
      $f_srvpa_id = getFieldValueFromClause("serviceplzarea","srvpa_id","srvpa_name = '" . $f_srvpa_name . "' AND hq_id = '" . $hq_id . "'");


      // *************************************************
      // * Selection of the mappings "address" => "area" *
      // *************************************************
      $whereClause = "";
      if ($f_ad_street != "") : $whereClause .= "ad.ad_street LIKE '" . $f_ad_street . "%'"; endif;      
      if ($whereClause != "" && $f_ad_zipcode != "") : $whereClause .= " AND "; endif;
      if ($f_ad_zipcode != "") : $whereClause .= "ad.ad_zipcode LIKE '" . $f_ad_zipcode . "%'"; endif;
      if ($whereClause != "" && $f_ad_city != "") : $whereClause .= " AND "; endif;      
      if ($f_ad_city != "") : $whereClause .= "ad.ad_city LIKE '" . $f_ad_city . "%'"; endif;      
      if ($whereClause != "" && $f_ad_country != "") : $whereClause .= " AND "; endif;      
      if ($f_ad_country != "") : $whereClause .= "ad.ad_country LIKE '" . $f_ad_country . "%'"; endif;

      // Only prefix !
      if ($whereClause != "" && $f_srvpa_id != "") : $whereClause .= " AND "; endif;
      if ($f_srvpa_id != "") : $whereClause .= "srvpa.srvpa_id = '" . $f_srvpa_id . "'"; endif;
      if ($whereClause != "" && $f_srvpaa_hsno_from != "") : $whereClause .= " AND "; endif;      
      if ($f_srvpaa_hsno_from != "") : $whereClause .= "srvpaa.srvpaa_hsno_from = '" . $f_srvpaa_hsno_from . "'"; endif;
      if ($whereClause != "" && $f_srvpaa_hsno_to != "") : $whereClause .= " AND "; endif;
      if ($f_srvpaa_hsno_to != "") : $whereClause .= "srvpaa.srvpaa_hsno_to = '" . $f_srvpaa_hsno_to . "'"; endif;
      
      if ($whereClause != "") : $whereClause .= " AND "; endif;

      if ($orderClause == "") : $orderClause = "ad.ad_street, srvpaa.srvpaa_hsno_to, ad.ad_zipcode"; endif;
      
      
      // **************************************
      // * Selection of the invoice addresses *
      // **************************************
      $sqlquery = "SELECT ad.ad_id, ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country," 
                   . "    srvpaa.srvpaa_id, srvpaa.srvpaa_hsno_from, srvpaa.srvpaa_hsno_to, srvpaa.srvpaa_mode,"
                   . "    srvpa.srvpa_id, srvpa.srvpa_name, par.par_value"
                   . " FROM address AS ad, serviceplzarea AS srvpa, serviceplzareaaddress AS srvpaa"
                   . "    LEFT JOIN parameter AS par ON CONCAT('MASK_AREA_ID_FROM_ADDRESS_', srvpaa.srvpaa_id) = par.par_key"
                   . " WHERE "    . $whereClause
                   . "    srvpaa.hq_id = '" . $hq_id . "'  AND"
                   . "    ad.ad_id = srvpaa.ad_id          AND"
                   . "    srvpa.srvpa_id = srvpaa.srvpa_id AND"
                   . "    srvpa.hq_id = '" . $hq_id . "'"
                   . " ORDER BY " . $orderClause;
      // echo $sqlquery;
      $result = $db->dbQ($sqlquery);

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

            $out .= "<tr class=\"f10bp1\">";
            $out .= "<td> ". $row["srvpa_name"] . ($row["par_value"] != "" ? "*" : "") . " &nbsp;</td> ";
            $out .= "<td> ". $row["ad_street"] . " &nbsp;</td>";            
            $out .= "<td> ". $row["srvpaa_hsno_from"] . " &nbsp;</td> ";
            $out .= "<td> ". $row["srvpaa_hsno_to"] . " &nbsp;</td> ";
            if ($row["srvpaa_mode"] == "1") :
               $out .= "<td> Nur ungerade &nbsp;</td> ";
            elseif ($row["srvpaa_mode"] == "2") :
               $out .= "<td> Nur gerade &nbsp;</td> ";
            else :
               $out .= "<td> &nbsp;</td> ";
            endif;
            $out .= "<td> ". $row["ad_zipcode"] . " &nbsp;</td> ";
            $out .= "<td> ". $row["ad_city"] . " &nbsp;</td> ";
/*            
            $out .= "<td align=\"center\"><a href=\"../jobs/job_edit.php?csc_id_start=" . ec($row["csc_id"]) . "\" target=\"_blank\">"
                                   . "<img src=\"../images/arrow_right.jpg\" border=\"0\" height=\"10\" width=\"25\">" 
                                   . "</a>" . "</td>";                                                            
*/
            $out .= "<td align=\"center\"><input type=\"checkbox\" name=\"f_del_assoc[]\" value=\"" . $row["srvpaa_id"] . "\"></td>";
            $out .= "</tr>\n";
            if ($row["par_value"] != ""):
              $rowPar_value = "";
              $rowPar_valueArr = explode(";", $row["par_value"]);
              foreach($rowPar_valueArr as $rowPar_valuePair) {
                $rowPar_valuePairArr = explode(",", $rowPar_valuePair);
                $rowPar_value .= $rowPar_valuePairArr[0] . " -&gt; " . $db->getOne("SELECT srvpa_name FROM serviceplzarea WHERE srvpa_id = " . $rowPar_valuePairArr[1]) . ", ";
              }
              $out_remarks .= $row["srvpa_name"] . "&nbsp;" . $row["ad_street"] . ": " . substr($rowPar_value, 0, strlen($rowPar_value) - 2) . "<br>\n";
            endif;
      endwhile;

      if ($out_remarks != ""):
        $out_remarks = "<tr><td><b>*) Folgende Hausnummern sind in der Preisberechnung abweichenden Bereichen zugeordnet: <br>\n" . $out_remarks . "</b></td><tr>";
      endif;
                        
      $result->free();     
   else :
      $statusMessage = "Eingabe mind. 1 Zeichen in einem Feld!";
   endif;
endif;   
?>

<html>

<head>
<title><?php echo $pageTitel ?></title>

<style type="text/css">
  <?php include_once ("../css/phoenix.css.php"); ?>
  <?php include_once ("../css/navigation.css.php"); ?>
  <?php include_once ("../css/mc.css.php"); ?>

  table, th, td {
    border: 1px solid var(--primary-color);;
    border-collapse: collapse;
    padding: 8px;
  }
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

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

function finishPage(mode) {
  if (mode == 'removeAreaAddress') {
     if (confirm('Möchten Sie die markierten Einträge wirklich löschen?')) {
     	document.forms[0].f_act.value = mode;
        document.forms[0].submit();
     }
  }
  if (mode == 'newAreaAddress') {
     if (confirm('Möchten Sie die neue Beziehung wirklich einstellen?')) {
     	document.forms[0].f_act.value = mode;
        document.forms[0].submit();
     }
  }  
};

function clearFields() {
  document.forms[0].f_srvpa_name.value = '';
  document.forms[0].f_ad_street.value = '';
  document.forms[0].f_srvpaa_hsno_from.value = '';
  document.forms[0].f_srvpaa_hsno_to.value = '';
  document.forms[0].f_ad_zipcode.value = '';
  document.forms[0].f_ad_city.value = '';
};
-->
</script>
</head>

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

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

<div class="mc_page-header">
  <?php echo getLngt("Zuordnung Adressen zu Bereichen für die Preisberechnung") ?>
</div>

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

<form action="srvpaa_list.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="orderClause" value="<?php echo $orderClause ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

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

  <?php echo defineButtonType08(getLngt("Suchen"), "action_search", "javascript:document.forms[0].f_act.value='search';document.forms[0].submit();", "180", "left", "3"); ?>
  <?php echo defineButtonType08(getLngt("Felder zurücksetzen"), "action_clear", "javascript:clearFields();", "180", "left", "3"); ?>
  <?php echo defineButtonType08(getLngt("Neu"), "action_clear", "javascript:finishPage('newAreaAddress');", "180"); ?>
  <?php echo htmlDivLineSpacer("10px"); ?>

  <div>
<?php if (false) : ?>
    <table border="0">
      <tr>      
        <td>
          <table border="0">
            <tr>
              <td>
<?php endif; ?>
                <table class="f8np1" border="1" cellpadding="0">
                  <tr>
                    <td><input type="text" name="f_srvpa_name" value="<?php echo $f_srvpa_name ?>" size="5"></td>
                    <td><input type="text" name="f_ad_street" value="<?php echo $f_ad_street ?>" size="50"></td>
                    <td><input type="text" name="f_srvpaa_hsno_from" value="<?php echo $f_srvpaa_hsno_from ?>" size="7"></td>
                    <td><input type="text" name="f_srvpaa_hsno_to" value="<?php echo $f_srvpaa_hsno_to ?>" size="7"></td>
                    <td>
                        <input type="radio" name="f_srvpaa_mode" value="0" <?php if ($f_srvpaa_mode == "0" || $f_srvpaa_mode == "") : echo "checked"; endif;  ?>> Alle<br>
                        <input type="radio" name="f_srvpaa_mode" value="1" <?php if ($f_srvpaa_mode == "1") : echo "checked"; endif;  ?>> Ungerade<br>
                        <input type="radio" name="f_srvpaa_mode" value="2" <?php if ($f_srvpaa_mode == "2") : echo "checked"; endif;  ?>> Gerade
                    </td>                                                      
                    <td><input type="text" name="f_ad_zipcode" value="<?php echo $f_ad_zipcode ?>" size="5"></td>
                    <td><input type="text" name="f_ad_city" value="<?php echo $f_ad_city ?>" size="30"></td>
                    <td><?php echo defineButtonType10("Löschen", "action_remove", "finishPage('removeAreaAddress');", "80", "left"); ?></td>
                  </tr>
                  <tr>
                    <td><a href="javascript:document.forms[0].orderClause.value='srvpa.srvpa_name';document.forms[0].f_act.value='search';document.forms[0].submit();">Bereich</a></td>
                    <td><a href="javascript:document.forms[0].orderClause.value='ad_street, srvpaa.srvpaa_hsno_from';document.forms[0].f_act.value='search';document.forms[0].submit();">Straße</a></td>
                    <td><a href="javascript:document.forms[0].orderClause.value='srvpaa.srvpaa_hsno_from';document.forms[0].f_act.value='search';document.forms[0].submit();">Hausnr. von</a></td>
                    <td><a href="javascript:document.forms[0].orderClause.value='srvpaa.srvpaa_hsno_to';document.forms[0].f_act.value='search';document.forms[0].submit();">Hausnr. bis</a></td>
                    <td><a href="javascript:document.forms[0].orderClause.value='srvpaa.srvpaa_mode';document.forms[0].f_act.value='search';document.forms[0].submit();">Modus</a></td>
                    <td><a href="javascript:document.forms[0].orderClause.value='ad.ad_zipcode';document.forms[0].f_act.value='search';document.forms[0].submit();">PLZ</a></td>
                    <td><a href="javascript:document.forms[0].orderClause.value='ad.ad_city';document.forms[0].f_act.value='search';document.forms[0].submit();">Ort</a></td>
                    <td>&nbsp;</td>
                  </tr>                                
                  <?php echo $out ?>
                </table>
<?php if (false) : ?>
              </td>
            </tr>        
            <?php // echo $out_remarks ?>
          </table>
        </td>      
    </table>
<?php endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>

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

  <div>
    <?php echo $out_remarks ?>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>

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

</html>