<?php

	include "library.php";

	$cxn = start_code();


		/* start the page  */

		// don't put this before a jump_to_page()
//	page_header( "View Profiles", $cxn );

	if (val( $_GET, 'country' ) != "")
		$curr_country = urldecode( val( $_GET, 'country' ) );
	else
		$curr_country = "";


		/* not required unless a compatability search */

	$id = val( $_SESSION, 'id' );


		/* determine the search criteria */

	$min_age = prep_for_sql( val( $_SESSION, "min_age" ) );
	$max_age = prep_for_sql( val( $_SESSION, "max_age" ) );
	$sex = prep_for_sql( val( $_SESSION, "sex" ) );
	$sex_wanted = prep_for_sql( val( $_SESSION, "sex_wanted" ) );
	$search_for = prep_for_sql( val( $_SESSION, "search_for" ) );
	$city = prep_for_sql( val( $_SESSION, "city" ) );
	$state = prep_for_sql( val( $_SESSION, "state" ) );
	$country = prep_for_sql( val( $_SESSION, "country" ) );
	$search_for_word = prep_for_sql( val( $_SESSION, "search_for_word" ) );
	$compatability = prep_for_sql( val( $_SESSION, "compatability" ) );
	$logged_on = prep_for_sql( val( $_SESSION, "logged_on" ) );

	$start_pos = val( $_GET, "startpos" );


		/* must be logged in for compatability mode */

	if ($id == "" && $compatability == "on")
	{
		$_SESSION['nextpage'] = url_encode( "view_profiles.php", "startpos", $start_pos, "country", rawurlencode( $curr_country ) );

		jump_to_page( "login.php" );	/* must happen before print output */

		exit();
	}
	
	crash_if_missing( $start_pos, "start pos missing in view_profiles", $cxn );

	if ($min_age == "")
		$min_age = "18";

	if ($max_age == "")
		$max_age = "200";

	$query = "SELECT profile.id as id, profile.handle, profile.short_intro, profile.city, profile.country, profile.last_login, year(profile.date_of_birth) as dob_year, dayofyear(profile.date_of_birth) as dob_dayofyear, online_status.id as logged_in FROM profile LEFT JOIN online_status ON online_status.member_id = profile.id WHERE visibility = 'all_members' and deleted = 'no' AND locked  = 'no' and email_address_valid = 'yes' and system_user = 'no'";

	if ($sex == "Men")
		$query = $query." AND sex = 'Male'";
	else
	if ($sex == "Women")
		$query = $query." AND sex = 'Female'";

	if ($sex_wanted == "Men")
		$query = $query." AND sex_wanted = 'Men'";
	else
	if ($sex_wanted == "Women")
		$query = $query." AND sex_wanted = 'Women'";

	if ($search_for == "Relationship")
		$query = $query." AND wants_relationship = 'on'";

	if ($search_for == "Friendship")
		$query = $query." AND wants_friendships = 'on'";

	if ($state != "")
		$query = $query." AND state = '".$state."'";

	if ($country != "")
		$query = $query." AND country = '".$country."'";

	if ($search_for_word != "")
		$query = $query." AND (short_intro like '%".$search_for_word."%' OR general_comments like '%".$search_for_word."%' OR looking_for like '%".$search_for_word."%' )";

	if ($logged_on == "on")
		$query = $query." AND profile.id IN (SELECT member_id FROM online_status) ";


		/* don't show members in search list that have already had contact */

	if ($id != "")
	{
		$query = $query." AND profile.id <> ".$id;

		if (! is_system_user( $id, $cxn ))
			$query = $query." AND profile.id NOT IN (SELECT DISTINCT sender_id FROM message WHERE receiver_id = ".$id.") AND profile.id NOT IN (SELECT DISTINCT receiver_id FROM message WHERE sender_id = ".$id.")";
	}

	$query .= " ORDER BY last_login DESC";


		/* run the query */

	$result = run_query( $query, $cxn );

	$found_one = "false";


		/* put rows in the age range into the array */

	$num_rows = 0;

	for ($i=0; $i < mysql_num_rows($result); $i++)
	{
		$this_row = get_row( $result );

		if ((date("z")+1) > $this_row['dob_dayofyear'])
			$age = date( "Y" ) - $this_row['dob_year'];
		else
			$age = date( "Y" ) - $this_row['dob_year'] - 1;

		if ($age >= $min_age && $age <= $max_age)
		{
			$include = true;

			if ($city != "")
			{
				if (city_name( $city, $cxn ) == city_name( $this_row['city'], $cxn ))
					$include = true;
				else
					$include = false;
			}

			if ($include)
			{
				$data[$num_rows] = $this_row;

				if ($compatability == "on")
					$key_values[$num_rows] = calc_compatability_score( $id, $this_row['id'], $cxn );
				else
					$key_values[$num_rows] = $this_row['last_login'];
				
				$num_rows++;
			}
		}
	}

		/* sort by the relevant key/score */

	if ($num_rows != 0)
	{
		$key_values = sort_array( $key_values, $num_rows );

		for ($i=0; $i < $num_rows; $i++)
			$data2[$i] = $data[$key_values[$i]];

		$data = $data2;
	}
	

		/* if the user's search result was too restrictive, widen it */

	if (val( $_SESSION, 'search_attempt' ) == "1" && $num_rows < 10 && $start_pos == "0" && $logged_on != "on")
		widen_search( $min_age, $max_age, $country, $cxn );


		/* page output starts here */

	page_header( "View Profiles", $cxn );


	if (val( $_SESSION, 'search_attempt' ) == "2" && $num_rows != 0)
		echo "<p align='center'>".black( "Your search returned a small number of results. This is a wider search." )."</p>";


		/* profile numbers in the list start at 0 */
		/* move down the list to the starting position */

	$num_per_page = 25;

	if ($start_pos + $num_per_page <= $num_rows)
		$num_this_page = $num_per_page;
	else
		$num_this_page = $num_rows - $start_pos;


		/* show the profile list display */

	for ($i=$start_pos; $i < $start_pos + $num_this_page; $i++)
	{
		$found_one = "true";

		if ($i == $start_pos)
			echo "<hr>";

		echo "<a name='id".$data[$i]['id']."'>";		/* bookmark to go back to search screen */

		echo "<table width='100%'><tr>";

		echo "<td width='10%'>";

		echo show_handle( $data[$i]['id'], $data[$i]['handle'], "search", $start_pos );

		if ($data[$i]['logged_in'] != "")
			echo "<br><br>".watermark( "online now" );

		echo "</td><td width='16%' align='center'>";

		show_photo( $data[$i]['id'], 100, -1, true, false, $cxn );

		echo "</td>";

		echo "<td width='52%'>".black( convert_to_html( $data[$i]['short_intro'] ) )."</td>";

		echo "<td width='2%'></td>";

		echo "<td width='10%'>".black( name_case( $data[$i]['city'] ) )."</td>";

		if ($country == "")
			echo "<td width='10%'>".black( $data[$i]['country'] )."</td>";
		else
			echo "<td width='10%'></td>";

		echo "</tr></table><hr>";
	}

	if ($found_one == "false")
	{
		if ($logged_on == "on")
			echo "<br><br><br><br><p align='center'>".black( "There are no members logged on who match your search criteria" )."</p><br>";
		else
			echo "<br><br><br><br><p align='center'>".black( "There are no profiles matching your search criteria" )."</p><br>";
	}
	else
	{
			/* show the next-page and previous-page links */

		$prev_page = $start_pos - $num_per_page;
		$next_page = $start_pos + $num_per_page;
		$end_pos = $start_pos + $num_this_page - 1;

		echo "<p align='center'>";

		$start = $start_pos + 1;
		$end = $end_pos + 1;

		echo black( "Profiles ".$start." to ".$end."<br><br>" );

		if ($start_pos > 1)
			echo show_link( "Previous Page", "view_profiles.php", "startpos", $prev_page );

		if ($start_pos + $num_per_page < $num_rows)
		{
			if ($start_pos > 1)
				echo sp(10);

			echo show_link( "Next Page", "view_profiles.php", "startpos", $next_page );
		}

		echo "</p>";
	}

	echo "<p align='center'>".pink( "This is a new site and our membership base is growing rapidly. " );
	echo pink( "We invite you to " )."<a class='gpink' href='".url_encode( "edit_profile.php", "newprofile", "true"  )."'>".pink( "<span style='text-decoration: underline'>create a profile</span>" )."</a></p>";


		/* a few blank lines so text is not crammed at the end of the screen */

	echo "<br>";

