<?php
if (!isset($PathPrefix)) {
	$PathPrefix='../';
}

include($PathPrefix . 'includes/session.php');
$Title = _('User Profile');
include('includes/header.php');

echo '<div class="row text-center">
		<div class="col-sm-12">
			<h2>'.$Title.'</h2>
		</div>
	</div>';


if (isset($_POST['Modify'])) {
	// no input errors assumed initially before we test
	$InputError = 0;

	/* actions to take once the user has clicked the submit button
	ie the page has called itself with some user input */

 	$UpdatePassword = false;

	if ($_POST['PasswordCheck'] != ''){
		if (mb_strlen($_POST['Password'])<5){
			$InputError = 1;
			prnMsg(_('The password entered must be at least 5 characters long'),'error');
		} elseif (mb_strstr($_POST['Password'],$_SESSION['UserID'])!= False){
			$InputError = 1;
			prnMsg(_('The password cannot contain the user id'),'error');
		}
		if ($_POST['Password'] != $_POST['PasswordCheck']){
			$InputError = 1;
			prnMsg(_('The password and password confirmation fields entered do not match'),'error');
		}else{
			$UpdatePassword = true;
		}
	}

	$SupportedImgExt = array('png','jpg','jpeg');
	$upload_dir = 'uploads/' . $_SESSION['UserID'];

	if (isset($_POST['ClearImage']) ) {
		foreach ($SupportedImgExt as $ext) {
			$file = $upload_dir . '/profile.' . $ext;
			if (file_exists ($file) ) {
				//workaround for many variations of permission issues that could cause unlink fail
				unlink($file);
				if(is_file($file)) {
				   prnMsg(_('You do not have access to delete this item image file.'),'error');
				}
			}
		}
	}

	if (isset($_FILES['ProfilePicture']) AND $_FILES['ProfilePicture']['name'] !='') {

		$ImgExt = pathinfo($_FILES['ProfilePicture']['name'], PATHINFO_EXTENSION);

		$result	= $_FILES['ProfilePicture']['error'];
		$UploadTheFile = true; //Assume all is well to start off with

		

		// check upload directory exist or create it
		if(is_dir($upload_dir))
		{
			$upload_dir_exist = true;
		}
		else
		{
			$upload_dir_exist = mkdir($upload_dir, 0775, true);
		}

		if($upload_dir_exist)
		{
			$filename = $upload_dir . '/profile.' . $ImgExt;

			//But check for the worst
			if (!in_array ($ImgExt, $SupportedImgExt)) {
				prnMsg('Only ' . implode(", ", $SupportedImgExt) . ' files are supported - a file extension of ' . implode(", ", $SupportedImgExt) . ' is expected', 'warn');
				$UploadTheFile = false;
			} elseif ( $_FILES['ProfilePicture']['size'] > ($_SESSION['MaxImageSize']*1024)) { //File Size Check
				prnMsg('The file size is over the maximum allowed. The maximum size allowed is ' . $_SESSION['MaxImageSize'] . 'KB','warn');
				$UploadTheFile = false;
			} elseif ( $_FILES['ProfilePicture']['type'] == 'text/plain' ) {  //File Type Check
				prnMsg('Only graphics files can be uploaded', 'warn');
				$UploadTheFile = false;
			} elseif ( $_FILES['ProfilePicture']['error'] == 6 ) {  //upload temp directory check
				prnMsg('No tmp directory set. You must have a tmp directory set in your PHP for upload of files.', 'warn');
				$UploadTheFile = false;
			}

			foreach ($SupportedImgExt as $ext) {
				$file = $upload_dir . '/profile.' . $ext;
				if (file_exists ($file) ) {
					$result = unlink($file);
					if (!$result){
						prnMsg(_('The existing image could not be removed'),'error');
						$UploadTheFile = false;
					}
				}
			}

			if ($UploadTheFile){
				$result = move_uploaded_file($_FILES['ProfilePicture']['tmp_name'], $filename);

				if(!$result)
				{
					prnMsg('Oops! Something went wrong when uploading profile image', 'error');
				}
			}
		}
		else
		{
			prnMsg('Failed to locate upload directory', 'error');
		}
	}

	if ($InputError != 1) {
		// no errors
		if ($UpdatePassword) {
			$sql = "UPDATE www_users
				SET password='" . CryptPass($_POST['Password']) . "',
					realname='".$_POST['RealName']."',
					email='".$_POST['email']."',
					phone='".$_POST['phone']."'
				WHERE userid = '" . $_SESSION['UserID'] . "'";

			$ErrMsg =  _('The user alterations could not be processed because');
			$DbgMsg = _('The SQL that was used to update the user and failed was');

			$result = DB_query($sql,$db, $ErrMsg, $DbgMsg);
		}
		else
		{
			$sql = "UPDATE www_users
				SET realname='".$_POST['RealName']."',
					email='".$_POST['email']."',
					phone='".$_POST['phone']."'
				WHERE userid = '" . $_SESSION['UserID'] . "'";

			$ErrMsg =  _('The user alterations could not be processed because');
			$DbgMsg = _('The SQL that was used to update the user and failed was');

			$result = DB_query($sql,$db, $ErrMsg, $DbgMsg);
		}

		$sql = "INSERT INTO lms_users (userid, title, organization)
				VALUES('" . $_SESSION['UserID'] . "', '" . $_POST['title'] . "', '" . $_POST['organization'] . "') ON DUPLICATE KEY UPDATE
				title='" . $_POST['title'] . "', organization='" . $_POST['organization'] . "'";

		$ErrMsg =  _('The user alterations could not be processed because');
		$DbgMsg = _('The SQL that was used to update the user and failed was');

		$result = DB_query($sql,$db, $ErrMsg, $DbgMsg);

		prnMsg(_('The user settings have been updated'),'success');

		if($_POST['RealName'] != $_SESSION['UsersRealName'])
		{
			$_SESSION['UsersRealName'] = $_POST['RealName'];
		}
	}
}

