<?php
	include("includes/dbconfig.php");
	$pagetitle = "System User Setup";
	require('includes/applicationtop.php');
	require('includes/applicationmenu.php');
	
	$err= "";
	
	$successsave="";
	
	if(isset($_POST['userfocus']))
	{
		$userfocus = $_POST['userfocus'];
	}
	
	if(!(isset($_POST['savedatabtn'])) && (isset($userfocus) && $userfocus > 0))
	{
		$sysuserdata = DB::queryFirstRow("SELECT first_name, last_name, phone, password, employee_role, email, login_name, status, role, branch, version FROM personnel_details WHERE id=%i", $userfocus);
		
		if(DB::count() == 1)
		{   
			$_POST['userfocus'] = $userfocus;
			$_POST['firstname'] = ($sysuserdata['first_name'] != "") ? $sysuserdata['first_name'] : "";
			$_POST['lastname'] = ($sysuserdata['last_name'] != "") ? $sysuserdata['last_name'] : "";
			$_POST['phone'] = ($sysuserdata['phone'] != "") ? $sysuserdata['phone'] : "";
			$_POST['mail'] = ($sysuserdata['email'] != "") ? $sysuserdata['email'] : "";
			$_POST['login'] = ($sysuserdata['login_name'] != "") ? $sysuserdata['login_name'] : "";
			$_POST['employee_role'] = ($sysuserdata['employee_role'] != "") ? $sysuserdata['employee_role'] : "";
			$_POST['status'] = $sysuserdata['status'];
			$_POST['role'] = $sysuserdata['role'];
			$_POST['shop'] = $sysuserdata['branch'];
			$_POST['recversion'] = $sysuserdata['version'];
		}
	}
	
	if(isset($_POST['savedatabtn']))
	{
		if($_SESSION["connectedusergroup"] == 1)
		{
			if(trim($_POST['firstname']) == "")
				$err = $err."First Name Required!<br>";
				
			if(trim($_POST['lastname']) == "")
				$err = $err."Last Name Required!<br>";
			
			if(trim($_POST['mail'])!="")
			{
				if(!filter_var(trim($_POST['mail']), FILTER_VALIDATE_EMAIL))
				{
					$err = $err."Valid Email Required!<br>";
				}
			}
			
			if($_POST['userfocus'] == 0)
			{
				if(trim($_POST['login']) == "")
				{
					$err = $err."login Name Required!<br>";
				}
				else
				{
					$availableusers = DB::queryFirstField("SELECT COUNT(id) FROM personnel_details WHERE login_name=%s", trim($_POST['login']));
					
					if($availableusers > 0)
						$err = $err."login Name Already Exists!<br>";
				}
			}
			
			if($_POST['userfocus'] == 0)
			{
				if (trim($_POST['kisumuluzo'])=="")
					$err = $err."Password Required!<br>";
					
				if (trim($_POST['damuekisumuluzo'])=="")
					$err = $err."Confirm Password Required!<br>";
					
				if(trim($_POST['kisumuluzo'])!="" && trim($_POST['damuekisumuluzo'])!="")
				{
					if(strlen(trim($_POST['kisumuluzo'])) < 8)
					{
						$err = $err."Password With 8 Or More Characters Permitted!<br>";
					}
					else
					{
						if(!preg_match('/[\'^!£$%&*()}{@#~?><>,|=_+¬-]/', trim($_POST['kisumuluzo'])) || !preg_match('/[0-9]/', trim($_POST['kisumuluzo'])))
						{
							$err = $err."Password With Atleast One Digit And Special A Character Permitted!<br>";
						}
						else
						{
							if(strcmp(trim($_POST['kisumuluzo']), trim($_POST['damuekisumuluzo'])) != 0)
								$err = $err."Password And Confirm Password Should Be The Same!<br>";
						}
					}
					
				}
			}
			else
			{
				if (trim($_POST['kisumuluzo'])!="" || trim($_POST['damuekisumuluzo'])!="")
				{
					if (trim($_POST['kisumuluzo'])=="")
						$err = $err."Password Required!<br>";
					
					if (trim($_POST['damuekisumuluzo'])=="")
						$err = $err."Confirm Password Required!<br>";
						
					if(trim($_POST['kisumuluzo'])!="" && trim($_POST['damuekisumuluzo'])!="")
					{
						if(strlen(trim($_POST['kisumuluzo'])) < 8)
						{
							$err = $err."Password With 8 Or More Characters Permitted!<br>";
						}
						else
						{
							if(!preg_match('/[\'^!£$%&*()}{@#~?><>,|=_+¬-]/', trim($_POST['kisumuluzo'])) || !preg_match('/[0-9]/', trim($_POST['kisumuluzo'])))
							{
								$err = $err."Password With Atleast One Digit And Special A Character Permitted!<br>";
							}
							else
							{
								if(strcmp(trim($_POST['kisumuluzo']), trim($_POST['damuekisumuluzo'])) != 0)
									$err = $err."Password And Confirm Password Should Be The Same!<br>";
							}
						}
						
					}
				}
			}
				
			if($_POST['status'] == "")
				$err = $err."Status Required!<br>";
				
			if($_POST['role'] == "")
				$err = $err."User Role Required!<br>";
				
			if($_POST['role'] == 1 || $_POST['role'] == 2)
			{
				if($_POST['shop'] != "")
					$err = $err."User Shop Not Required For Selected User Role!<br>";
			}
			else
			{
				if($_POST['shop'] == "")
					$err = $err."User Shop Required!<br>";
			}
		}
		else
		{
			$err = $err."Limited Access!<br>";
		}
		
		if($err == "")
		{
			DB::$error_handler = false;
			DB::$throw_exception_on_error = true;
		
			if($userfocus == 0)
			{
				try
				{
					$pass= password_hash(trim($_POST['kisumuluzo']), PASSWORD_BCRYPT);
					DB::startTransaction();
					DB::query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
					DB::insert
					('personnel_details', 
						array
						(
							'created_by' => $_SESSION['connecteduserid'], 
							'first_name' => (trim($_POST['firstname']) != "") ? trim($_POST['firstname']) : NULL, 
							'last_name' => (trim($_POST['lastname']) != "") ? trim($_POST['lastname']) : NULL, 
							'display_name' => trim($_POST['firstname']) . " " . trim($_POST['lastname']), 
							'phone' => (trim($_POST['phone']) != "") ? trim($_POST['phone']) : NULL, 
							'email' => (trim($_POST['mail']) != "") ? trim($_POST['mail']) : NULL,
							'login_name' => (trim($_POST['login']) != "") ? trim($_POST['login']) : NULL,
							'password' => $pass ,
							'status' => ($_POST['status'] != "") ? $_POST['status'] : NULL,
							'role' => ($_POST['role'] != "") ? $_POST['role'] : NULL,
							'employee_role' => ($_POST['employee_role'] != "") ? $_POST['employee_role'] : 0,
							'branch' => ($_POST['shop'] != "") ? $_POST['shop'] : NULL 
						)
					);
					
					DB::commit();
					
					$successsave="New System User Successfully Saved";
					
					unset($_POST['userfocus']);
					unset($_POST['firstname']);
					unset($_POST['lastname']);
					unset($_POST['phone']);
					unset($_POST['mail']);
					unset($_POST['login']);
					unset($_POST['kisumuluzo']);
					unset($_POST['damuekisumuluzo']);
					unset($_POST['status']);
					unset($_POST['role']);
					unset($_POST['shop']);
					unset($_POST['recversion']);
					unset($_POST['employee_role']);
				}
				catch(MeekroDBException $e)
				{
					$err = $err."Critical Error Occured!<br>";
					$err = $err.$e->getMessage()."<br>";
					$err = $err.$e->getQuery()."<br>";
					DB::rollback();
					DB::$error_handler = 'meekrodb_error_handler';
					DB::$throw_exception_on_error = false;
				}
			}
			else
			{
				try
				{
					$trxnConnextn = new MeekroDB();
					$nonTrxnConnextn = new MeekroDB();
					
					$trxnConnextn->startTransaction();
					$trxnConnextn->query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
					$trxnConnextn->query("SELECT * FROM personnel_details WHERE id=%i FOR UPDATE", $_POST['userfocus']);
					$pass= password_hash(trim($_POST['kisumuluzo']), PASSWORD_BCRYPT);
					
					$trxnConnextn->update
					('personnel_details', 
						array
						(
							'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
							'updated_by' => $_SESSION['connecteduserid'], 
							'first_name' => (trim($_POST['firstname']) != "") ? trim($_POST['firstname']) : NULL, 
							'last_name' => (trim($_POST['lastname']) != "") ? trim($_POST['lastname']) : NULL, 
							'display_name' => trim($_POST['firstname']) . " " . trim($_POST['lastname']), 
							'phone' => (trim($_POST['phone']) != "") ? trim($_POST['phone']) : NULL, 
							'email' => (trim($_POST['mail']) != "") ? trim($_POST['mail']) : NULL,
							'status' => ($_POST['status'] != "") ? $_POST['status'] : NULL,
							'role' => ($_POST['role'] != "") ? $_POST['role'] : NULL,
							'branch' => ($_POST['shop'] != "") ? $_POST['shop'] : NULL,
							'employee_role' => ($_POST['employee_role'] != "") ? $_POST['employee_role'] : 0,
							'version' => ($_POST['recversion'] + 1),
							'password' => $pass
						), 
						"id=%i", $_POST['userfocus']
					);
					
					if(trim($_POST['kisumuluzo']) != "")
					{
						$pass= password_hash(trim($_POST['kisumuluzo']), PASSWORD_BCRYPT);
						$trxnConnextn->update
						('personnel_details',
							array
							(
								'password' => $pass
							), 
							"id=%i", $_POST['userfocus']
						);
					}
					
					$userversionrow = $nonTrxnConnextn->queryFirstRow("SELECT version FROM personnel_details WHERE id=%i LIMIT 1", $_POST['userfocus']);
					
					if($userversionrow['version'] == $_POST['recversion'])
					{
						$trxnConnextn->commit();
?>
						<script>
							location.href="systemusers.php";
						</script>
<?php
						exit();
					}
					else
					{
						$trxnConnextn->rollback();
						$err = "System User Details Could Not Be Updated Due To Updates Just Done By Another System User!<br>";
					}
					
				}
				catch(MeekroDBException $e)
				{
					$err = $err."Critical Error Occured!<br>";
					$err = $err.$e->getMessage()."<br>";
					$err = $err.$e->getQuery()."<br>";
					$trxnConnextn->rollback();
					DB::$error_handler = 'meekrodb_error_handler';
					DB::$throw_exception_on_error = false;
				}
			}
		}
	}
