<?php

	include "library.php";

	$cxn = start_code( true );

	$member_id = val( $_GET, "memberid" );

	$ip_address = val( $_GET, "ipaddress" );


		/* this code records the highest simultaneous visitors/members logged on  */
/*
	$visitors = get_first_row( "SELECT count(*) as num FROM online_status WHERE member_id = -1", $cxn );
	$members = get_first_row( "SELECT count(*) as num FROM online_status WHERE member_id <> -1", $cxn );
		
	$peak_visitors = get_first_row( "SELECT hits FROM sys_data WHERE param = 'peak_visitors'", $cxn );
	$peak_members = get_first_row( "SELECT hits FROM sys_data WHERE param = 'peak_members'", $cxn );

	if ($visitors['num'] > $peak_visitors['hits'])
		run_query( "UPDATE sys_data SET hits = ".$visitors['num']." WHERE param = 'peak_visitors'", $cxn );

	if ($members['num'] > $peak_members['hits'])
		run_query( "UPDATE sys_data SET hits = ".$members['num']." WHERE param = 'peak_members'", $cxn );
*/


		/* clear out members not logged in */

	$prev_time = date("Y-m-d H:i:s", time() - 15);

	$query = "DELETE FROM online_status WHERE refresh_stamp < '".$prev_time."'";

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


		/* clear out old conversations */

	$query = "DELETE FROM active_chats WHERE initiator_id NOT IN (SELECT member_id FROM online_status) OR responder_id NOT IN (SELECT member_id FROM online_status)";

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


		/* clear out old chat text */

	$query = "DELETE FROM chat_text WHERE typed_by NOT IN (SELECT member_id FROM online_status)";

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


		/* refresh our stamp */

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


	if (! query_has_rows( "SELECT id FROM online_status WHERE member_id = ".$member_id." AND ip_address = '".$ip_address."'", $cxn ))
	{
		$query = "INSERT INTO online_status ( member_id, ip_address, refresh_stamp ) VALUES ( ".$member_id.", '".$ip_address."', '".$curr_time."')";

		$result = run_query( $query, $cxn );
	}
	else
	{
		$query = "UPDATE online_status SET refresh_stamp = '".$curr_time."' WHERE member_id = ".$member_id." AND ip_address = '".$ip_address."'";

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

		/* look for a new chat request */

		/* TODO: handle multiple chat requests here */

	if (query_has_rows( "SELECT id FROM active_chats WHERE responder_id = ".$member_id." AND notified = 'no'", $cxn ))
	{
			/* get the asking member id */

		$query = "SELECT id, initiator_id FROM active_chats WHERE responder_id = ".$member_id." AND notified = 'no'";

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

		$data = get_row( $result );

			/* set as member notified */

		$query = "UPDATE active_chats SET notified = 'yes' WHERE responder_id = ".$member_id;

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

		echo "x".$data['initiator_id']."&conversationid=".$data['id'];
	}
	else
		echo "ok";	/* don't change this it's used to identify that we're not sending through a chat request id */


?>
