<?php
	include ('includes/bootstrap.inc.php');
	
	if(empty(Data::getSession('uid'))){
		header('Location: login.php?op=e');
		die();
	}
	
	$op 	= Data::getGet( 'op' );
	$uid 	= intval( Data::getGet( 'uid' ) );
	
	// create a new user object
	$u = new User($uid);

	$bs = new Bootstrap();
	
	
	switch ($op){
		case 'f':
			/**
			 * Creates a new template for the user's form.
			 * and fills it with user login form.
			 */
			$template_user_form 	= _DEFAULT_THEME_PATH . _DEFAULT_THEME . "/user_form.tpl";
			$layout_user_form = new Template ( $template_user_form );
			
			
			/**
			 * uid is not null so enter edit mode by adding uid to form action
			 */
			if( is_null( $uid ) == false && is_int( $uid ) == true){
				$layout_user_form->set( "uid", $uid );
				
			}else{
				$layout_user_form->set( "uid", "" );
			}
			
			/**
			 * if user attempt to access another user data, set an access denied message log the error
			 */
			if( Security::checkByUid( Security::ROLE_ADMIN, $_SESSION['uid'] ) == false ){
				if( $uid !== $_SESSION['uid'] ){
					$layout->set ( "message-box", $bs->message( _( "Access denied" ), Bootstrap::ALERT_DANGER, 3000 ));
					$layout->set ( "content", $bs->redirect('user.php?op=f&uid=' . $_SESSION['uid'], 3500) );
					Watchdog::write( Watchdog::TYPE_ACCESS_DENIED, 'attempt to modify user data', $_SESSION['uid'], Watchdog::WATCHDOG_WARNING );
					break;
				}
			}
			
			
			$open_form = $bs->openForm( 'user-form', $_SERVER['PHP_SELF'] . '?op=s&uid=' . $uid );
			
			
			$input_uid = $bs->addInput('hidden', 'uid', $uid);

			
			$roles = Connection::entity_load( 'roles', array('rid', 'name') );
			
			/**
			 * Role select: for security reason, user cannot change his/her role
			 */
			if( $uid == $_SESSION['uid'] ){
				$select_rid = $bs->addInput('hidden', 'rid', $_SESSION['uid']);
			}else{
				$select_rid = $bs->addSelect( 'rid', $roles, $u->rid, true,  _( "Role" ) );
			}
			
			
			
			$locales = Connection::entity_load( 'locales', array('locale', 'description') );
			$locale = $bs->addSelect( 'locale', $locales, $u->locale, true,  _( "Language" ) );

			
			$input_email = $bs->addInput('email', 
											'username', 
											$u->email, 
											true, 
											_( "Email" ), 
											'myname@example.com'
											);
			
			/*
			 * show password input if is a new user
			 */
			$input_password = '';
			if(empty($uid) == true){
				$input_password = $bs->addInput('password', 
										'password', 
										'',
										true,
										_( "Password" )
										);
			}
			
			
			$input_firstname = $bs->addInput('text', 
										'firstname', 
										$u->firstname,
										true,
										_( "First name" ),
										'john'
										);
			
			
			$input_lastname = $bs->addInput('text', 
										'lastname', 
										$u->lastname,
										true,
										_("Last name"),
										'longbow' 
										);
			
			
			$input_phone = $bs->addInput('text', 
										'phone', 
										$u->phone,
										true,
										_( "Phone number" ), 
										'+39 055 1234567'
										);
			
			
			/**
			 * set action buttons at the bottom of the form
			 */
			$input_submit = $bs->addSubmit( 'save', _( "save" ) );
			
			/**
			 * for security reason, user cannot delete himself
			 */
			if( $uid != $_SESSION['uid'] ){
				$input_delete 		= $bs->addButton( 'delete', 'delete' );
				$input_delete_logic = $bs->confirm('button-delete', _( "Do you want to delete selected user ?" ), $_SERVER['PHP_SELF'] . '?op=d&uid=' . $uid);
				$user_form_title = _( "Edit user detail for user " ) . $u->firstname . " " . $u->lastname. " (" . $u->email . ")";
			}else{
				$input_delete 		= '';
				$input_delete_logic = '';
				$user_form_title = _( "Edit my detail" );
			}
			$close_form = $bs->closeForm();
			
			$layout_user_form->set( "user-logic", '' );
			$layout_user_form->set( "user-form-title", $user_form_title );
			$layout_user_form->set( "user-form", 	$open_form. 
													$input_uid.
													$select_rid.
													$locale.
													$input_email.
													$input_password.
													$input_firstname.
													$input_lastname.
													$input_phone.
													$input_submit.
													$input_delete.
													$input_delete_logic.
													$close_form
													);

			// assign form output to the content container
			$layout->set ( "content", $layout_user_form->output () );
			break;
		
			
			
			
		case 'cpwd':
			// if uid to change password is different from the user one and user is not an admin
			if( $uid != $_SESSION['uid'] ){
				if( Security::checkByUid( Security::ROLE_ADMIN, $_SESSION['uid'] ) == false ){
					$layout->set ( "message-box", $bs->message( _( "Access denied" ), Bootstrap::ALERT_DANGER, 3000 ));
					$layout->set ( "content", $bs->redirect('user.php?op=pwd&uid=' . $_SESSION['uid'], 3500) );
					Watchdog::write( Watchdog::TYPE_ACCESS_DENIED, 'attempt to modify user data', $_SESSION['uid'], Watchdog::WATCHDOG_WARNING );
					break;
				}
			}
			
			if( is_null( Data::getPost( 'new-password' ) ) == false ){
				$u->password = md5( Data::getPost( 'new-password' ) );
				$rv = $u->update();
			}else{
				$rv = false;
			}
			
			if($rv == true){
				// set a global message
				$message->set( _( "Password changed" ), Message::MESSAGE_TYPE_SUCCESS);
				
				// overwrite user session variable
				$user_array = Connection::entity_load ( 'users', array(), array (
									'uid' => $_SESSION['uid']
								) );
				$_SESSION ['user_array'] = $user_array[0];
				
				// show a success dialog
				$layout->set ( "content", $bs->dialog( _( "Changing password..." ) ) . $bs->redirect(referer_uri(), 3000) );
			}else{
				$layout->set ( "message-box", $bs->message( _( "Cannot change password. Please check form again or contact application support." ), Bootstrap::ALERT_DANGER, 3000 ));
				$layout->set ( "content", $bs->redirect('user.php?op=pwd&uid=' . $u->uid, 3500) );
			}
			
			break;
			
			
		case 'pwd':
			// if uid to change password is different from the user one and user is not an admin
			if( $uid != $_SESSION['uid'] ){
				if( Security::checkByUid( Security::ROLE_ADMIN, $_SESSION['uid'] ) == false ){
					$layout->set ( "message-box", $bs->message( _( "Access denied" ), Bootstrap::ALERT_DANGER, 3000 ));
					$layout->set ( "content", $bs->redirect('user.php?op=pwd&uid=' . $_SESSION['uid'], 3500) );
					Watchdog::write( Watchdog::TYPE_ACCESS_DENIED, 'attempt to modify user data', $_SESSION['uid'], Watchdog::WATCHDOG_WARNING );
					break;
				}
			}
			
			
			/**
			 * Creates a new template for the user's form.
			 * and fills it with user login form.
			 */
			
			$open_form = $bs->openForm( 'change-password-form', $_SERVER['PHP_SELF'] . '?op=cpwd&uid=' . $uid, 'POST', '', 'data-parsley-validate' );
		
			
			$bso = new BootstrapInput( 'new-password', '', _( "New password" ), _( "New password" ) );
			$bso->setType( BootstrapInput::TYPE_PASSWORD );
			$bso->placeholder = _( "New password" );
			$input_new_password = $bso->output();
			unset( $bso );
			
			$bso = new BootstrapInput( 'repeat-password', '', _( "Repeat password" ), _( "Repeat password" ) );
			$bso->setType( BootstrapInput::TYPE_PASSWORD );
			$bso->placeholder	= _( "Repeat password" );
			$bso->attributes	= 'data-parsley-equalto="#new-password"';
			$input_repeat_password = $bso->output();
			unset( $bso );
			
			$button_change_password = BootstrapButton::create( 'change-password', _( "Change password" ) );
			$close_form = $bs->closeForm();
			
			
			// Adding output to teplates
			$template_user_form 	= _DEFAULT_THEME_PATH . _DEFAULT_THEME . "/user_form.tpl";
			$layout_user_form = new Template ( $template_user_form );
			
			$user_logic = '<script type="text/javascript" src="assets/js/user.logic.js"></script>';
			$user_form_title = _( "Change my password" );
			if( $uid != $_SESSION['uid'] ){
				$user_form_title = _( "Change password for user " ) . $u->firstname . " " . $u->lastname. " (" . $u->email . ")";
			}
			$layout_user_form->set( 'user-form-title', $user_form_title );
			$layout_user_form->set( 'user-logic', $user_logic );
			$layout_user_form->set( "user-form", $open_form.
													$input_new_password.
													$input_repeat_password.
													$button_change_password.
													$close_form
													);
			
			
			$layout->set ( "content", $layout_user_form->output () );
			break;
		case 'd':
			if( Security::checkByUid( Security::ROLE_ADMIN, $_SESSION['uid'] ) == false ){
				$layout->set ( "message-box", $bs->message( _( "Access denied" ), Bootstrap::ALERT_DANGER, 3000 ));
				$layout->set ( "content", $bs->redirect('user.php?op=f&uid=' . $_SESSION['uid'], 3500) );
				Watchdog::write( Watchdog::TYPE_ACCESS_DENIED, 'attempt to modify user data', $_SESSION['uid'], Watchdog::WATCHDOG_WARNING );
			}else{
				$rv = $u->delete();
				
				if($rv == true){
					// set a global message
					$message->set( _( "User deleted" ), Message::MESSAGE_TYPE_SUCCESS);
					$layout->set ( "content", $bs->dialog( _( "Deleting user" ) ) . $bs->redirect('user.php', 3000) );
				}else{
					$layout->set ( "message-box", $bs->message( _( "Cannot delete user. Please try again or contact application support." ), Bootstrap::ALERT_DANGER, 3000 ));
					$layout->set ( "content", $bs->redirect('user.php?op=f&uid=' . $u->uid, 3500) );
				}
			}
			break;
		
		case 's':
			// security warning. Standard user can NOT modify others data 
			if( $uid != $_SESSION['uid'] ){
				if( Security::checkByUid( Security::ROLE_ADMIN, $_SESSION['uid'] ) == false ){
					$layout->set ( "message-box", $bs->message( _( "Access denied" ), Bootstrap::ALERT_DANGER, 3000 ));
					$layout->set ( "content", $bs->redirect('user.php?op=f&uid=' . $_SESSION['uid'], 3500) );
					Watchdog::write( Watchdog::TYPE_ACCESS_DENIED, 'attempt to modify user data', $_SESSION['uid'], Watchdog::WATCHDOG_WARNING );
					break;
				}
			}
			
			
			if( $uid == $_SESSION['uid'] ){
				$u->rid = $_SESSION['rid'];	
			}else{
				$u->rid 	= Data::getPost( 'rid' );
			}
			
			
			$u->locale		= Data::getPost( 'locale' );
			$u->email 		= Data::getPost( 'username' );
			$u->firstname 	= Data::getPost( 'firstname' );
			$u->lastname	= Data::getPost( 'lastname' );
			$u->phone 		= Data::getPost( 'phone' );
			
			if( is_null(Data::getPost( 'password' ) ) == false ){
				$u->password = md5( Data::getPost( 'password' ) );
			}
			
			$rv = $u->save();
			
			if($rv == true){
				// set a global message
				$message->set( _( "User saved" ), Message::MESSAGE_TYPE_SUCCESS);
				// overwrite user session variable
				$user_array = Connection::entity_load ( 'users', array(), array (
									'uid' => $_SESSION['uid']
								) );
				$_SESSION ['user_array'] = $user_array [0]; 
				// show a success dialog
				$layout->set ( "content", $bs->dialog( _( "Saving user..." ) ) . $bs->redirect(referer_uri(), 3000) );
			}else{
				$layout->set ( "message-box", $bs->message( _( "Cannot save user. Please check form again or contact application support." ), Bootstrap::ALERT_DANGER, 3000 ));
				$layout->set ( "content", $bs->redirect('user.php?op=f&uid=' . $u->uid, 3500) );
			}
			
			break;
			
		default:
			
			if( Security::checkByUid( Security::ROLE_ADMIN, $_SESSION['uid'] ) == false ){
				$layout->set ( "message-box", $bs->message( _( "Access denied" ), Bootstrap::ALERT_DANGER, 3000 ));
				$layout->set ( "content", $bs->redirect('user.php?op=f&uid=' . $_SESSION['uid'], 3500) );
				Watchdog::write( Watchdog::TYPE_ACCESS_DENIED, 'attempt to modify user data', $_SESSION['uid'], Watchdog::WATCHDOG_WARNING );
				break;
			}
			
			$u = Connection::entity_load('users', array('uid', 'rid', 'email', 'firstname', 'lastname', 'phone'));
			
			// create a Datatable object and populate with data taken from User table
			$DT = new Datatable('users');
			
			
			// populate datatable
			$DT->addRows($u);
			
			$DT->addAction('edit', 'user.php?op=f&uid=%s', array('uid'));
			$DT->addAction('view', 'user.php?op=view&uid=%s', array('uid'));
			$DT->addAction('password', 'user.php?op=pwd&uid=%s', array('uid'));
			
			// render the Datatable object and put the HTML output into a variable
			$output = $DT->output();
			
			$output .= '<a href="'.$_SERVER['PHP_SELF'].'?op=f"><button>add user</button></a>';
			
			$layout->set ( "content", $output );
			break;
	}
	
	
	$layout->set ( 'section-name', _( "Users" ) );
	// create the search input using Typeahead suggestion library
	$search_logic = '<script type="text/javascript" src="assets/js/search.logic.js"></script>';

	$bso = new BootstrapInput( 'input-search', '' );
	$bso->placeholder = _('Search...');
	$search_input = $bso->output();

	$layout->set ( "search", $search_logic . $search_input );
	
	
	/**
	 * Outputs the page with the user's profile.
	 */
	echo template_common_header();
	echo $layout->output ();
	echo template_common_footer();
?>
