<?php

	include "library.php";

	$cxn = start_code();


			/* get variables */

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

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

		
//	page_header( "", $cxn );


		/* check parameters */

	crash_if_missing( $newaccount, "newaccount missing in save account", $cxn );

	if ($newaccount != "true")
		crash_if_missing( $id, "id missing in save account", $cxn );

	
			/* define timestamps */

//	$date_created = date("Y-m-d H:i:s");
//	$date_modified = date("Y-m-d H:i:s");
//	$date_assigned = date("Y-m-d H:i:s");
//	$todays_date = date("Y-m-d H:i:s");

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


	$ok = validate_form( $id, $newaccount, "abfs_account", $screen_data, $screen_data_errors, $validation_errors, $cxn );		


	if ($validation_errors != "")
	{	
				/* must happen before print output */
		jump_to_page( "edit_account.php", "newaccount", $newaccount );
			
		exit();
	}


	page_header( "", $cxn );



	$email_verification_code = substr(md5(time()), 0, 8);



		/* save the record to the database */

	if ($newaccount == "true")
	{

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

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

		if ($source == "")
			$source = ".blank";

		$ip_country = get_ip_country( $cxn );

		$ip_country = str_replace( "'", "''", $ip_country );
		                                           
		if ($screen_data['email_address'] == "mark.mcilroy@outlook.com")
			$system_user = "yes";
		else
			$system_user = "no";
		
					
			// still save the account in case there are two member's with the same name
			
			
		$screen_data['date_created'] = $date_today;
		$screen_data['date_modified'] = $date_today;
		$screen_data['ip_country'] = $ip_country;
		$screen_data['system_user'] = $system_user;
		$screen_data['source'] = $source;
		$screen_data['last_login'] = $date_today;
		$screen_data['locked'] = "no";
		$screen_data['deleted'] = "no";
		$screen_data['login_attempts'] = "0";
		$screen_data['number_of_logins'] = "0";		
		$screen_data['email_address_valid'] = "no";
		$screen_data['new_photo_number'] = "0";
		$screen_data['email_verification_code'] = $email_verification_code;

		$username = $screen_data['username'];
		$email_address = $screen_data['email_address']; 
		$country = $screen_data['country']; 
		
		
		save_form_data_to_database( $id, $newaccount, "abfs_account", "account", $screen_data, $cxn );
		
		
	
			/* create account  */

		
		$query = "SELECT id FROM account WHERE username = '".$username."'";

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

		$data = get_row( $result );

		
		send_verification_email( $data['id'], $email_verification_code, $cxn );


			/* save the username  history */

		$query = "INSERT INTO username_history (account_id, username, date_assigned) VALUES (".$data['id'].", '".$username."', '".$date_today."' )";

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


			/* save the email history */

		$query = "INSERT INTO email_history (account_id, email, date_entered) VALUES (".$data['id'].", '".$email_address."', '".$date_today."' )";

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


			/* log any current user out to avoid confusion about who's account you're in */

		$_SESSION['id'] = "";


		send_email( "Australian Businesses for Sale Platform", "noreply@aubusinessesforsale.com", "mark.mcilroy@outlook.com", "Australian Businesses for Sale Platform", "noreply@aubusinessesforsale.com", "Australian Businesses for Sale Platform, new account", "", "", $cxn, "live" );


		$query = "INSERT INTO account_activity (account_id, event, event_datetime) VALUES (".$data['id'].", 'account created', '".date("Y-m-d H:i:s")."')";
		$result = run_query( $query, $cxn );


//		echo black( "Successfully saved<br><br>" );

	}
	else
	if ($newaccount == "false")
	{
		$new_id = $id;


			/* update handle history  */

		$query = "SELECT username, email_address, email_address_verified FROM account WHERE id = ".$id;

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

		$data = get_row( $result );

		$prev_email_address = $data['email_address'];
		
		$email_address_verified = $data['email_address_verified'];

		$username = $screen_data['username'];
		
		if ($data['username'] != $username)
		{
			$query = "INSERT INTO username_history (account_id, username, date_assigned) VALUES (".$id.", '".$username."', '".$date_today."')";

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


		$email_address = $screen_data['email_address'];

		if ($prev_email_address != $email_address)
		{
			$screen_data['email_address_valid'] = "no";

				/* save the email history */

			$query = "INSERT INTO email_history (account_id, email, date_entered) VALUES (".$id.", '".$email."', '".$date_today."' )";

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



		$screen_data['date_modified'] = $date_today;
		$screen_data['last_login'] = $date_today;



			// note: don't update the email verification code or there will be mismatches when the member edits their account and saves it

		save_form_data_to_database( $id, $newaccount, "abfs_account", "account", $screen_data, $cxn );



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

//		$_SESSION['color_scheme'] = $screen_data['color_scheme'];


			/* change of email adress */
			
		if ($prev_email_address != $email_address)
		{
			$query = "SELECT email_verification_code FROM account WHERE id = ".$id;

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

			$data = get_row( $result );

			$email_verification_code = $data['email_verification_code'];
		
			echo black( "You have changed your email address.<br><br>A verification email should arrive in your email inbox shortly.<br><br> You will need to click on the link in the verification email to reactivate your membership.<br><br>" );

			send_verification_email( $id, $email_verification_code, $cxn );
		}

		echo black( "Successfully saved<br><br>" );

	}
	else
		crash( "Internal Error: invalid newaccount flag in save_account", $cxn );


		
	if ($newaccount == "true")
        {
//            $_SESSION['id'] = $new_id;


		echo "<br>";

		echo "Account saved successfully.<br><br>";
           
		echo black( "You will shortly receive a verification email from the Australian Businesses for Sale Platform. Please check your email inbox and spam folders. You will need to click on the link in the email to activate your account.<br><br>" );

//		echo show_link( "Upload a Photo", "manage_photos.php" );

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


        echo "<!-- Google Code for Philippines Business for Sale, new account Conversion Page -->";
        
        echo "<script type='text/javascript'>";
        echo "/* <![CDATA[ */";
        echo "var google_conversion_id = 835775666;";
        echo "var google_conversion_language = 'en';";
        echo "var google_conversion_format = '3';";
        echo "var google_conversion_color = 'ffffff';";
        echo "var google_conversion_label = 'gOj9CKifs3QQstnDjgM';";
        echo "var google_remarketing_only = false;";
        echo "/* ]]> */";
        echo "</script>";
        echo "<script type='text/javascript' src='//www.googleadservices.com/pagead/conversion.js'>";
        echo "</script>";
        echo "<noscript>";
        echo "<div style='display:inline;'>";
        echo "<img height='1' width='1' style='border-style:none;' alt=''src='//www.googleadservices.com/pagead/conversion/835775666/?label=gOj9CKifs3QQstnDjgM&amp;guid=ON&amp;script=0'/>";
        echo "</div>";
        echo "</noscript>";


            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";
            echo "<br>";

		// adsense ads are not permitted on control-flow, non-content pages
//            show_ads( $cxn, true, true );
        }
        else
        {
            echo "<br>";

//            echo "account saved successfully.<br><br>";

	    echo show_home_link();
        }

			/* check to see whether a new user has selected an existing handle */



		/* a handle can only contain alphanumeric characters */

	function check_handle_chars( $handle )
	{
		$ok = true;

		for ($i=0; $i < strlen( $handle ); $i++)
		{
			$ch = substr( $handle, $i, 1 );

			if (! (($ch >= "a" && $ch <="z") ||
					($ch >= "A" && $ch <= "Z") ||
					($ch >= "0" && $ch <= "9")))
				$ok = false;
		}

		return ($ok);
	}


		/* returns true if the text contains a phone number */

	function check_for_phone_number( $text )
	{
		$has_number = false;
		$points = 0;

		for ($i=0; $i < strlen( $text ); $i++)
		{
			$ch = substr( $text, $i, 1 );

			if ($ch >= "0" && $ch <="9")
				$points += 5;
			else
				$points--;

			if ($points < 0)
				$points = 0;

			if ($points >= 30)
				$has_number = true;
		}

		return ($has_number);
	}
	
?>