<?PHP

/** TO DO **

- Allow users to search by start time
- Allow users to search by entry fee

************/

include("config.php");
require_once("rating/classes/include.all.php");

// string comparison match percent
$comp_pct = 80;

if (!$_POST){ header('Location: '.$site_url); }

// build the SQL query
$sql = 'SELECT retailer_id, retailer_name, retailer_address, retailer_address_two, retailer_city, retailer_state, retailer_zip, retailer_phone, retailer_fax, retailer_email, retailer_website, retailer_cart FROM gforum_Retailers WHERE retailer_valid=1 ';

// add fitters

if (isset($_POST[fitters])) {
  // FIST tri
  if (in_array('fist', $_POST[fitters])) {
    $sql = $sql." AND retailer_fist = 1";
  }
  // FIST road
  if (in_array('fist_road', $_POST[fitters])) {
    $sql = $sql." AND retailer_fist_road = 1";
  }
  // FIST advanced
  if (in_array('fist_advanced', $_POST[fitters])) {
    $sql = $sql." AND retailer_fist_advanced = 1";
  }
  // Serotta
  if (in_array('serotta', $_POST[fitters])) {
    $sql = $sql." AND retailer_serotta = 1";
  }
  // Any
  if (in_array('any', $_POST[fitters])) {
    $sql = $sql." AND (retailer_serotta = 1 OR retailer_fist = 1 OR retailer_fist_road = 1)";
  }
}

if (isset($_POST[methods])) {
  if (in_array("999", $_POST[methods])) {
  		$sql = $sql." AND retailer_method <> '0'";
  } else {
	  	$sql = $sql." AND (";
  	  	$flag = 0;
	  	foreach ($_POST[methods] AS $value) {
	    	if ($flag == 1){
	    		$sql = $sql." OR ";
	    	}
			$sql = $sql." retailer_method = '$value'";
			$flag = 1;
	  	}
	  	$sql = $sql.")";
  }
}

if (isset($_POST[fitbikes])) {
  if (in_array("999", $_POST[fitbikes])) {
  		$sql = $sql." AND retailer_fitbikes <> ',0,'";
  } else {
  	  $sql = $sql." AND (";
  	  $flag = 0;
	  foreach ($_POST[fitbikes] AS $value) {
	    if ($flag == 1){
	    	$sql = $sql." OR ";
	    }
		$sql = $sql." retailer_fitbikes LIKE '%,$value,%'";
		$flag = 1;
	  }
	  $sql = $sql.")";
	  /**foreach ($_POST[fitbikes] AS $value) {
		$sql = $sql." AND retailer_fitbikes LIKE '%,$value,%'";  
	  }**/
  }
}

if (isset($_POST[motioncapture])) {
  if (in_array("999", $_POST[motioncapture])) {
  		$sql = $sql." AND retailer_motioncapture <> ',0,'";
  } else {
  	  $sql = $sql." AND (";
  	  $flag = 0;
	  foreach ($_POST[motioncapture] AS $value) {
	    if ($flag == 1){
	    	$sql = $sql." OR ";
	    }
		$sql = $sql." retailer_motioncapture LIKE '%,$value,%'";
		$flag = 1;
	  }
	  $sql = $sql.")";
	  /**foreach ($_POST[motioncapture] AS $value) {
		$sql = $sql." AND retailer_motioncapture LIKE '%,$value,%'";  
	  }**/
  }
}

if (isset($_POST[ecommerce])) {
  $sql = $sql." AND retailer_cart = 1";  
}

if (isset($_POST[spoke])) {
  $sql = $sql." AND retailer_spoke = 1";  
}

if (isset($_POST[mailorder_ecommerce])) {
  $sql = $sql." AND retailer_mailorder_ecommerce = 1";  
}
if (isset($_POST[mailorder_phone])) {
  $sql = $sql." AND retailer_mailorder_phone = 1";  
}
if (isset($_POST[local_ecommerce])) {
  $sql = $sql." AND retailer_local_ecommerce = 1";  
}
if (isset($_POST[local_phone])) {
  $sql = $sql." AND retailer_local_phone = 1";  
}
if (isset($_POST[pickup_ecommerce])) {
  $sql = $sql." AND retailer_pickup_ecommerce = 1";  
}
if (isset($_POST[pickup_phone])) {
  $sql = $sql." AND retailer_pickup_phone = 1";  
}
if (isset($_POST[ecommerce])) {
  $sql = $sql." AND retailer_cart = 1";  
}

if (isset($_POST[wetsuits])) {  
	$sql = $sql." AND (";
	$flag = 0;
	foreach ($_POST[wetsuits] AS $value) {
	if ($flag == 1){
		$sql = $sql." OR ";
	}
	$sql = $sql." retailer_wetsuits LIKE '%,$value,%'";
	$flag = 1;
	}
	$sql = $sql.")";
  /**foreach ($_POST[wetsuits] AS $value) {
	$sql = $sql." AND retailer_wetsuits LIKE '%,$value,%'";  
  }**/
}

if (isset($_POST[bikes])) {
	$sql = $sql." AND (";
	$flag = 0;
	foreach ($_POST[bikes] AS $value) {
	if ($flag == 1){
		$sql = $sql." OR ";
	}
	$sql = $sql." retailer_bikes LIKE '%,$value,%'";
	$flag = 1;
	}
	$sql = $sql.")";
  /**foreach ($_POST[bikes] AS $value) {
	$sql = $sql." AND retailer_bikes LIKE '%,$value,%'";  
  }**/
}

