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

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


getSecHttpVars("1", array("phrase", "compareType"));

getLanguage(__FILE__);

$deactivateMenuStatic = "1";
$pageTitel = getLngt("ÄHNLICHE SUCHERGEBNISSE");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");

getCurrentScript(__FILE__);

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

$debugON = false;

$regexpSQLArray = array();
$numOfChecksArray = array();

$phrase = trim($phrase);
$phraseOrg = $phrase;
// if (getEmpIdOfRootAdmin($userTypeName) == $emp_id) :
// echo $phrase . "<br>";
$phrase = str_replace(" mit ", " ", $phrase);
$phrase = str_replace(" und ", " ", $phrase);
$phrase = str_replace(" oder ", " ", $phrase);
$phrase = str_replace(" GmbH", "", $phrase);
$phrase = str_replace(" Co.", "", $phrase);
$phrase = str_replace(" KG", "", $phrase);
$phrase = str_replace("&", "", $phrase);
$phrase = str_replace("#", "", $phrase);
$phrase = str_replace("'", "", $phrase);
// echo $phrase . "<br>";
// Signs to be escaped for reg exp:  . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
$specialSignsArray = array("/\!/", "/§/", "/%/", "/\-/", "/_/", "/\./", "/\:/", "/,/", "/;/", "/\$/", "/\?/", "/\+/", "/\*/", "/\|/", "/\=/", "/\(/", "/\)/", "/\[/", "/\]/", "/\</", "/\>/");
$phrase = preg_replace ($specialSignsArray, "", $phrase);  // Remove special signs
// echo $phrase . "<br>";
// die();
// endif;

$wordArray = spliti(" ", $phrase);
$wordArrayLen = count($wordArray);
if ($wordArrayLen > 3) :
   $wordArray = array($wordArray[0], $wordArray[1], $wordArray[2]);
   $wordArrayLen = count($wordArray);
endif;

// Executes similarity search for the current headquarters logged in only
$parFilterHQ = getParameterValue("0", "SIMILARITY_SEARCH_FILTER_HQ", "0");
$whereClauseHQ = "";

if (!isset($compareType)) : $compareType = "cs"; endif;

$compareField = " cmp.cmp_comp ";
if ($compareType == "cs") :
   $compareField = " cmp.cmp_comp ";
   if ($parFilterHQ == "1" && $hq_id != "") :
      $whereClauseHQ = " AND cs.hq_id = '" . $hq_id . "' ";
   endif;
endif;
if ($compareType == "cr") :
   $compareField = " cmp.cmp_comp ";
   if ($parFilterHQ == "1" && $hq_id != "") :
      $whereClauseHQ = " AND cr.hq_id = '" . $hq_id . "' ";
   endif;
endif;



for ($i = 0; $i < $wordArrayLen; $i++) :

    $phrase = $wordArray[$i];
    $phraseLen = strlen($phrase);
    
    $regexpSQLArray[$i] = array();
    $numOfChecksArray[$i] = 0;
    
    if ($phraseLen > 0) :
    
       // [1.] Exact match by subtring
       $regexpSQLArray[$i][] = " LIKE '%" . $phrase . "%'";
    
       // [2.] All letters have to be found in the same sort sequence following directly
       // Example: "test" => ("blah test blah", "blah tttteeeesssstttt blah", "teeeeest") 
       $tmpRegexp = "";
       for ($j = 0; $j < $phraseLen; $j++) :
           $char = substr($phrase, $j, 1);
           $tmpRegexp .= $char . "+";
       endfor;
       $regexpSQLArray[$i][] = " REGEXP '" . $tmpRegexp . "'";
    
       // [3.] One of the letters could be another, but the rest has to match
       // Example: "test" => ("xxxxrestxxxxtastxxxxtertxxxxtesaxxxx")
       for ($j = 0; $j < $phraseLen; $j++) :
           $tmpSubstrLeft = substr($phrase, 0, $phraseLen - $j - 1);
           $tmpSubstrRight = substr($phrase, $phraseLen  - $j);
           $regexpSQLArray[$i][] = " REGEXP '" . $tmpSubstrLeft . "[[:alnum:][:blank:]]?" . $tmpSubstrRight . "'";
       endfor;
    
       // [4.] All letters have to be found in the same sort sequence
       // Example: "test" => ("blahxxxxxtyyyyyyyezzzzzzsxxxxtyyyyyblah") [look for letters "t","e","s","t"]
       $tmpRegexp = "";
       for ($j = 0; $j < $phraseLen; $j++) :
           $char = substr($phrase, $j, 1);
           $tmpRegexp .= $char . "+[[:alnum:][:blank:]]*";
       endfor;
//     $regexpSQLArray[$i][] = " REGEXP '" . $tmpRegexp . "'";

// SELECT cmp_comp, SOUNDEX(cmp_comp) FROM company WHERE (CAST(SUBSTRING(SOUNDEX(cmp_comp),2) AS UNSIGNED) - CAST(SUBSTRING(SOUNDEX('Frie'),2) AS UNSIGNED)) < 10

       $numOfChecksArray[$i] = count($regexpSQLArray[$i]);
    endif;
