
<?php 
/****** add new user */
if(ISSET($_POST['btn-save'])){
		
    try{
    $fname = trim($_POST['firstname']);
    $lname = trim($_POST['lastname']);
    $phone = trim($_POST['phone']);
    $role = $_POST['role'];
    $rank_id = $_POST['rank_name'];
    $title_id = $_POST['title_name'];
    $privilege = $_POST['privilege'];
    $status = 1;
    $email = trim($_POST['email']);
    $gender = $_POST['gender'];

    $reg_date = date("Y-m-d");
    $acc_priviledge = 1;
        
    $password = "System2022";
    $dir = ['cost' => 12];
    $hash = password_hash($password, PASSWORD_DEFAULT, $dir);
    $pass = $hash;
    // Fetch user role
    $select= $conn->prepare("SELECT * FROM tbl_role where role_id = $role ");
    $select->execute();
    while($row_1 = $select->fetch()) { $rl= $row_1['role_name'];}
        
    //for new user
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // chech if user exist
    $stmt = $conn->prepare(
    "SELECT * FROM tbl_user_accounts WHERE mobile_no ='".$phone."' ");
    $stmt->execute();
    $users = $stmt->fetchAll();
    foreach($users as $user){
    $e=$user['email'];}
    if($user['mobile_no']==$phone){
        $delete_msg=" The user with $phone already exist in a system!";
    }else{

    $sql211 = "SELECT * FROM  tbl_user_accounts";
    $stmt211 = $conn->query($sql211);
    $data = $stmt211->rowCount();
    while ($row1 = $stmt211->fetch()) {
    $user_id2=$row1['user_id'];
    }
    $user_id2 = $user_id2+1;
    $yr = date('Y');
    $acc_id1 = "ENG-".$user_id2;
    $user_email = $email;   
    $username = strtolower(substr($fname , 0,3)).substr($phone, -2);                 
        
        $usts = 1;
        $sgn = "1";            
          
           $insert = $db->prepare("INSERT INTO tbl_user_accounts(acc_id, first_name,family_name,mobile_no,user_email,user_role,gender,accc_log,user_status,user_reg_date,signature,registar)
            values(:accId, :fsName, :fmname, :mob, :mail, :rle, :gend, :acclg, :usts, :regdt, :sign, :regst)");
    
            $insert->bindParam(':accId', $acc_id1);
            $insert->bindParam(':fsName',  $fname);
            $insert->bindParam(':fmname',  $lname);
            $insert->bindParam(':mob', $phone);
            $insert->bindParam(':mail', $user_email);
            $insert->bindParam(':rle', $role);
            $insert->bindParam(':gend', $gender);
            $insert->bindParam(':acclg', $privilege);                
            $insert->bindParam(':usts', $usts);
            $insert->bindParam(':regdt', $reg_date);
            $insert->bindParam(':sign', $sgn);
            $insert->bindParam(':regst', $user_id);
            $insert->execute();

            $lastid = $db->lastInsertId();
        
        $sql = " INSERT INTO tbl_user_access(rank_id,title_id,login_id,fst_name,fmly_name,username,phone,email,password,u_role,privilege_id,institut_id,u_function,last_acc,status,date) 
        VALUES ('".$rank_id."','".$title_id."','".$acc_id1."','".$fname."','".$lname."','".$username."','".$phone."','".$user_email."','".$pass."','".$role."','".$privilege."','".$institut_id."','".$acc_priviledge."','".$lastid."','1','".$reg_date."')";
        $conn->exec($sql);
                   
         $g_email=$user_email;

        $msg="$fname registered successfully";
   }//Check Used

    }catch(PDOException $e){
        echo $e->getMessage();
    }
    
echo'<meta http-equiv="refresh"'.'content="3;URL=gate?b=mgeus">'; 
}
/****** end add new user */


// for activate user   	
if(isset($_REQUEST['acid']))
{
  
  try{
          $a = 1;
          $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          $sql = " UPDATE tbl_user_accounts SET user_status=1 WHERE user_id='".$_REQUEST['acid']."' ";
          $conn->exec($sql);

           /***** */
          $sql2 = " UPDATE tbl_user_access SET status=1 WHERE last_acc ='".$_REQUEST['acid']."' ";
          $conn->exec($sql2);
           /***** */
          $msg="Activated successfully";
      }catch(PDOException $e){
          echo $e->getMessage();
      }
   
    echo'<meta http-equiv="refresh"'.'content="2;URL=gate?b=mgeus">'; 
 }

// for Deactivate user
  else if(isset($_REQUEST['did']))
    {
    try{
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$sql = " UPDATE tbl_user_accounts SET user_status=0 WHERE user_id='".$_REQUEST['did']."' ";
			$conn->exec($sql);
            
            /***** */
			$sql2 = " UPDATE tbl_user_access SET status=0 WHERE last_acc='".$_REQUEST['did']."' ";
		 	$conn->exec($sql2);
           /***** */
           $msge="Deactivated successfully";
      }catch(PDOException $e){
          echo $e->getMessage();
      }
    echo'<meta http-equiv="refresh"'.'content="2;URL=gate?b=mgeus">'; 
  }

  ####### reset ######
  if(isset($_REQUEST['resetid'])){
    $reset = $_REQUEST['resetid'];
    $pwd = "System2022";
    $dir = ['cost' => 12];
    $hash = password_hash($pwd, PASSWORD_DEFAULT, $dir);
    $pass1 = $hash;
    $query = $db->prepare('UPDATE tbl_user_access SET password="'.$pass1.'" WHERE last_acc="'.$reset.'" ');
    $query->execute();
    if($query){
        $msg="Password reset successfully!";
    }    
    echo'<meta http-equiv="refresh"'.'content="2;URL=gate?b=mgeus">'; 
  } 

/***** delete user */
  if(ISSET($_POST['btn-delete'])){
    try{
        
        $delete_data = $_POST['del'];
        
        //for Deleting user
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = " DELETE FROM tbl_user_accounts WHERE user_id='$delete_data' ";
        $conn->exec($sql);
        $sql1 = " DELETE FROM tbl_user_access WHERE last_acc='$delete_data' ";
        $conn->exec($sql1);
        
        $delete_msg =" User has been deleted successfuly ";

    }catch(PDOException $e){
        echo $e->getMessage();
    }
    $msge="User data removed!";
    echo'<meta http-equiv="refresh"'.'content="3;URL=">'; 
 }
 /***** end delete user */

 /****** update user */
   
 if(ISSET($_POST['btn-update'])){
    //alert('update code goes here');
        $fname = trim($_POST['firstname']);
        $lname = trim($_POST['lastname']);
        $phone = trim($_POST['phone']);
        
        $email = trim($_POST['email']);
        $gender = $_POST['gender'];

        $usr_id = $_POST['usr_id'];

        $rank_id = $_POST['rank_id'];
        $role = $_POST['role'];
        $title_name = $_POST['title_name'];
        $privilege = $_POST['privilege'];


try {
    // update=====
$update = $db->prepare("UPDATE tbl_user_accounts SET family_name = '$fname', first_name = '$lname', user_email = '$email', mobile_no ='$phone',
 gender = '$gender',user_role='$role' WHERE tbl_user_accounts . user_id = $usr_id");

 ###### user access #####
$update1 = $db->prepare("UPDATE tbl_user_access SET rank_id='".$rank_id."',	fmly_name = '$fname', fst_name = '$lname', email = '$email',
 phone ='$phone',u_role='$role',title_id='$title_name',privilege_id='$privilege' WHERE tbl_user_access . last_acc = $usr_id ");
    }
    catch (PDOException $ex) {
        echo $ex->getMessage();
    }
if($update->execute() && $update1->execute()){
    $messave="User update Successfully";
}
else{$delete_msg=" Something Went Wrong!";
}
}
 /***** end update user */
?>


<div class="card mb-g border shadow-0">

    <div class="card-header bg-white p-0 header">
        <div class="p-3 d-flex flex-row">
            <div class="d-block ml-2">
                <span class="h6 font-weight-bold text-uppercase d-block m-0">
                    <?php echo $title;?> 
                </span>

                <?php 
                if(empty($_REQUEST['usrid'])){
                ?>
                <div class="d-flex mr-4">
                    <li class="position-absolute pos-top pos-right d-none d-sm-block"  style="padding: 10px;">
                        <button class="btn btn-primary" id="add-btn"><i class="fa fa-plus-circle"></i> Add</button>
                        <button class="btn btn-default" id="list-btn"><i class="fa fa-eye"></i> View List</button> 
                    </li>
                </div>
                <?php }?>
                <div class="clearfix"></div>  
            </div>
        </div>
    </div>

    <div class="card-body">
    
        <?php if(isset($msg)){?>
            <div class="alert alert-success alert-dismissable">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                <strong>Well Done!</strong> <?php echo htmlentities($msg); ?>
            </div>
            <?php }else if(isset($msge)){?>
            
            <div class="alert alert-danger alert-dismissable">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <strong>Oooh Snap!</strong> <?php echo htmlentities($msge); ?>
        </div>
        <?php }
        if(isset($_REQUEST['usrid'])){
            include 'editusr.php';
        }else{
        ?>
        <div id="table-result">
        <?php include 'listusers.php';?>
        </div>

        <div id="form-display" style="display: none;">
            <?php include 'userform.php';?>
        </div>
        <?php }?>
    </div>
</div>

<script>
    function getappoint(data0){
	//alert(data0);
	const ajaxreq =new XMLHttpRequest();
	ajaxreq.open('GET','../res/getVal?dept='+data0,'TRUE');
	ajaxreq.send();
	ajaxreq.onreadystatechange= function(){

		if (ajaxreq.readyState== 4 && ajaxreq.status == 200) {

			document.getElementById('appointid').
			innerHTML = ajaxreq.responseText;
		}
	}

	}
</script>

<script>
    $("#list-btn").hide();

    $(document).ready(function(){
    $("#add-btn").click(function(){
       $("#form-display").show();
       $("#table-result").hide();
       $("#list-btn").show();
       $("#add-btn").hide();
    });
    
    // SHOW PROJECT DETAILS
    
    $("#list-btn").click(function(){
       $("#form-display").hide();
       $("#table-result").show();
       $("#list-btn").hide();
       $("#add-btn").show();
    });
    });
</script>

