<?php
require_once ('includes/config.inc.php'); 
$page_title = 'Edit Profile';
include ('includes/headr.php');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> Edit Profile </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <link href="includes/main.css" rel="stylesheet" type="text/css">
  <link href="includes/panels.css" rel="stylesheet" type="text/css">
  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript" src="validation/jquery.validate.js"></script>
  <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
  <script type="text/javascript">
	$(document).ready(function(){
	$("#editprofile1").validate({
		rules: {		 
		up_avatar: {
         accept: "image/*",

		},
		},
		messages: {
			up_avatar: {	
				accept: "Not an image!",
			},
			},
	});
	$("#editprofile2").validate({
		rules: {		 
		email: {
		 required: true,
         email: true,
		},
		pass :"required",		
		},
		messages: {
			email: {
				required: "You didn't enter an email!",
				email: "Please enter a valid address!",
			},
			pass: "Please enter your password!",
			},
	});
	$("#editprofile3").validate({
		rules: {		 
		olpass: "required",
		newpass: "required",
		confnew: {
			required: true,
			equalTo: "#newpass",
		},
		},
		messages: {
			confnew: {
				required: "Please confirm your new password!",
				equalTo: "Passwords don't match!",
			},
			},
	});
	$("#editprofile4").validate({
		rules: {		 
		pass: "required",
		},
		messages: {
			pass:"Please enter your password to validate yourself!",
			},
	});
	$("#editprofile1").click(function(){
    //check whether browser fully supports all File API, to do filesize check with HTML5
    if (window.File && window.FileReader && window.FileList && window.Blob)
    {
        //get the file size and file type from file input field
        var fsize = $("#up_avatar")[0].files[0].size;
        
        if(fsize>102400) //do something if file size more than 100 KB (102400)
        {
            alert("Selected avatar file is too large.\nThe maximum allowed file size is 100KB.");
        }
    }else{
        alert("Please upgrade your browser, because your current browser lacks some new features we need!");
    }
	});
}); 
</script>
 </head>

 <body>
 <?php if (isset($success4)) echo '<p align="center">'.$success4.'</p>';
		//if (isset($bsuccess)) echo $bsuccess;
	?>
<?php 
require_once (MYSQL); 

