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

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

// build the SQL query
$sql = "SELECT coach_id, coach_name, coach_address, coach_address_two, coach_city, coach_state, coach_zip, coach_phone, coach_fax, coach_email, coach_website FROM ".$prefix."Coaches WHERE coach_valid=1 ";

// add coaches

if (isset($_POST[certifications])) {
  if (in_array("999", $_POST[certifications])) {
  		$sql = $sql." AND coach_certifications <> ',0,'";
  } else {
	  foreach ($_POST[certifications] AS $value) {
		$sql = $sql." AND coach_certifications LIKE '%,$value,%'";  
	  }
  }
}

if (isset($_POST[services])) {
  if (in_array("999", $_POST[services])) {
  		$sql = $sql." AND coach_services <> ',0,'";
  } else {
	  foreach ($_POST[services] AS $value) {
		$sql = $sql." AND coach_services LIKE '%,$value,%'";  
	  }
  }
}

if (isset($_POST[degree])) {
  if (in_array("999", $_POST[degree])) {
  		$sql = $sql." AND coach_degrees <> ',0,'";
  } else {
	  foreach ($_POST[degree] AS $value) {
		$sql = $sql." AND coach_degrees LIKE '%,$value,%'";  
	  }
  }
}

// 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 coach_state_tag IN $statelist";
}


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

//echo $sql;

$results = mysql_query($sql) OR die(mysql_error());

$none = FALSE;
if (mysql_num_rows($results) == 0) {
  $none = TRUE;
}
$coach_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_coaches = mysql_fetch_array($results)) {
		// build an array that we can loop through.
		$arr_coaches[$i] = $row_coaches;
		$i++;
	}
	
	$arr_Matches = array();
	foreach ($arr_coaches AS $coach) {	
			if (stripos($coach['coach_name'], $_POST['keyword']) !== false) {
				// push this onto the array of matches
				$coach['percent'] = 100;
				array_push($arr_Matches, $coach);
			} else {
				$name_nospace = str_replace(" ", "", $coach['coach_name']);
				$keyword_nospace = str_replace(" ", "", $_POST['keyword']);
				if (stripos($name_nospace, $keyword_nospace) !== false) {
					// push this onto the array of matches
					$coach['percent'] = 90;
					array_push($arr_Matches, $coach);
				} else {
					// trim redundant keywords
					$coach_name = $coach['coach_name'];
					foreach ($trim_words AS $word) {
						$coach_name = str_ireplace($word, " ", $coach_name);
					}
					//$coach_name = str_ireplace(" ", "", $coach_name);
					$coach_name = strtolower($coach_name);
					$arr_coach_name = explode(" ", $coach_name);
					$_POST['keyword'] = strtolower($_POST['keyword']);
					$_POST['keyword'] = str_replace(" ", "", $_POST['keyword']);
					foreach ($arr_coach_name AS $test_word) {					
						similar_text($test_word, $_POST['keyword'], $percent);
						if ($percent >= 70) {
							// push this onto the array of matches
							$coach['percent'] = round($percent, 0);
							//$coach['trimmed'] = $coach_name;
							array_push($arr_Matches, $coach);
							break;
						}
					}
				}
			}
	}
	
	if (count($arr_Matches) == 0) {
 		$none = TRUE;
 	}
 	$coach_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, coaches, triathlon, results";
$meta_description = "Triathlon coaches matching a user's search query. A list of matching coaches.";
?>

<? 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><b><? echo $coach_count; ?></b> Coaches Match Your Search</p>
                    
                    <table border="0" cellspacing="0" cellpadding="1" width="580">
                    <? 
                    $x = 0;
                    if ($bool_Keywords == true) {
                        foreach ($arr_Matches AS $row) {
                            include("include_store.php");
                        } //end foreach
                    } else { //else bool_keyword
                        while ($row = mysql_fetch_array($results)) {
                            include("include_store.php");
                        } //end while ?>
                    <? } // end if/else ?>
                    </table>

              </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>