<?php

	include "library.php";

	$cxn = start_code();

	$cxn_common = db_common_login();


			/* get variables */

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

    if ($nextpage == "")
        $nextpage = "index.php";
        

			/* start page  */
			
//	page_header( "", $cxn, $cxn_common, "" );


			/* search for the user and password */

	$username = prep_for_sql( val( $_POST, 'username' ) );
	$password = prep_for_sql( val( $_POST, 'password' ) );

	crash_if_missing( $nextpage, "nextpage not set in accept_login", $cxn );

        $login = true;

	if ($username == "")
	{
		page_header( "", $cxn, $cxn_common, "" );
		echo black( "The username entered is blank<br><br>" );
                $login = false;
	}
	else
	if ($password == "")
	{
		page_header( "", $cxn, $cxn_common, "" );
		echo black( "The password entered is blank<br><br>" );
                $login = false;
	}

        if ($login)
	{
		$query = "SELECT * FROM user WHERE username = '".$username."'";

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

		if (query_num_rows($result) == 0)
		{
			page_header( "", $cxn, $cxn_common, "" );

			echo black( "There is no user with this username defined in the system<br><br>" );

			echo show_home_link();
			
			exit();			
		}
		else
		{
			$data = get_row( $result );
			
			if ((strtoupper( $password ) != strtoupper( $data['password'] )))
			{
				page_header( "", $cxn, $cxn_common, "" );

				echo black( "Password Incorrect<br><br><br>" );

				echo show_home_link();
				
				exit();
			}
			else
			{
				$_SESSION['userid'] = $data['id'];
			
				header( "Location: ".$nextpage );
			}			
			
			
//					if ($data['login_attempts'] >= 10)
//					{
//						echo black( "Your account has been locked.<br><br>" );
//						echo black( "Please contact site support on" );
//						echo black( " <a ref='mailto:enquiries@academicdating.net'>enquiries@academicdating.net</a><br><br>" );
//
//						$query = "UPDATE profile SET locked = 'yes' WHERE id = ".$data['id'];
//						$result = run_query( $query, $cxn );
//					}
//					else
//					{
//						$attempts = $data['login_attempts'] + 1;
//
//						$query = "UPDATE profile SET login_attempts = ".$attempts." WHERE id = ".$data['id'];
//						$result = run_query( $query, $cxn );
//					}
//			}
//			else
//			{

//				$_SESSION['userid'] = $data['id'];
				
//					$query = "UPDATE profile SET last_login = '".date( "Y-m-d H:i:s" )."' WHERE id = ".$data['id'];
//					$result = run_query( $query, $cxn );

//					$query = "UPDATE profile SET login_attempts = 0 WHERE id = ".$data['id'];
//					$result = run_query( $query, $cxn );

//					$num_logins = $data['number_of_logins'] + 1;

//					$query = "UPDATE profile SET number_of_logins = ".$num_logins." WHERE id = ".$data['id'];
//					$result = run_query( $query, $cxn );

//				header( "Location: ".$nextpage );
//			}
		
		}
	}

	echo show_home_link();
?>