if (isset($_SESSION['user_id'])) {
	
	//update session variables if changes were made NO
	/*if (isset($_POST['submitted1'])||isset($_POST['submitted2'])||isset($_POST['submitted3'])){
	$q = "SELECT * FROM user WHERE user_id='".$_SESSION['user_id']."'";
	$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
	// Register the values
	$_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC);
	//header("Location: edit_profile.php");
	}*/

	//text search? redirect!	
if (isset ($_GET['sitesearch'])){
	header('Location: home.php?sitesearch='.$_GET['sitesearch'].'');
}
 
 //escape the incoming data
 if (isset($_POST['submitted1'])){

    $bio = mysqli_real_escape_string($dbc, $_POST['bio']);

	if ($bio!=$_SESSION['bio']){ //update only if there's been a change
		$q = "UPDATE user SET bio='$bio' WHERE user_id ='". $_SESSION['user_id']."'";
		$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
		//we've only updated the database. We need to pull the new bio in the SESSION variable (see top):
		$q = "SELECT bio FROM user WHERE user_id='".$_SESSION['user_id']."'";
		$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
		$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
		$_SESSION['bio']= $row['bio'];
		$bsuccess="Bio changed successfully!";

	}

	//update avatar
	// Create a temporary file name:
	$temp = '../avatars/'.md5($_FILES['up_avatar']['name']);
	
	// Move the file over:
	$file_success = "";
	
	/* Fields are already checked with jquery
	Now check whether the file has been uploaded so that we can add the artwork to the database */
	if (move_uploaded_file($_FILES['up_avatar']['tmp_name'], $temp)) {
	
			$file_success = "Avatar was successfully uploaded to the server!";
			$flag = true;			
			$file_name = $_FILES['up_avatar']['name'];
			}
	else { // Couldn't move the file over.
			$file_success = "A problem occured when uploading the file. Please try again";
			$temp = $_FILES['up_avatar']['tmp_name'];
			$flag = false;
		}

	$upload_success = "";
	

		//If avatar is uploaded, add avatar to the database:
		if ($flag) {
		$ava_url = "../avatars/$file_name";
		$q = 'INSERT INTO avatar (user_id, file_name, ava_url) VALUES (?, ?, ?)'; //SOLVED add user_id
		$stmt = mysqli_prepare($dbc, $q);
		mysqli_stmt_bind_param($stmt, 'iss', $_SESSION['user_id'], $file_name, $ava_url);
		mysqli_stmt_execute($stmt);
		
		// Check the results...
		if (mysqli_stmt_affected_rows($stmt) == 1) {
		
			$upload_success = "Avatar was successfully submitted"; 
			$id = mysqli_stmt_insert_id($stmt); // Get the avatar ID.
			rename ($temp, "../avatars/$id");
			$newurl = "../avatars/$id";
			$q3="UPDATE avatar SET ava_url='$newurl' WHERE avatar_id='$id'";
			$r3 = mysqli_query ($dbc, $q3) or trigger_error("Query: $q3\n<br />MySQL Error: " . mysqli_error($dbc));
			//and update user's record
			$q = "UPDATE user, avatar SET user.avatar_id=avatar.avatar_id WHERE avatar.avatar_id='$id' AND user.user_id='".$_SESSION['user_id']."' AND avatar.user_id='".$_SESSION['user_id']."'";
			$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
			//we've only updated the database. We need to pull the new avatar_id in the SESSION variable:
			$q = "SELECT avatar_id FROM user WHERE user_id='".$_SESSION['user_id']."'";
			$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
			$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
			$_SESSION['avatar_id']= $row['avatar_id'];
			$successa = "Avatar was successfully changed!";
		}
			else { // Error!
			$successa = "Avatar could not be submitted due to a system error";
		}
		
		mysqli_stmt_close($stmt);
		
	}


 } //end submitted1

 if (isset($_POST['submitted2'])){

    $email = mysqli_real_escape_string($dbc, $_POST['email']);
	$pass = mysqli_real_escape_string($dbc, $_POST['pass']);
	

	if ($email !=NULL){ //update only if there's been a change
		
		$q1 = "SELECT user_id FROM user WHERE email='$email'";
		$r1 = mysqli_query ($dbc, $q1) or trigger_error("Query: $q1\n<br />MySQL Error: " . mysqli_error($dbc));
		$flag1 = mysqli_num_rows($r1);

		$email_match = ""; //error messages for registered emails 

		if ($flag1 == 0 ){ // No rows were retrieved, email is available

			//check if user has entered any/correct password to validate themselves
			if (SHA1($pass) == $_SESSION['pass']) {
				$q = "UPDATE user SET email='$email' WHERE user_id = '".$_SESSION['user_id']."'";
				$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
				//we've only updated the database. We need to pull the new email in the SESSION variable (see top):
				$q = "SELECT email FROM user WHERE user_id='".$_SESSION['user_id']."'";
				$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
				$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
				$_SESSION['email']= $row['email'];
				$successm="Email updated successfully!";
			}//end if
				else {
				$error1 = "You have to enter your own password correctly!";
				}
		}else $email_match = "That email address has already been registered.";
	}//end update
 }//end submitted2

 if (isset($_POST['submitted3'])){

	$olpass = mysqli_real_escape_string($dbc, $_POST['olpass']);
	$newpass = mysqli_real_escape_string($dbc, $_POST['newpass']);
	$confnew = mysqli_real_escape_string($dbc, $_POST['confnew']);

	if ($newpass !=NULL){ //update only if there's been a change

		//check if user has entered any/correct password and confirmation to validate themselves
		if (SHA1($olpass) == $_SESSION['pass']){ //#1 successful validation

			if ($newpass == $confnew) { //#2 successful confirmation of new password

				$q = "UPDATE user SET pass=SHA1('$newpass') WHERE user_id = '".$_SESSION['user_id']."'";
				$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
				//we've only updated the database. We need to pull the new password in the SESSION variable (see top):
				$q = "SELECT pass FROM user WHERE user_id='".$_SESSION['user_id']."'";
				$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
				$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
				$_SESSION['pass']= $row['pass'];
				$successp="Password changed successfully!";
			} //end if #2
			else {
				$errorp = "Passwords don't match!";
			}
		}//end if #1			
		else {
			$errorp = "Please enter your old password correctly!";
		}
	} //end update
 } //end submitted3

 if (isset($_POST['deactivated'])){//if user deactivates their account
	 

	$pass = mysqli_real_escape_string($dbc, $_POST['pass']);
		//check if user has entered any/correct password to validate themselves
		if (SHA1($pass) == $_SESSION['pass']) {
			$q = "INSERT INTO reports (byuser_id, type, item_id) VALUES ('".$_SESSION['user_id']."', '4', '".$_SESSION['user_id']."')";
			$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));			
			if (mysqli_affected_rows($dbc) == 1) { //One row affected, user successfully added
				$q = "INSERT INTO deactivated (user_id) VALUES ('".$_SESSION['user_id']."')";
				$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
				$success4= "Your request has been submitted. Your account will be deleted within a few days.";
			}//!
			else {
				$success4= "System error. Please try again later.";
			}//!
		}//end-if correct password
			else {
			echo $success4="Please enter your password correctly";
			}
	
 }//end deactivated

   print '<div class="panel"><form enctype="multipart/form-data" action="edit_profile.php" method="POST" name="editprofile1" id="editprofile1">
   <h3>Identity:</h3>
   <table width=50% border="0" cellpadding="0" cellspacing="5">
	<tr> 
   <td height="22" align="right" valign="middle"><label for="up_avatar" class="label">Change your avatar: </label></td>
	<td height="22" align="left" valign="middle"><input name="up_avatar" type="file" id="up_avatar"></td>
	</tr>
	<tr>
	<td height="22" colspan="3" align="middle" valign="middle"><span class="error">';if (isset ($successa)) echo $successa; print'</span></td>
	</tr> 
	<tr>
	<td height="22" align="right" valign="middle"><label for="bio" class="label">Bio </label></td>
   <td height="22" align="left" valign="middle"><textarea id="bio" name = "bio" rows = "5" cols = "45">';print $_SESSION['bio']; print'</textarea></td>
   </tr><tr>
   <td height="22" colspan="3" align="middle" valign="middle"><input type="submit" name="submit" id="submit" value="Save changes"></td>
    </tr><tr>
  <td height="22" colspan="3" align="middle" valign="middle"><input type="hidden" name="submitted1" value="TRUE" /></td>
   </tr></table>
   </form></div>';

   print '<div class="panel"><form method="post" action="edit_profile.php" name="editprofile2" id="editprofile2"> 
    <h3>Change your Email:</h3>
	<table width=50% border="0" cellpadding="0" cellspacing="5">
	<tr> 
    <td height="22" align="right" valign="middle"><label for="email" class="label">New Email </label></td>
    <td height="22" align="left" valign="middle"><input name="email" type="text" id="email"></td>
	</tr> 
	<tr>
	<td height="22" colspan="3" align="middle" valign="middle"><span class="error">';if (isset ($email_match)) echo $email_match; if (isset ($successm)) echo $successm ;print'</span></td>
	</tr> 
	<tr>
    <td height="22" align="right" valign="middle"><label for="pass" class="label">Password </label></td>
    <td height="22" align="left" valign="middle"><input name="pass" type="password" id="pass"></td>
	</tr> 
	<tr>
	<td height="22" colspan="3" align="middle" valign="middle"><span class="error">';if (isset ($error1)) echo $error1; print'</span></td>
	</tr> 
	<tr>
    <td height="22" colspan="3" align="middle" valign="middle"><input type="submit" name="submit" id="submit" value="Save changes"></td>
	</tr> 
	<tr>
    <td height="22" colspan="3" align="middle" valign="middle"><input type="hidden" name="submitted2" value="TRUE" /></td>
	</tr>
	</table>
    </form></div>
    
	<div class="panel"><form method="post" action="edit_profile.php" name="editprofile3" id="editprofile3">
    <h3>Change your Password:</h3>
	<table width=50% border="0" cellpadding="0" cellspacing="5">
	<tr> 
    <td height="22" align="right" valign="middle"><label for="olpass" class="label">Old Password</label></td> 
    <td height="22" align="left" valign="middle"><input name="olpass" type="password" id="olpass"></br></td>
    </tr>
	<tr>
	<td height="22" colspan="3" align="middle" valign="middle"><span class="error">';if (isset ($errorp)) echo $errorp; if (isset ($successp)) echo $successp ;print'</span></td>
	</tr> 
	<tr>
	<td height="22" align="right" valign="middle"><label for="newpass" class="label">New Password </label></td> 
    <td height="22" align="left" valign="middle"><input name="newpass" type="password" id="newpass"></br></td>
	</tr> 
	<tr>
    <td height="22" align="right" valign="middle"><label for="confnew" class="label">Retype New </label></td>
    <td height="22" align="left" valign="middle"><input name="confnew" type="password" id="confnew"></br></td>
	</tr> 
	<tr>
    <td height="22" colspan="3" align="middle" valign="middle"><input type="submit" name="submit" id="submit" value="Save changes"></td>
	</tr> 
	<tr>
   <td height="22" colspan="3" align="middle" valign="middle"><input type="hidden" name="submitted3" value="TRUE" /></td>
   </tr></table>
    </form></div>
   
   <div class="panel">
   <h3>Deactivate Account:</h3>
   <p>By deactivating your account, you are effectively closing it. An administrator will delete your profile and all its contents within a few days.</p>
   <p>Your profile and its contents will no longer be visible or accessible by anyone.</p>
   <p>All pending earnings from prints sold before the deactivation will be tranferred to your paypal account before the deletion of your account. All pending shipping of prints ordered before the deactivation will be completed without any complications whatsoever."
   <p>This is an one-way procedure: Once you have deactivated your profile, you cannot cancel your action. After logout, you will no longer be able to access your account</p>
    <form action="edit_profile.php" method="POST" name="editprofile4" id="editprofile4">';
	if (isset ($success4)) echo $success4; 
	print'</br>
   <label for="pass" class="label">Password </label>
   <input name="pass" type="password" id="pass">
   <input type="submit" name="submit" id="submit" value="Deactivate Account">
   <input type="hidden" name="sessionpass" value="'.$_SESSION['pass'].'" />
	<input type="hidden" name="deactivated" value="TRUE" />
	</form>
   </div>
   ';

 
 }
else header('Location: Access Error.php');
 mysqli_close($dbc);
 ?>
  
 </body>
 <?php include ('includes/footer.php'); ?>
</html>