endfor;

// ---- DEBUG ----
if ($debugON) :
   echo "regexpSQLArray:<br>";
   print_r($regexpSQLArray);
   echo "<br><br>";
endif;
// ---------------

// Function to generate the WHERE clause according to the phrases
function generateWhereClause ($addedVector = array()) {
	global $whereClauseArray, $weightArray, $compareField;
	$whereClauseArrayLen = count($whereClauseArray);
	$addedVectorLen = count($addedVector);
	$newWhereClauseArray = array();
	$newWeightArray = array();
	if ($addedVectorLen > 0) :
	   $count = 0;
	   if ($whereClauseArrayLen > 0) :
        for ($i = 0; $i < $whereClauseArrayLen; $i++) :
    	       for ($j = 0; $j < $addedVectorLen; $j++) :
    	           $newWhereClauseArray[$count] = $whereClauseArray[$i];
    	           array_push($newWhereClauseArray[$count], $compareField . $addedVector[$j] . " ");
    	           $newWeightArray[$count] = max($weightArray[$i] + (10 - $j), 50);
    	           $count++;
    	       endfor;
    	  endfor;
    else :
        for ($j = 0; $j < $addedVectorLen; $j++) :
            $newWhereClauseArray[$count] = array($compareField . $addedVector[$j] . " ");
            $newWeightArray[$count] = (10 - $j);
            $count++;
        endfor;
    endif;
	endif;
	$whereClauseArray = $newWhereClauseArray;
	$weightArray = $newWeightArray;
}


// Generate WHERE clause array
$whereClauseArray = array();
$weightArray = array();
$numOfChecksArrayLen = count($numOfChecksArray);
if ($numOfChecksArrayLen > 0) :
   for ($k = 0; $k < $numOfChecksArrayLen; $k++) :
       generateWhereClause($regexpSQLArray[$k]);
   endfor;
endif;

// Extend WHERE clause for exact match
for ($i = 0; $i < $wordArrayLen; $i++) :
    $whereClauseArrayLen = count($whereClauseArray);
    $whereClauseArray[$whereClauseArrayLen][0] = $compareField . "= '" . $wordArray[$i] . "' ";
    $weightArray[$whereClauseArrayLen] = 100;
endfor;

// Extend WHERE clause for exact match by prefix
for ($i = 0; $i < $wordArrayLen; $i++) :
    $whereClauseArrayLen = count($whereClauseArray);
    $whereClauseArray[$whereClauseArrayLen][0] = $compareField . "LIKE '" . $wordArray[$i] . "%' ";
    $weightArray[$whereClauseArrayLen] = 70;
endfor;

// Extend WHERE clause for exact match by prefix AND combination with other expressions
for ($i = 0; $i < $wordArrayLen; $i++) :
    $numOfChecksArrayLen = count($numOfChecksArray);
    if ($numOfChecksArrayLen > 0) :
       for ($k = 0; $k < $numOfChecksArrayLen; $k++) :
           if ($i != $k) :
              $addedVectorLen = count($regexpSQLArray[$k]);
              for ($j = 0; $j < $addedVectorLen; $j++) :
                  $whereClauseArrayLen = count($whereClauseArray);
                  $whereClauseArray[$whereClauseArrayLen][0] = $compareField . "LIKE '" . $wordArray[$i] . "%' ";
                  $whereClauseArray[$whereClauseArrayLen][1] = $compareField . $regexpSQLArray[$k][$j] . " ";
                  $weightArray[$whereClauseArrayLen] = 90 - $j;
              endfor;
           endif;
       endfor;
    endif;
endfor;

// ---------------
if ($debugON) :
   echo "whereClauseArray:<br>";
   print_r($whereClauseArray);
   echo "<br><br>";
   echo "weightArray:<br>";
   print_r($weightArray);
   echo "<br><br>";
endif;
// ---------------