//	echo "<p align='center'>".black( "To see a search of all members " ).show_link( "click here", "search_all.php" )."</p>";


		/* show ads for non-charging countries */

	echo "<br>";

	show_ads( $cxn );

	echo "</body></html>";


		/* remove spaces, punctuation etc and convert to lower case */

	function prep_city( $city )
	{
		$city_res = "";

		$city = strtolower( $city );

		for ($i=0; $i < strlen( $city ); $i++)
		{
			if (substr( $city, $i, 1 ) >= "a" && substr( $city, $i, 1 ) <= "z")
				$city_res .= substr( $city, $i, 1 );
		}

		return ($city_res);
	}


		/* widen the search parameters and re-run the search */

	function widen_search( $min_age, $max_age, $country, $cxn )
	{
		$_SESSION['search_attempt'] = "2";

		$_SESSION['state'] = "";
		$_SESSION['city'] = "";

			/* eliminte country restriction if less than 50 profiles */

		$query = "SELECT count(*) as num FROM profile WHERE country = '".$country."'";

		$result = run_query( $query, $cxn );

		if (mysql_num_rows($result) > 0)
		{
			$data = get_row( $result );

			if ($data['num'] < 30)
				$_SESSION['country'] = "";

		}

			/* widen age range */

		if (($max_age - $min_age) < 10)
		{
			$max_age = $max_age + 5;
			$min_age = $min_age - 5;

			if ($min_age < 18)
				$min_age = 18;

			$_SESSION['min_age'] = $min_age;
			$_SESSION['max_age'] = $max_age;
		}

			/* must happen before print output */
			
		jump_to_page( "view_profiles.php", "startpos", "0" );

		exit();
	}


		/* check for common spellings of the city */

	function city_name( $city, $cxn )
	{
		$city = prep_city( $city );

		$city_res = $city;

		$query = "SELECT city FROM city_spellings WHERE spelling = '".$city."'";

		$result = run_query( $query, $cxn );

		if (mysql_num_rows($result) > 0)
		{
			$data = get_row( $result );
			$city_res = $data['city'];
		}

		return ($city_res);
	}


		/* returns the compatability score between two members */
		/* not symmetrical because depends on last login of $found_id */

	function calc_compatability_score( $id, $found_id, $cxn )
	{
		$score = 100;

		$query1 = "SELECT * FROM profile WHERE id = ".$id;

		$result1 = run_query( $query1, $cxn );
		$data1 = get_row( $result1 );

		$query2 = "SELECT * FROM profile WHERE id = ".$found_id;

		$result2 = run_query( $query2, $cxn );
		$data2 = get_row( $result2 );


			/* check that they are looking for the correct sex */

		if ($data1['sex_wanted'] == 'Men' && $data2['sex'] == 'Female')
			$score -= 200;

		if ($data1['sex_wanted'] == 'Women' && $data2['sex'] == 'Male')
			$score -= 200;

		if ($data2['sex_wanted'] == 'Men' && $data1['sex'] == 'Female')
			$score -= 200;

		if ($data2['sex_wanted'] == 'Women' && $data1['sex'] == 'Male')
			$score -= 200;


			/* subtract points for percentage age difference */
			/* 10% = 20 points */

		$age1 = check_date( $data1['date_of_birth'], $cxn );
		$age2 = check_date( $data2['date_of_birth'], $cxn );

		if ($age1 != 0 && $age2 != 0)
		{
			if ($age1 > $age2)
				$score -= 200 * ($age1 / $age2) - 1;
			else
				$score -= 200 * ($age2 / $age1) - 1;
		}
		else
			$score -= 20;


			/* +20 points for important words in both profiles */

		$text1 = $data1['short_intro']." ".$data1['interests']." ".$data1['general_comments']." ".$data1['looking_for'];
		$text2 = $data2['short_intro']." ".$data2['interests']." ".$data2['general_comments']." ".$data2['looking_for'];
		
		if (strpos( $text1, "marriage" ) !== false && strpos( $text2, "marriage" ) !== false)
			$score += 20;

		if (strpos( $text1, "sex" ) !== false && strpos( $text2, "sex" ) !== false)
			$score += 20;

		if (strpos( $text1, "fun" ) !== false && strpos( $text2, "fun" ) !== false)
			$score += 20;

		if (strpos( $text1, "serious" ) !== false && strpos( $text2, "serious" ) !== false)
			$score += 20;

		if (strpos( $text1, "christian" ) !== false && strpos( $text2, "christian" ) !== false)
			$score += 20;

		if (strpos( $text1, "relationship" ) !== false && strpos( $text2, "relationship" ) !== false)
			$score += 20;

		if (strpos( $text1, "family" ) !== false && strpos( $text2, "family" ) !== false)
			$score += 20;

		if ((strpos( $text1, "husband" ) !== false || strpos( $text1, "wife" ) !== false) && (strpos( $text2, "husband" ) !== false || strpos( $text2, "wife" ) !== false))
			$score += 20;


			/* check for matching profile parameters */

		if ($data1['wants_relationship'] == $data2['wants_relationship'])
			$score += 20;

		if ($data1['wants_friendships'] == $data2['wants_friendships'])
			$score += 20;

		if ($data1['wants_children'] == $data2['wants_children'])
			$score += 20;

		if ($data1['religion'] == $data2['religion'])
			$score += 10;

		if ($data1['country'] == $data2['country'])
			$score += 10;

			/* -0.5 points for each day since login or same list */
			/* will appear every time */

		$score -= 0.5 * ((time() - strtotime($data2['last_login']) / (24*60*60)));

		return ($score);
	}


		/* sort an array of sort keys */

	function sort_array( $key_values, $num_rows )
	{
		arsort( $key_values );

		$i = 0;

		foreach ($key_values as $key => $val)
		{
			$key_data2[$i] = $key;
			$i++;
		}

		return ($key_data2);
	}
?>

