<?php

	include "library.php";

	$cxn = start_code();

	$cxn_common = db_common_login();


	
			/* get variables */

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

	$send_to_id = val( $_GET, "sendtoid" );

	$send_type = val( $_GET, "sendtype" );

	$returnpoint = val( $_SESSION, "returnpoint" );

	$startpos = val( $_SESSION, "startpos" );

	
		/* if the user is not logged in log them in then back to here */

	if ($id == "")
	{
		$_SESSION['nextpage'] = url_encode( "send_message.php", "sendtoid", $send_to_id, "sendtype", $send_type );

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

		exit();
	}

		/* check id's */


	crash_if_missing( $send_to_id, "Send to id missing in send_message", $cxn );

	crash_if_missing( $send_type, "Send type missing in send_message", $cxn );

	crash_if_missing( $returnpoint, "return point missing in send message", $cxn );


	$ip_address = get_ip_address();	


		/* check blocked list */

	$query = "SELECT * FROM blocked_list WHERE (blocker_id = ".$id." AND blockee_id = ".$send_to_id." ) OR ( blocker_id = ".$send_to_id." AND blockee_id = ".$id." )";

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

	if (query_num_rows($result) > 0)
	{
		page_header( "", $cxn, $cxn_common );
		echo black( "Communication with this member is currently blocked" );
		exit();
	}


		/* check visibilty */

	$query = "SELECT *, year(date_of_birth) as dob_year, dayofyear(date_of_birth) as dob_dayofyear FROM profile WHERE id = ".$id;
	$result = run_query( $query, $cxn );

	$data = get_row( $result );

    $membership_type = $data['membership_type'];

	$age_from = calc_person_age( $data['dob_dayofyear'], $data['dob_year'] );
	

	$query2 = "SELECT *, year(date_of_birth) as dob_year, dayofyear(date_of_birth) as dob_dayofyear FROM profile WHERE id = ".$send_to_id;
	$result2 = run_query( $query2, $cxn );

	$data_send_to = get_row( $result2 );

	$age_to = calc_person_age( $data_send_to['dob_dayofyear'], $data_send_to['dob_year'] );



//	if ($data['visibility'] == "hidden" && (! is_system_user( $id, $cxn )))

	if ($data['visibility'] == "hidden")	
	{
		page_header( "", $cxn, $cxn_common );
		echo black( "<br>You cannot communicate with other members while your profile status is 'hidden'<br><br><br>" );
		echo show_home_link();
		exit();
	}


	if ($data_send_to['visibility'] == "hidden")	
	{
		page_header( "", $cxn, $cxn_common );
		echo black( "<br>You cannot communicate with another member who's profile status is 'hidden'<br><br><br>" );
		echo show_home_link();
		exit();
	}

		/* check for a valid email address */


	if ($data['email_address_valid'] == "no")
	{
		page_header( "", $cxn, $cxn_common );
		echo black( "<br>You cannot send messages to other members until your email address" );
		echo black( " has been verified.<br><br>" );
		echo black( " You must click on the link in the verification email that has arrived in your email inbox. Also check your junk or spam folder.<br><br>" );
		echo black( " Your email address is listed as " );
		echo "<span class='gemail'><b>".$data['email']."</span></b><br><br>";
		echo black( " If this is not your correct email address please click on 'Edit Your Profile' on the home page and update your profile.<br><br>" );
		echo black( " Please check your inbox or " ).show_link( "click here", "send_verification_email.php", "sendid", $id, "code", $data['email_verification_code'] );
		echo black( " to send the verification email again.<br><br><br>" );
		echo show_home_link();
		exit();
	}


	if ($data_send_to['email_address_valid'] == "no")
	{
		page_header( "", $cxn, $cxn_common );
		echo black( "<br>This member has not verified their email address. You cannot send messages to them at this time.<br><br><br>" );
		echo show_home_link();
		exit();
	}


	if ($data['returned_mail'] == "yes")
	{
		page_header( "", $cxn, $cxn_common );
		echo black( "<br>We have received a bounced email indicating that the email address that you have on file in your profile is not valid.<br><br>" );
		echo black( " Please edit your profile and enter a valid email address that you check regularly.<br><br>" );
		echo black( " Your email address is listed as " );
		echo "<span class='gemail'><b>".$data['email']."</span></b><br><br><br>";
		echo show_home_link();
		exit();
	}


	if ($data_send_to['returned_mail'] == "yes")
	{
		page_header( "", $cxn, $cxn_common );
		echo black( "<br>We have received a bounced email indicating that the email address of the member that you are trying to send this message to is invalid.<br><br>" );
		echo black( " Please try to contact them through some other method.<br><br><br>" );
		echo show_home_link();
		exit();
	}


        // check for too many messages from one ip address, hopefully a single person and not some shared system
        
        // due to timezone differences, do the check as messsages sent in the last 6 hours
        
	$datetime_now = date_create( date( "Y-m-d H:i:s" ) );
	$now_minus_6_hours = clone $datetime_now;

	date_sub( $now_minus_6_hours, date_interval_create_from_date_string( '6 hours' ));
	$now_minus_6_hours_str = $now_minus_6_hours->format( "Y-m-d H:i:s" );		

    $query = "SELECT count(*) as num FROM message WHERE ip_address = '".$ip_address."' AND sent > '".$now_minus_6_hours_str."'";
    
	$result = run_query( $query, $cxn );

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


        $query2 = "SELECT * FROM profile WHERE id = ".$id;
    
        $result2 = run_query( $query2, $cxn );
    
        $data2 = get_row( $result2 );
    
        $membership_type = $data2['membership_type'];
        
        
            // places to update the send-message limit
            // this file below
            // 'charges' help
            // membership_status.php
            // send_membership_upgrade_reminder.php
        
            