echo '<form class="form-horizontal" enctype="multipart/form-data" method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

echo '<div class="form-group">
		<label class="control-label col-sm-3">' . _('User ID') . ':</label>
		<div class="col-sm-9">
		<p class="form-control-static">' . $_SESSION['UserID'] . '</p>
		</div>
	</div>';

echo '<div class="form-group">
		<label class="control-label col-sm-3">User Name:</label>
		<div class="col-sm-9">
			<input type="text" class="form-control" placeholder="User Name" name="RealName" size="35" value="' .  $_SESSION['UsersRealName'] . '" required />
		</div>
	</div>';

if (!isset($_POST['PasswordCheck'])) {
	$_POST['PasswordCheck']='';
}
if (!isset($_POST['Password'])) {
	$_POST['Password']='';
}

echo '<div class="form-group">
		<label class="control-label col-sm-3">New Password:</label>
		<div class="col-sm-9">
			<input type="password" class="form-control" placeholder="Password" name="Password" size="20" value="' .  $_POST['Password'] . '" />
		</div>
	</div>
	<div class="form-group">
		<label class="control-label col-sm-3">Confirm Password:</label>
		<div class="col-sm-9">
			<input type="password" class="form-control" placeholder="Confirm Password" name="PasswordCheck" size="20"  value="' . $_POST['PasswordCheck'] . '" />
			<span class="help-block">(If you leave the password boxes empty your password will not be changed)</span>
		</div>
	</div>';


$sql = "SELECT title, organization
		from lms_users WHERE userid = '" . $_SESSION['UserID'] . "'";

$result = DB_query($sql);
$myrow = DB_fetch_array($result);

if(!isset($_POST['title'])) {
	$_POST['title'] = $myrow['title'];
}
if(!isset($_POST['organization'])) {
	$_POST['organization'] = $myrow['organization'];
}

echo '<div class="form-group">
		<label class="control-label col-sm-3">Job Title:</label>
		<div class="col-sm-9">
			<input type="text" maxlength="50" class="form-control" name="title" placeholder="Job Title" value="'.$_POST['title'].'">
		</div>
	</div>
	
	<div class="form-group">
		<label class="control-label col-sm-3">Company:</label>
		<div class="col-sm-9">
			<input type="text" maxlength="50" class="form-control" name="organization" placeholder="Company / Organization Name" value="'.$_POST['organization'].'">
		</div>
	</div>';


$sql = "SELECT email, phone
		from www_users WHERE userid = '" . $_SESSION['UserID'] . "'";

$result = DB_query($sql);
$myrow = DB_fetch_array($result);

if(!isset($_POST['email'])) {
	$_POST['email'] = $myrow['email'];
}
if(!isset($_POST['phone'])) {
	$_POST['phone'] = $myrow['phone'];
}

echo '<div class="form-group">
		<label class="control-label col-sm-3">Phone No:</label>
		<div class="col-sm-9">
			<input type="tel" class="form-control" name="phone" placeholder="Contact Phone Number" value="'.$_POST['phone'].'">
			<span class="help-block">(Eg: +60123456789) </span>
		</div>
	</div>
	
	<div class="form-group">
		<label class="control-label col-sm-3">Email:</label>
		<div class="col-sm-9">
			<input type="email" class="form-control" name="email" placeholder="Contact Email Address" value="'.$_POST['email'].'">
		</div>
	</div>';



$profile_img = 'css/profile.png';
$upload_dir = 'uploads/' . $_SESSION['UserID'];
$SupportedImgExt = array('png','jpg','jpeg');
foreach ($SupportedImgExt as $ext) {
	$file = $upload_dir . '/profile.' . $ext;
	if (file_exists ($file) ) {
		$profile_img = $file;
		break;
	}
}

echo '<div class="form-group">
		<div class="col-sm-3"></div>
		<div class="col-sm-9">
			<img src="' . $profile_img . '?' . filemtime($profile_img) . '" class="media-object" style="width:80px">
		</div>
	</div>

	<div class="form-group">
		<label class="control-label col-sm-3">Upload Profile Picture:</label>
		<div class="col-sm-9">
			<input class="form-control" type="file" id="ProfilePicture" name="ProfilePicture" />
			<span class="help-block">(We recommend using a square image that is between 200 and 250 pixels wide)</span>
			<div class="checkbox">
				<label><input name="ClearImage" id="ClearImage" value="1" type="checkbox"> Remove Profile Picture</label>
			</div>
		</div>
	</div>

	<div class="form-group">
		<div class="col-sm-3"></div>
		<div class="col-sm-9">
			<input type="submit" class="btn btn-default" name="Modify" value="' . _('Modify') . '" />
		</div>
	</div>
	</form>';

include('includes/footer.php');
?>