<?php

	include "library.php";

	$cxn = start_code();

	$cxn_common = db_common_login();



		/* not required unless a compatability search */

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


	$today_date = date_create( date("Y-m-d") );
	$today_minus_365_days = clone $today_date;

	date_sub( $today_minus_365_days, date_interval_create_from_date_string( '365 days' ));
    $today_minus_365_days_str = $today_minus_365_days->format( "Y-m-d 00:00:00" );		


		/* determine the search criteria */

	$min_age = str_replace( "'", "''", val( $_SESSION, "smin_age" ) );
	$max_age = str_replace( "'", "''", val( $_SESSION, "smax_age" ) );
	$city = str_replace( "'", "''", val( $_SESSION, "scity" ) );
	$state = str_replace( "'", "''", val( $_SESSION, "sstate" ) );
	$country = str_replace( "'", "''", val( $_SESSION, "scountry" ) );
	$region = str_replace( "'", "''", val( $_SESSION, "sregion" ) );	
	$search_for_word = str_replace( "'", "''", val( $_SESSION, "ssearch_for_word" ) );
	$compatability = str_replace( "'", "''", val( $_SESSION, "scompatability" ) );
	$logged_on = str_replace( "'", "''", val( $_SESSION, "slogged_on" ) );
	$sex_and_seeking = str_replace( "'", "''", val( $_SESSION, "ssex_and_seeking" ) );
	$tick_if_gay = str_replace( "'", "''", val( $_SESSION, "stick_if_gay" ) );		


	$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 );

	    jump_to_page( val( $_SESSION, "login_page" ) );		/* must happen before print output */

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

    log_hits( "search", $cxn, $cxn_common );

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

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

    $sex = "";	    
    $sex_wanted = "";	    
    $search_for = "";


	if ($sex_and_seeking == "Men")
	{
	    $sex = "Men";	    
	}
	else
	if ($sex_and_seeking == "Women")
	{
	    $sex = "Women";	    	   	    
	}


	$query = "SELECT profile.id as id, profile.handle, profile.short_intro, profile.city, profile.country, profile.last_login, ";

	$query .= "online_status.id as logged_in, academi1_commondata.country.region FROM profile LEFT JOIN online_status ON online_status.member_id = profile.id ";

	$query .= "LEFT JOIN academi1_commondata.country ON academi1_commondata.country.display_name = profile.country WHERE ";

	$query .= " deleted = 'no' AND locked  = 'no' AND returned_mail  = 'no' AND email_address_valid = 'yes' AND system_user = 'no'";



        // only include memebers in search results who have logged in within the last 12 months
    
    $query = $query." AND last_login >= '".$today_minus_365_days_str."'";

//    if ($tick_if_gay == "on")
//		$query = $query." AND tick_if_gay = 'on'";
//    else
//        $query = $query." AND tick_if_gay <> 'on'";
        
	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 ($city != "")
		$query = $query." AND city = '".$city."'";

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


            // don't restrict on region if country is also specified as they may conflict
            
	if ($country == "" && $region != "")
		$query = $query." AND region  = '".$region."'";

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

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


	$today_date_obj = date_create( date("Y-m-d") );
									
	$min_date_of_birth = clone $today_date_obj;
		
	date_sub( $min_date_of_birth, date_interval_create_from_date_string( $min_age." years" ));

	$min_date_of_birth_str = $min_date_of_birth->format( "Y-m-d" );		
	
	$query = $query." AND date_of_birth < '".$min_date_of_birth_str."'";


	$max_date_of_birth = clone $today_date_obj;
		
	date_sub( $max_date_of_birth, date_interval_create_from_date_string( $max_age." years" ));

	$max_date_of_birth_str = $max_date_of_birth->format( "Y-m-d" );		
	
	$query = $query." AND date_of_birth > '".$max_date_of_birth_str."'";


		/* 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 membership_type DESC, last_login DESC LIMIT 3000";

        // don't retrieve too many profiles otherwise the compatability search will be very slow.
        
	$query .= " ORDER BY last_login DESC LIMIT 1000";


		/* run the query */

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

	$found_one = "false";


		// may not be logged in 

    if ($id != "")
    {
    	$query1 = "SELECT * FROM profile WHERE id = ".$id;
    
    	$result1 = run_query( $query1, $cxn );
    	$data1 = get_row( $result1 );
    }
    
	$num_rows = 0;

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

		$data[$num_rows] = $this_row;


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