//        if ($membership_type == "premium")
//            $limit = 50;
//        else

        $limit = 35;

		if ($data['num'] >= $limit)
		{
			page_header( "", $cxn, $cxn_common );

			echo black( "<br>To prevent overloading members with messages, there is a" );

			echo black( " limit of 35 messages a day that you can send through the site.<br><br>" );

			echo black( " You have reached the limit for today. Please try again tomorrow.<br><br>" );

			echo black( "<br>" );
			
		    echo show_home_link();

			exit();
		}
	}



		/* avoid repeated contact requests to the same member */

	if ($send_type == "contact_request" && (! is_system_user( $id, $cxn )))
	{
		if (query_has_rows( "SELECT id FROM message WHERE type = 'contact_request' AND sender_id = ".$id." AND receiver_id = ".$send_to_id, $cxn ))
		{
			echo black( "You have already sent a Contact Request to this member.<br><br>" );

			echo show_home_link();

			exit();
		}
	}

		/* work out credits used if any */

	$_SESSION['credits_used'] = 0;


		/* check if an email has already been exchanged */

	$query = "SELECT id FROM message WHERE type = 'email' AND ((sender_id = ".$id." AND receiver_id = ".$send_to_id.") OR (sender_id = ".$send_to_id." AND receiver_id = ".$id."))";

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

	if (query_num_rows($result) > 0)
		$channel_open = true;
	else
		$channel_open = false;
		


	$ip_country = get_ip_country( $cxn_common );

	$ip_country = str_replace( "'", "", $ip_country );




		// don't allow sending messages until a photo has been posted to ensure that member is legitimate

	$query = "SELECT * FROM photos WHERE member_id = ".$id;

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

	if (query_num_rows($result) == 0)
	{
			// allow message if replying to a message
			
		$query = "SELECT id FROM message WHERE type = 'email' AND ((sender_id = ".$id." AND receiver_id = ".$send_to_id.") OR (sender_id = ".$send_to_id." AND receiver_id = ".$id."))";

		$result = run_query( $query, $cxn );
		
		if (query_num_rows($result) == 0)
		{
			page_header( "", $cxn, $cxn_common );
			
			echo black( "<br>You cannot send messages to other members until you have posted a photo to your profile.<br><br>" );
			echo black( "We apologise for the inconvenience.<br><br>" );
			echo black( "This is a security measure to ensure that all our members are legitimate.<br><br>" );
			echo black( "If you would prefer not to post a photo you can remain a member and wait for other members to contact you.<br><br>" );			
			echo black( "Please " );
			
			echo show_link( "Upload a Photo", "manage_photos.php" );
	
			echo black( "<br><br><br>" );
			
			echo show_home_link();
			exit();
		}
	}
		
		
	if ($send_type == "email")
	{
		$query = "SELECT id FROM message WHERE (sender_id = ".$send_to_id." AND receiver_id = ".$id.")";

		$result = run_query( $query, $cxn );
		
		if (query_num_rows($result) == 0)
		{
			page_header( "", $cxn, $cxn_common );
			
			echo black( "<br>You cannot send an email to a member until you have sent them a Contact Request and they have replied.<br><br>" );

			echo black( "<br><br><br>" );
			
			echo show_home_link();
			exit();
		}
	}

		

	// LATEST CHARGING CODE 25/04/17, WORKS FINE

		// as at 27/08/17 paypal is not available in these countries