// Iterate WHERE clause array and define SQL statements
$output = "";
$sqlStatementArray = array();
$whereClauseArrayLen = count($whereClauseArray);
if ($whereClauseArrayLen > 0) :

   // Iterate word vector (each component is a word) with different number of check statements
   for ($k = 0; $k < $whereClauseArrayLen; $k++) :

       // Generate statements according to the regular expressions
       $whereClause = implode(" AND ", $whereClauseArray[$k]);
       $whereClause .= " AND ";

       if ($compareType == "cr") :
          $sqlStatementArray[] = "SELECT cmp.cmp_id, cmp.cmp_comp, cmp.cmp_comp2, cr.cr_eid, hq.hq_mnemonic, '" . $weightArray[$k] .  "' AS mysort"
                               . " FROM company AS cmp, courier AS cr, user AS usr, address AS ad, headquarters AS hq"
                               . " WHERE " . $whereClause
                               . "       cmp.cmp_id = cr.cmp_id AND"
                               . "       cr.usr_id = usr.usr_id AND"
                               . "       cmp.ad_id = ad.ad_id AND"
                               . "       cr.hq_id = hq.hq_id" . $whereClauseHQ;

       else :  // "cs"
          $sqlStatementArray[] = "SELECT cmp.cmp_id, cmp.cmp_comp, cmp.cmp_comp2, cs.cs_eid, hq.hq_mnemonic, '" . $weightArray[$k] .  "' AS mysort"
                               . " FROM company AS cmp, customer AS cs, employee AS emp, user AS usr, address AS ad, headquarters AS hq"
                               . " WHERE " . $whereClause
                               . "       cmp.cmp_id = cs.cmp_id AND"
                               . "       cs.cs_admin = emp.emp_id AND"
                               . "       emp.usr_id = usr.usr_id AND"
                               . "       cmp.ad_id = ad.ad_id AND"
                               . "       cs.hq_id = hq.hq_id" . $whereClauseHQ;
       endif;
   endfor;

   // Generate UNION statement
   $sqlQuery = "(" . implode(") UNION (", $sqlStatementArray) . ") ORDER BY mysort DESC, cmp_comp";
   // ---- DEBUG ----
   if ($debugON) :
      echo "<br><br>" . $sqlQuery . "<br><br>";
   endif;
   // ---------------
   $result = $db->query($sqlQuery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

   // Generate unique array
   $rowArray = array();
   while ($row = $result->fetchRow()):
         if (!is_array($rowArray[$row["cs_eid"]])) :
            $rowArray[$row["cs_eid"]] = array($row["mysort"], $row["cmp_comp"], $row["cmp_comp2"], $row["cs_eid"], $row["cmp_id"]);
         endif;
   endwhile;
   $result->free();

   // Output
/*
   $keyArray = array_keys($rowArray);
   $keyArrayLen = count($keyArray);
   for ($j = 0; $j < $regexpSQLArrayLen; $j++) :
       for ($i = 0; $i < $keyArrayLen; $i++) :
           if ($rowArray[$keyArray[$i]][0] == $j) :
              echo $rowArray[$keyArray[$i]][0] . "&nbsp;&nbsp;&nbsp;&nbsp;" . $rowArray[$keyArray[$i]][1] . "&nbsp;&nbsp;&nbsp;&nbsp;" . $rowArray[$keyArray[$i]][2] . "&nbsp;&nbsp;&nbsp;&nbsp;" . $rowArray[$keyArray[$i]][3] . "&nbsp;&nbsp;&nbsp;&nbsp;" . $rowArray[$keyArray[$i]][4] . "<br>";
           endif;
       endfor;
   endfor;
*/
   $keyArray = array_keys($rowArray);
   $keyArrayLen = count($keyArray);
   $output .= "<table>";
   for ($i = 0; $i < $keyArrayLen; $i++) :
       $output .= "<tr>";
       $output .= "<td><a href=\"../admin/customer_special.php?companyId=" . $rowArray[$keyArray[$i]][4] . "\" target=\"_blank\">" . $rowArray[$keyArray[$i]][3] . "</a></td><td>" . $rowArray[$keyArray[$i]][1] . "</td><td>" . $rowArray[$keyArray[$i]][2] . "</td>";
       $output .= "</tr>";
   endfor;
   $output .= "</table>";
endif;
?>

<html lang="de">
<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 src="../include/checkFormTags.js" type="text/javascript"></script>

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

var refreshStatus = 1;

function startReload() {  
  if (refreshStatus == 1) {
     // self.location.reload();
     // document.forms[0].submit();
     this.close();
  }
}

function startTimeout() {  
  self.setTimeout("startReload()", 90000);
}  

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

function openCustomerSpecial(cmpId) {
  var widthPopupWin = 900;
  var heightPopupWin = 750;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/customer_special.php?companyId=" + cmpId ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};
-->
</script>
<noscript>
  <center>
  <b><br>JavaScript ist nicht verf&uuml;gbar. Bitte aktivieren Sie JavaScript<br><br>
        in Ihrem Browser, damit diese Seite ordnungsgem&auml;&szlig; funktioniert!</b><br><br>
  </center>
</noscript>
</head>

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

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

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

<form action="../admin/nearBySearch.php" method="post">
  
  <input type="hidden" name="f_act" value="">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

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

  <?php echo htmlDivLineSpacer("10px"); ?>
  
  <div class="f12bp1_blue">
    <?php echo getLngt("Ähnlichkeitssuche"); ?>
  </div>
  <?php echo htmlDivLineSpacer("20px"); ?>
  
  <div style="float:left;">
  	<input type="text" name="phrase" value="<?php echo $phraseOrg ?>" size="50" maxlength="50">&nbsp;&nbsp;
  </div>
  <?php echo defineButtonType10(getLngt("Neue Suche"), "action_list", "finishPage('search');", "120", "left", "5"); ?>
  <?php echo defineButtonType10(getLngt("Schließen"), "action_list", "window.close();", "120", "left"); ?>
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>

  <div class="f10bp1_blue">
    <?php echo getLngt("Suchergebnisse"); ?>
  </div>
  <?php echo htmlDivLineSpacer("20px"); ?>
  
  <div class="f12bp1_blue">
    <?php echo $output ?>
  </div>
  <?php echo htmlDivLineSpacer("30px"); ?>

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