<?php 	

require_once '../../Server/connection.php';

$valid['success'] = array('success' => false, 'messages' => array());
//$valid['success'] = array('success' => false, 'messages' => array(), 'staff_id' => '');

if($_POST){	

  $FirstName = addslashes($_POST['FirstName']);
  $MiddleName = addslashes($_POST['MiddleName']);
  $LastName = addslashes($_POST['LastName']);
  $Email = addslashes(strtolower($_POST['Email']));
  $PhoneNumber = addslashes($_POST['PhoneNumber']);
  $deptId = $_POST['dept_id'];
  $roleId = $_POST['role_id'];
  
  $passwd = addslashes(strtoupper($LastName.'123'));
  $password = md5(addslashes(strtoupper($LastName.'123')));
  
  $link = "<a href='https://ems.edgeec.co.tz/'>EMS</a>"; 
  
  $fromEmail = 'info@edgeec.co.tz';
  $toEmail = $Email;
  
  $n = substr($PhoneNumber,1);
  $n1 = '255';
  $phone_number = $n1.$n;
  
  $staff_image = '../../staff_pictures/76327192860902d3d98acc.jpg';
  
   $message = "Hello"."&nbsp&nbsp".$FirstName."&nbsp&nbsp".$LastName."&nbsp&nbsp"."You have been registered into edge engineering Employee Management System - EMS, You will login using your email"."&nbsp&nbsp".$Email."&nbsp&nbsp"."and your default password will be"."&nbsp&nbsp".$passwd."&nbsp&nbsp"."You can change your password after login"."&nbsp&nbsp"."Please Click the following link to login into the System"."&nbsp&nbsp".$link;
   $subject = "User Account Creation";
  
 
				
				$sql = "INSERT INTO staff (firstname,middlename, lastname, email,phone_number,dept_id,staff_image) 
				VALUES ('$FirstName', '$MiddleName', '$LastName','$Email','$phone_number','$deptId','$staff_image')";
				
				
				//if(mysqli_query($conn, $sql) $conn->query($sql) === TRUE){
				if(mysqli_query($conn, $sql)){
					
				 //$staff_id = $conn->insert_id;
				 $staff_id = mysqli_insert_id($conn, $sql);
				 
				if($staff_id){
				$staffSql = "INSERT INTO users (staff_id,password,status,role_id,dept_id) 
				VALUES ('$staff_id','$password','1', '$roleId', '$deptId')";
				  }
				  
                  }


                //mail($toEmail,$subject,$message,"From:" . $fromEmail);
				//if($conn->query($staffSql) === TRUE) {
		
				if(mysqli_query($conn, $staffSql)) {
					
				//if(@mail($toEmail,$subject,$message,"From:" . $fromEmail)){	
					
					
					$valid['success'] = true;
					$valid['messages'] = "User is Successfully Registered";	
					
				//}	
					
				} else {
					$valid['success'] = false;
					$valid['messages'] = "Error while adding User";
				}

			

	

	$conn->close();

	echo json_encode($valid);
 
} // /if $_POST