?>
			<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<!-- Content Header (Page header) -->
				<section class="content-header">
					<h4>System User Setup</h4>
					<ol class="breadcrumb">
					</ol>
				</section>

				<!-- Main content -->
				<section class="content">
					<!-- Default card -->
					<div class="card card-primary">
						<?php
							if($_SESSION["connectedusergroup"] == 1)
							{
						?>
						<div class="card-header with-border text-center">
							<h3 class="card-title">System User Setup Form</h3>
						</div>
						
						<div class="card-body">
							<?php
								if($err!="")
								{
							?>
							<div class="alert alert-danger alert-dismissable">
								<i class="glyphicon glyphicon-ban-circle"></i>
								<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><br>
								<?php 
									echo $err; 
								?>
							</div>
							<?php
								}
							?>
							
							<?php
								if($successsave!="")
								{
							?>
							<div class="alert alert-success alert-dismissable">
								<i class="glyphicon glyphicon-ok"></i>
								<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
								<?php 
									echo $successsave; 
								?>
							</div>
							<?php
								}
							?>
							<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
								<INPUT name="userfocus" id="userfocus" type=hidden value="<?php echo isset($_POST['userfocus']) ? $_POST['userfocus'] : 0 ?>">
								<INPUT name="recversion" id="recversion" type=hidden value="<?php echo isset($_POST['recversion']) ? $_POST['recversion'] : 0 ?>">
							<div class="row">
								<div class="col-sm-6">
								   
									<div class="form-group  ">
									<label for="employee_role">Personel Category</label>
									<select  class="form-control" name="employee_role" id="employee_role" data-placeholder="Choose One">
											<option value="0">Choose One</option>
											<?php
												$employee_roledata = DB::query("SELECT * FROM employee_category");
												
												foreach($employee_roledata as $useemployee_role)
												{
											?>
											<option <?php if(isset($_POST['employee_role']) && ($useemployee_role['id'] == $_POST['employee_role'])) echo "selected=\"selected\""; ?> value="<?php echo $useemployee_role['id']; ?>"><?php echo $useemployee_role['name']; ?></option>
											<?php
												}
											?>
											</select>
										 </div><!-- form-group -->
										 
									<div class="form-group">
										<label for="firstname">First Name</label>
										<input type="text" name="firstname" id="firstname" maxlength="40" class="form-control" value="<?php echo isset($_POST['firstname']) ? $_POST['firstname'] : "" ?>" >
									</div><!-- form-group -->
									
									<div class="form-group">
										<label for="lastname">Last Name</label>
										<input type="text" name="lastname" id="lastname" maxlength="40" class="form-control" value="<?php echo isset($_POST['lastname']) ? $_POST['lastname'] : "" ?>" >
									</div><!-- form-group -->
									
									<div class="form-group">
										<label for="phone">Phone Number</label>
										<input type="text" name="phone" id="phone" maxlength="15" class="form-control" value="<?php echo isset($_POST['phone']) ? $_POST['phone'] : "" ?>" >
									</div><!-- form-group -->
									
									<div class="form-group">
										<label for="mail">Email</label>
										<input type="text" name="mail" id="mail" maxlength="80" class="form-control" value="<?php echo isset($_POST['mail']) ? $_POST['mail'] : "" ?>" >
									</div><!-- form-group -->
									
									 
									
									 
									
																		
								</div>
							
								<div class="col-sm-6">
									<div class="form-group">
										<label for="login">login Name</label>
										<input type="text" <?php echo (isset($_POST['userfocus']) && $_POST['userfocus'] > 0) ? "disabled" :  ""; ?> name="login" id="login" maxlength="80" class="form-control" value="<?php echo isset($_POST['login']) ? $_POST['login'] : "" ?>" >
									</div><!-- form-group -->
									
									<div class="form-group">
										<label for="kisumuluzo">Password</label>
										<input type="password" name="kisumuluzo" id="kisumuluzo" maxlength="50" class="form-control" value="<?php echo isset($_POST['kisumuluzo']) ? $_POST['kisumuluzo'] : "" ?>" >
									</div><!-- form-group -->
									
									<div class="form-group">
										<label for="damuekisumuluzo">Confirm Password</label>
										<input type="password" name="damuekisumuluzo" id="damuekisumuluzo" maxlength="50" class="form-control" value="<?php echo isset($_POST['damuekisumuluzo']) ? $_POST['damuekisumuluzo'] : "" ?>" >
									</div><!-- form-group -->
									
									<div class="row">
									<div class="form-group col-sm-4">
										<label for="status">Status</label>
										<select  class="form-control" name="status" id="status" data-placeholder="Choose One">
											<option value="">Choose One</option>
											<option <?php if(isset($_POST['status']) && "1"==$_POST['status']) echo "selected=\"selected\""; ?> value="1">Active</option>
											<option <?php if(isset($_POST['status']) && "0"==$_POST['status']) echo "selected=\"selected\""; ?> value="0">Inactive</option>
										</select>
									</div><!-- form-group -->
									
									<div class="form-group col-sm-4">
										<label for="role">User Role</label>
										<select  class="form-control" name="role" id="role" data-placeholder="Choose One">
											<option value="">Choose One</option>
											<?php
												$roledata = DB::query("SELECT id, role_name FROM peronnel_role");
												
												foreach($roledata as $userole)
												{
											?>
											<option <?php if(isset($_POST['role']) && ($userole['id'] == $_POST['role'])) echo "selected=\"selected\""; ?> value="<?php echo $userole['id']; ?>"><?php echo $userole['role_name']; ?></option>
											<?php
												}
											?>
										</select>
									</div><!-- form-group -->
									
									<div class="form-group col-sm-4">
										<label for="shop">User Shop</label>
										<select  class="form-control" name="shop" id="shop" data-placeholder="Choose One">
											<option value="">Choose One</option>
											<?php
												$shopsdata = DB::query("SELECT id, full_name FROM shop");
												
												foreach($shopsdata as $useshop)
												{
											?>
											<option <?php if(isset($_POST['shop']) && ($useshop['id'] == $_POST['shop'])) echo "selected=\"selected\""; ?> value="<?php echo $useshop['id']; ?>"><?php echo $useshop['full_name']; ?></option>
											<?php
												}
											?>
										</select>
									</div><!-- form-group -->
									</div>
								</div>
							</div>
						</div><!-- /.card-body -->
						
						<div class="card-footer">
							
							<div class="btn-list">
								<div class="text-right">
									<a href="systemusers.php" class="btn btn-danger"><i class="glyphicon glyphicon-remove"></i> Cancel</a>
									
									<button type="submit" name="savedatabtn" id="savedatabtn" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Save</button>
								</div>
							</div>
						</div><!-- /.card-footer-->
							</form>
						<?php
							}
							else
							{
						?>
						<div class="alert alert-danger alert-dismissable">
							<i class="glyphicon glyphicon-ban-circle"></i><br>
							Limited Access
						</div>
						<?php
							}
						?>
					</div><!-- /.card -->
				</section><!-- /.content -->
			</div><!-- /.content-wrapper -->

			 
		</div><!-- ./wrapper -->

			<?php include ('includes/general_footer.php')?>
		<!-- AdminLTE App -->
		<script src="dist/js/app.min.js" type="text/javascript"></script>
		<script src="plugins/bert/storepos.js" type="text/javascript"></script>
		
	</body>

</html>