<?php

	include "library.php";

	$cxn = start_code( true );

	
			/* get variables */

	$message_id = val( $_GET, "messageid" );

	page_header( "", $cxn );

	crash_if_missing( $message_id, "message id missing in delivery_failed", $cxn );

	$sent = date("Y-m-d H:i:s");


		/* get receiver handle */

	$query = "SELECT id, handle FROM profile WHERE id IN (SELECT receiver_id FROM message WHERE id = ".$message_id." )";

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

	$data = get_row( $result );

	$receiver_id = $data['id'];
	$receiver_handle = $data['handle'];


		/* get sender id */

	$query = "SELECT sender_id, profile.handle as sender_handle FROM message LEFT JOIN profile ON message.sender_id = profile.id WHERE message.id = ".$message_id;

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

	$data = get_row( $result );

	$sender_id = $data['sender_id'];
	$sender_handle = $data['sender_handle'];


		/* send message */

	$subject = "Mail delivery failed";

	$text_body = "Your message to Academic Dating member ".$receiver_handle." could not be delivered.\n\n";
	$text_body .= "This is most likely due to an invalid email address.\n\n";
	$text_body .= "We are sorry for the inconvenience";

	$html_body = "Your message to Academic Dating member <b>".$receiver_handle."</b> could not be delivered.<br><br>";
	$html_body .= "This is most likely due to an invalid email address.<br><br>";
	$html_body .= "We are sorry for the inconvenience";

	send_external( $sender_id, $subject, $text_body, $html_body, $cxn );


		/* lock receiver's profile */

	$query = "UPDATE profile SET locked = 'yes' WHERE id = ".$receiver_id;
	$result = run_query( $query, $cxn );

	$query = "INSERT INTO account_activity (member_id, event, event_datetime) VALUES (".$receiver_id.", 'profile locked due to returned mail', '".date("Y-m-d H:i:s")."')";
	$result = run_query( $query, $cxn );


		/* log this email */

	$query = "INSERT INTO sys_message (sent_to_id, type, sent) VALUES (".$sender_id.", 'returned mail message', '".$sent."')";

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

	echo "Locked ".$receiver_handle."<br><br>";

	echo "Email sent to ".$sender_handle."<br><br>";

	echo "Finished";
?>