if (isset($_POST[customs])) {
	$sql = $sql." AND (";
	$flag = 0;
	foreach ($_POST[customs] AS $value) {
	if ($flag == 1){
		$sql = $sql." OR ";
	}
	$sql = $sql." retailer_customs LIKE '%,$value,%'";
	$flag = 1;
	}
	$sql = $sql.")";
  /**foreach ($_POST[customs] AS $value) {
	$sql = $sql." AND retailer_customs LIKE '%,$value,%'";  
  }**/
}

// add tri or du or other
/*if (isset($_POST[type])) {
  // convert the array to a SQL friendly format
  $typelist = "(".implode(",", $_POST[type]).")";
  $sql = $sql." AND type IN $typelist";
}*/

// regions are checkboxes that then check off all states within that region
// add states
if (isset($_POST[states])) {
  $glue = "','";
  $statelist = "('".implode($glue, $_POST[states])."')";
  $sql = $sql." AND retailer_state_tag IN $statelist";
}


$sql = $sql." ORDER BY retailer_name ASC";

//echo $sql;

$results = mysql_query(mysql_real_escape_string($sql));

$none = FALSE;
if (mysql_num_rows($results) == 0) {
  $none = TRUE;
}
$match_count = mysql_num_rows($results);

//keyword search
// trim redundant keywords: triathlon, duathlon
$trim_words = array(" the ", " a ", " an ", "and ", " half ", "triathlon", "duathlon");
foreach ($trim_words AS $word) {
	$_POST['keyword'] = str_ireplace($word, " ", $_POST['keyword']);
}
$bool_Keywords = false;
if (isset($_POST['keyword']) && $_POST['keyword'] != "") {
	$bool_Keywords = true;
	while($row_retaileres = mysql_fetch_array($results)) {
		// build an array that we can loop through.
		$arr_retaileres[$i] = $row_retaileres;
		$i++;
	}
	
	$arr_Matches = array();
	foreach ($arr_retaileres AS $retailer) {	
			if (stripos($retailer['retailer_name'], $_POST['keyword']) !== false) {
				// push this onto the array of matches
				$retailer['percent'] = 100;
				array_push($arr_Matches, $retailer);
			} else {
				$name_nospace = str_replace(" ", "", $retailer['retailer_name']);
				$keyword_nospace = str_replace(" ", "", $_POST['keyword']);
				if (stripos($name_nospace, $keyword_nospace) !== false) {
					// push this onto the array of matches
					$retailer['percent'] = 90;
					array_push($arr_Matches, $retailer);
				} else {
					// trim redundant keywords
					$retailer_name = $retailer['retailer_name'];
					foreach ($trim_words AS $word) {
						$retailer_name = str_ireplace($word, " ", $retailer_name);
					}
					//$retailer_name = str_ireplace(" ", "", $retailer_name);
					$retailer_name = strtolower($retailer_name);
					$arr_retailer_name = explode(" ", $retailer_name);
					$_POST['keyword'] = strtolower($_POST['keyword']);
					$_POST['keyword'] = str_replace(" ", "", $_POST['keyword']);
					foreach ($arr_retailer_name AS $test_word) {					
						similar_text($test_word, $_POST['keyword'], $percent);
						if ($percent >= $comp_pct) {
							// push this onto the array of matches
							$retailer['percent'] = round($percent, 0);
							//$retailer['trimmed'] = $retailer_name;
							array_push($arr_Matches, $retailer);
							break;
						}
					}
				}
			}
	}
	
	if (count($arr_Matches) == 0) {
 		$none = TRUE;
 	}
 	$match_count = count($arr_Matches);
 	
 	//sort the array by keyword match success instead of by date
 	function cmp($a, $b)
	{
		if ($a['percent'] == $b['percent']) {
			return 0;
		}
		return ($a['percent'] > $b['percent']) ? -1 : 1;
	}
	
	usort($arr_Matches, "cmp");
}
//end keyword search

// set the page title
$pagetitle = "Search Results";

// set meta tags
$meta_keywords = "search, retailers, triathlon, results";
$meta_description = "Triathlon retailers in matching a user's search query. A list of matching retailers.";
?>

<? include("include_common_head.php"); ?>

<body class="listings">
  <? include($common_path . "/ads/ad_wallpaper.html"); ?>

  <div class="container">
    <? include($common_path . "/templates/include_header.php"); ?>
    <div class="main">
      <div class="contentwrapper clearfix">
        <? include("include_breadcrumb.php"); ?>

        <section class="section listings section-has-widgets section-static remove-sidebar">
          <div class="sidebar-b">
            <? include("include_sidebar.php"); ?>
          </div>

          <div class="content content-has-widgets">
            <div class="grid">

              <div class="clearfix">
                <h1>Search Results</h1>
                <p><strong><? echo $match_count; ?> Retailers Match Your Search</strong></p>
                <? 
                if ($bool_Keywords == true) {
                    foreach($arr_Matches AS $row){	
                        include("include_store.php");
                    } // end foreach arr_Matches 
                } else { //if bool_Keywords
                    while ($row = mysql_fetch_array($results)) {
                        include("include_store.php");
                    } // end foreach mysql_fetch_array ?>
                <? } // end else ?>


              </div><!-- end col-2/3 -->

            </div><!-- end grid -->
          </div><!-- end content -->
        </section>

      </div><!-- end contentwrapper -->
    </div> <!-- end main -->

  <? include($common_path . "/templates/include_footer.php") ?>
  </div> <!-- container  -->
</body>
<? include($common_path . "/templates/include_global_js.php") ?>
</html>
