<?php

	include "library.php";

	$cxn = start_code();

	$cxn_common = db_common_login();

	
			/* get variables */

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

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



		/* check parameters */

	crash_if_missing( $newprofile, "newprofile missing in save profile, handle = ".val( $_POST, 'handle' ), $cxn );

	if ($newprofile != "true")
		crash_if_missing( $id, "id missing in save profile", $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");
	$date_entered = date("Y-m-d H:i:s");
	$effective_date = date("Y-m-d H:i:s");
	$todays_date = date("Y-m-d H:i:s");


	$ok = validate_form( $id, $newprofile, "chat_city_profile", $screen_data, $screen_data_errors, $validation_errors, $cxn, $cxn_common );		


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

	page_header( "", $cxn, $cxn_common );


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


    if ($screen_data['sex_and_seeking'] == "Man")
    {
    	$screen_data['sex'] = "Male";
    }
    else
    if ($screen_data['sex_and_seeking'] == "Woman")
    {
    	$screen_data['sex'] = "Female";
    }


		/* save the record to the database */

	if ($newprofile == "true")
	{
		$prev_membership_type = "";

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

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

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

		$ip_country = get_ip_country( $cxn_common );

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

		if ($screen_data['email'] == "mark.mcilroy@outlook.com")
			$system_user = "yes";
		else
			$system_user = "no";
		
			
		$query = "SELECT id FROM profile WHERE first_name = '".val( $screen_data, "first_name" )."' AND surname = '".val( $screen_data, "surname" )."'";
		
		$result = run_query( $query, $cxn );
		
		$error = "false";


			// took this out. there are a few problems with checking for multiple profiles
			//	1. people forget their password so they just create a new profile
			//	2. two people may have the same name
			//	3. members can get around it by putting in different details to the new profile
			//		
			// check for multiple profiles. Allow 3 profiles in case there are two members with the same name
			
//		if (query_num_rows( $result, $cxn ) >= 3)
//		{
//			$error = "true";
//		
//			echo red( "<br>There is already a profile with this name.<br><br>" );
//			echo red( "Please do not create multiple profiles on this site!<br><br>" );
//			echo red( "We manually monitor all activity on the site and if we find a member creating multiple profiles we will need to take action.<br><br>" );
//			echo red( "Thank you for your co-operation.<br><br><br>" );
//			echo red( "Site adminstration.<br><br><br>" );
//		}
					
			// still save the profile in case there are two member's with the same name
			
			
		$screen_data['date_created'] = $date_created;
		$screen_data['date_modified'] = $date_modified;
		$screen_data['ip_country'] = $ip_country;
		$screen_data['ip_country_created'] = $ip_country;		
		$screen_data['system_user'] = $system_user;
		$screen_data['source'] = $source;
		$screen_data['last_login'] = $todays_date;
		$screen_data['locked'] = "no";
		$screen_data['deleted'] = "no";
		$screen_data['returned_mail'] = "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;

		$screen_data['short_intro'] = str_insert_spaces( $screen_data['short_intro'] );

		$handle = $screen_data['handle'];
		$email = $screen_data['email']; 
		$country = $screen_data['country']; 
		
		
		save_form_data_to_database( $id, $newprofile, "chat_city_profile", "profile", $screen_data, $cxn, $cxn_common );

		
	
			/* create profile  */

		
		$query = "SELECT id FROM profile WHERE handle = '".$handle."'";

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

		$data = get_row( $result );



			/* update handle history */

		$query = "SELECT id FROM profile WHERE handle = '".$handle."'";

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

		$data = get_row( $result );

		$new_id = $data['id'];


			/* save the handle history */

		$query = "INSERT INTO handle_history (member_id, handle, date_assigned) VALUES (".$new_id.", '".$handle."', '".$date_assigned."' )";

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


			/* save the email history */

		$query = "INSERT INTO email_history (member_id, email, date_entered) VALUES (".$new_id.", '".$email."', '".$date_entered."' )";

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



//			/* log any current user out to avoid confusion about who's account you're in */
//
//		$_SESSION['id'] = "";



		$query = "INSERT INTO account_activity2 (member_id, event, event_datetime) VALUES (".$new_id.", 'profile created', '".date("Y-m-d H:i:s")."')";
		$result = run_query( $query, $cxn );
		
		
			/* log the source of the new member */

//		log_conversion( $cxn, $cxn_common );

		
			// send this last in case it crashes and prevents storing handle history and other records
			
		send_verification_email( $new_id, $email_verification_code, $cxn, $cxn_common );
		

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

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


			/* update handle history  */

		$query = "SELECT handle, email, email_address_valid, returned_mail, membership_type FROM profile WHERE id = ".$id;

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

		$data = get_row( $result );

		$prev_email = $data['email'];
		$email_address_valid = $data['email_address_valid'];

		$screen_data['short_intro'] = str_insert_spaces( $screen_data['short_intro'] );

		$handle = $screen_data['handle'];
		
		if ($data['handle'] != $handle)
		{
			$query = "INSERT INTO handle_history (member_id, handle, date_assigned) VALUES (".$id.", '".$handle."', '".$date_assigned."')";

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


		$email = $screen_data['email'];

		if ($prev_email != $email)
		{
			$screen_data['email_address_valid'] = "no";
		    $screen_data['returned_mail'] = "no";					


				/* save the email history */

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

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


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

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



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

		save_form_data_to_database( $id, $newprofile, "chat_city_profile", "profile", $screen_data, $cxn, $cxn_common );


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


		$_SESSION['show_language_translation'] = $screen_data['show_language_translation'];


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

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

			$data = get_row( $result );

			$email_verification_code = $data['email_verification_code'];
		
			echo black( "<br>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 before you can send messages to other members<br><br>" );

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

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

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


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


				// $error means that duplicate profiles were detected. Don't display the screen messages
				
//		if ($error == "false")
//		{
			echo "<br>";
	
			echo "Profile saved successfully.<br><br>";

			echo black( "<br>You will shortly receive a verification email from Chat City. 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 "<br>";
			
			echo "We recommend that you ";

                // convert back to http
                
        	echo "<a class='glink' href='".url_encode( "http://chatcity1.net/manage_photos.php" )."'>Upload a Photo</a>";		

    		echo "<br><br>";		    
		    
//		}
			


			// conversions tracking code for adwords account admin@chatcity1.net
		

            // <!-- Google Code for Chat City new member Conversion Page -->
            
        echo "<script type='text/javascript'> ";
        echo "/* <![CDATA[ */ ";
        echo "var google_conversion_id = 832189732;  ";
        echo "var google_conversion_language = 'en';  ";
        echo "var google_conversion_format = '3';  ";
        echo "var google_conversion_color = 'ffffff';  ";
        echo "var google_conversion_label = '_lirCL_k3XUQpOrojAM';  ";
        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/832189732/?label=_lirCL_k3XUQpOrojAM&amp;guid=ON&amp;script=0'/>  ";
        echo "</div>  ";
        echo "</noscript>  ";



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

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

//            echo "Profile saved successfully.<br><br>";
        }


	echo "<a class='glink' href='".url_encode( "index.php", "internaljump", "true" )."'>Home Page</a>";		


		/* 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);
	}

?>