//	if ((! $channel_open) && $membership_type == 'free' && ($ip_country != "Afghanistan" &&

//	if ($membership_type == 'free' && ($ip_country != "Afghanistan" &&
//						$ip_country != "Bangladesh" &&
//						$ip_country != "Central African Republic" &&
//						$ip_country != "Equatorial Guinea" &&
//						$ip_country != "Ghana" &&
//						$ip_country != "Haiti" &&
//						$ip_country != "Iran, Islamic Republic of" &&
//						$ip_country != "Iraq" &&
//						$ip_country != "Lebanon" &&
//						$ip_country != "Liberia" &&
//						$ip_country != "Libya" &&
//						$ip_country != "Myanmar" &&
//						$ip_country != "Pakistan" &&
//						$ip_country != "South Sudan" &&						
//						$ip_country != "Sudan" &&					
//						$ip_country != "Syrian Arab Republic" &&
//						$ip_country != "Timor-Leste" &&
//						$ip_country != "Uzbekistan"))
//	{
//		echo black( "<br>You must be a Paid member of the site to send messages to other members.<br><br>" );
//		echo black( "Paid membership costs USD $10 and lasts for 12 months.<br><br>" );
//		echo black( "Paid members have full use of the site and can send messages to other members.<br><br>" );
//		echo black( "Please click on the link below to upgrade to Paid membership.<br><br><br>" );			
//		
//		echo show_link( "Upgrade to Paid membership", "membership_status.php" );
//		
//		exit();
//		
//	}


	/* basic membership */

	if ($send_type == "contact_request")
	{
		page_header( "Send Contact Request", $cxn, $cxn_common );

		echo black( "Are you sure that you want to send an email contact request to this member?<br><br><br>" );

			/* yes */

		echo "&nbsp;&nbsp;";

		show_green_button( "Yes", 70, "send_message_go.php", "send", "yes", "sendtype", "contact_request", "sendtoid", $send_to_id );

			/* no */

		echo "&nbsp;&nbsp;";

		show_green_button( "No", 70, "send_message_go.php", "send", "no", "sendtype", "contact_request", "sendtoid", $send_to_id );
		
	}
	else
	if ($send_type == "email")
	{
		page_header( "Send Email", $cxn, $cxn_common );
	
		form_start( "send_message_go.php", "send", "yes", "sendtype", "email", "sendtoid", $send_to_id );

		write_yellow_input_boxes();

		if (low_res_screen())
		{
			form_text( "Subject", "subject", 36, "", "true" );

			form_textarea( "Message", "message", 18, 40, "" );

		}
		else
		{
			form_text( "Subject", "subject", 110, "", "true" );

			form_textarea( "Message", "message", 20, 110, "" );
		}

                // prevent sending of bulk emails to members through calling send_message_go.php programmatically
                
        echo "<input type='hidden' name='send_email_system_password' value='1234abcd%^%'>";
        

		echo "<tr><td></td><td align='center'><br><br>";
		
		
		show_green_button_submit( "Send", 75 );
		
		echo "</td></tr>";

		form_end();

		
			// not enough content on this page to justify ads, as per adsense policies
			
//			if (! low_res_screen())
//			{
//				echo "<br><br><br><br>";
//
//				show_double_ads( $cxn );
//			}
//			else
//			{
//				echo "<br><br><br><br><br>";			
//				
//				show_ads_large_square();				
//
////				show_ads_narrow_banner();
//			}

	}
	else
		crash( "Internal Error: invalid send type in send_message", $cxn );

?>