//		$key_values[$num_rows] = $i;

		$num_rows++;
	}



	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 < 1 && $start_pos == "0")
		widen_search( $min_age, $max_age, $country, $cxn, $cxn_common );


		/* page output starts here */

	page_header( "View Profiles", $cxn, $cxn_common );


	if (val( $_SESSION, 'search_attempt' ) == "2" && $num_rows != 0)
		echo "<p align='center'>".red( "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;


//    if ($num_this_page > 0)
//		echo "<hr>";

		
		/* show the profile list display */

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

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

// this code works
//		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%'>";
		
		echo show_introduction( $data[$i]['id'], convert_to_html( $data[$i]['short_intro'] ), "search", $start_pos );
		
		echo "</td>";


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

		if (! low_res_screen())
		{
			echo "<td width='10%'>".black( name_case( $data[$i]['city'] ) )."</td>";
	
			echo "<td width='10%'>".black( $data[$i]['country'] )."</td>";
		}
		else
		{
			echo "<td width='10%'>".black( name_case( $data[$i]['city'] )."<br><br>".name_case( $data[$i]['country'] ) )."</td>";
		}	
		
		echo "</tr></table><hr>";


		if (! low_res_screen() && (($i-$start_pos) % 4 == 3))
		{
            echo "<br><br><br><br><table width='100%'><tr><td width='100%' align='center'>";
            
            echo show_ads_small_banner();            
//            echo show_ads( $cxn );
        
            echo "</td></tr></table><br><br><br><br><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. We suggest that you try a wider search including removing the country restriction." )."</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 "<br><br><br><br>";

		echo black( "Profiles ".$start." to ".$end."<br><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 "&nbsp;&nbsp;&nbsp;&nbsp;";

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

		echo "</p>";
	}

	echo "<br>";
	
	if ($num_rows > 0 && $num_rows < 20)
	{
		echo "<p align='center'>".black( "Your search returned a small number of profiles. We suggest that you try a wider search including removing the country restriction." )."</p><br>";
	}
	
	
	echo "<p align='center'>";


	echo red( "To join the site click on " )."<a class='redlink2' href='".url_encode( "edit_profile.php", "newprofile", "true" )."'>Join the Site</a></p>";


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

	echo "<br>";


		// don't show ads at the bottom of the search screen.
		// unless the page has limited results on it, the ads are not visible at the bottom of the page and reduce the adsense stats
		// also, it distracts visitors from joining.
		
//	if ($num_rows < 5) 
//	{


		if (! low_res_screen())
		{
		
			echo "<br><br><br><br>";
			
			show_ads( $cxn );		
		}
		else
		{
			echo "<br><br><br><br>";
	
//			show_ads_narrow_banner();			
			
			show_ads_large_square();
		}
//	}
	
	echo "<br><br><br><br><br><br><br>";
	
	echo "</body></html>";


		/* widen the search parameters and re-run the search */
		
		// Procedure is
		//
		//  1. if a city was specified, expand out to the whole country
		//  2. if a country was specified (including from step 1), and the profiles for the country are < 200, expand out to region 
		

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

		$_SESSION['sstate'] = "";
		
		$city = $_SESSION['scity'];
		
		if ($city != "")
		{
		    $query = "SELECT country FROM city WHERE display_name = '".$city."'";

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

        	if (query_num_rows($result) > 0)
    		{
    			$data = get_row( $result );
    			
		        $_SESSION['scountry'] = $data['country'];
    		}
    		
		    $_SESSION['scity'] = "";
		}
		
		
		$country = $_SESSION['scountry'];		

		
			/* eliminate country restriction if less than 200 profiles */

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

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

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

			if ($data['num'] < 200)
			{
				$_SESSION['scountry'] = "";


                    // widen the search to the same region that the user selected
                    
        		if ($country != "")
        		{
        		    $query = "SELECT region FROM country WHERE country.display_name = '".$country."'";
        
            		$result = run_query( $query, $cxn_common );
        
                	if (query_num_rows($result) > 0)
            		{
            			$data = get_row( $result );
            			
        		        $_SESSION['sregion'] = $data['region'];
            		}
        		}
    
			}    
        }		

			/* 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['smin_age'] = $min_age;
			$_SESSION['smax_age'] = $max_age;
		}

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

		exit();
	}



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

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

		$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 -= 1000;

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

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

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


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

        $age_difference = abs( $age1 - $age2 );

		$score -= $age_difference * 10;
        


			/* +20 points for similar 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 += 100;

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

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

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

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

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

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

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

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


			/* 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['religion'] == $data2['religion'])
			$score += 10;

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

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

//		$score -= 2 * ((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);
	}
	
	
	function show_introduction( $member_id, $text, $returnpoint, $startpos )
	{
		if ($startpos == "")
			$startpos = "0";		// if missing default to start of list

		$url = url_encode( "display_profile.php", "showid", $member_id, "returnpoint", $returnpoint, "startpos", $startpos );

		return ("<a href='".$url."' style='text-decoration: none;'><span class='gblack'>".$text."</span></a>");
	}
	
?>