<?php 
$email_exist = 0;
if (isset($_POST['save_emp']) || isset($_POST['save_manager']))
{
    include("db.php");
      
        $username   =   $_POST['username'];
        $password   =   md5($_POST['password']);
        if(isset($_POST['pwd_type']) && $_POST['pwd_type'] == 'mail'):
            $new_password   = generate_password(12); 
            $password       = md5($new_password);
        endif;
        $email      =   $_POST['email'];
        $phone      =   $_POST['phone'];
        $ename      =   $_POST['ename'];
        $comp       =   $_POST['comp'];
        $desc       =   $_POST['desc'];
        $type       =   $_POST['user_type'];
        $sel_man    =   $_POST['select_manager'];
        $fname      =   "";
        $time       =   date('Y-m-d h:i:s');

        $alredy_email = mysqli_query($conn, "SELECT * FROM db_users WHERE LOWER(email) LIKE '".strtolower($email)."' and company_name='".$comp."' ");
        if($alredy_email->num_rows != 0){
            echo "email exist";
            $email_exist = 1;
            die();
        }

        if(isset($_FILES['eimage']['name']) && !empty($_FILES['eimage']['name'])){

            $rawBaseName = pathinfo($_FILES['eimage']['name'], PATHINFO_FILENAME );
            $extension = pathinfo($_FILES['eimage']['name'], PATHINFO_EXTENSION );
            $counter = 0;
            $fname = basename($_FILES["eimage"]["name"]);

            $doc_root = $_SERVER['DOCUMENT_ROOT'];
            if (strpos($_SERVER['REQUEST_URI'], 'timesheet_new') !== false) {
                $doc_root = $_SERVER['DOCUMENT_ROOT']."/timesheet_new";
                
            }
            while(file_exists($doc_root."/dist/assets/profile/".$fname)) {
                $fname = $rawBaseName . $counter . '.' . $extension;
                $counter++;
            }
           
            move_uploaded_file($_FILES['eimage']['tmp_name'], $doc_root."/dist/assets/profile/".$fname);
            

        }
        
        
        if($alredy_email->num_rows == 0){
            $query = "insert into db_users(username, password, email,phone,full_name,company_name,selected_manager, description,profile_img,type,date_time) values ('$username', '$password', '$email', '$phone','$ename', '$comp', '$sel_man', '$desc', '$fname', '$type', '$time' )";
            $sql=mysqli_query($conn,$query);
            if($sql && $_POST['pwd_type'] == 'mail'){
                $comp_domain = get_user_by_id($comp)['username'];
                $msg = "Profile created successfully on $site_url. <br>Here is login details<br><br> <b>Company Domain :</b> $comp_domain<br><b>Email : </b> $email<br><b>Password : </b> $new_password <br> <small>(Note: Above Password is system generated. You can login here and reset your password : <a hre='".$site_url."'>$site_url</a>)</small><br><br> Regards,<br> Timesheethub.";
                send_zoho_mail($email,"System Generated Password",$msg);
            } else {
                $comp_domain = get_user_by_id($comp)['username'];
                $msg = "Profile created successfully on $site_url. <br>Here is login details<br><br> <b>Company Domain :</b> $comp_domain<br><b>Email : </b> $email<br><b>Password : </b> ".$_POST['password']." <br><br> Regards,<br> Timesheethub.";
                send_zoho_mail($email,"Profile Created Successfully on $site_url",$msg);
            }
        } 
        die();
        
        
}
    include("header.php"); 
    
    $edit_ename = '';
    $edit_comp  = '';
    $edit_manger= '';
    $edit_img   = '';
    $edit_uname = '';
    $edit_pwd   = '';
    $edit_email = '';
    $edit_phone = '';
    $edit_desc  = '';
    $emp_id     = '';
    $edit_type  = '';

    if(isset($_POST['save_new_pwd'])){
        if($_POST['new_pwd'] == $_POST['cnf_pwd']){
             $emp_list = mysqli_query($conn, "UPDATE db_users SET password='".md5($_POST['new_pwd'])."' where id='".$_POST['hidden_user_id']."' ");
             $u_info = get_user_by_id($_POST['hidden_user_id']);
             $msg = 'Hello '.ucwords($u_info['full_name']).'<br><br> You have successfully reset password on '.$site_url.'. <br><br><b>Note:</b> if not reset by you then immediadtly visit site and reset password again to prevent unauthorize access. Regards,<br> Timesheethub.';
             send_zoho_mail($u_info['email'],"Password Reset Successfully!!",$msg);
        }
    }
    if(isset($_POST['action']) && $_POST['action'] == 'edit_profile' && $_POST['edit_id']){

        $single_emp = mysqli_fetch_assoc(mysqli_query($conn, "select * from db_users where id=".$_POST['edit_id']));


        $edit_ename = $single_emp['full_name'];
        $edit_comp  = $single_emp['company_name'];
        $edit_img   = $single_emp['profile_img'];
        $edit_uname = $single_emp['username'];
        $edit_email = $single_emp['email'];
        $edit_phone = $single_emp['phone'];
        $edit_desc  = $single_emp['description'];
        $emp_id     = $_POST['edit_id'];
        $edit_manger= $single_emp['selected_manager'];
        $edit_type  = $single_emp['type'];
    }
    if(isset($_POST['action']) && $_POST['action'] == 'del_profile' && $_POST['del_id']){
        mysqli_query($conn, "delete from db_users where id=".$_POST['del_id']);
    }
    if(isset($_POST['update_emp']) && !empty($_POST['emp_id'])){

        if(isset($_FILES['eimage']['name']) && !empty($_FILES['eimage']['name'])){

            $rawBaseName = pathinfo($_FILES['eimage']['name'], PATHINFO_FILENAME );
            $extension = pathinfo($_FILES['eimage']['name'], PATHINFO_EXTENSION );
            $counter = 0;
            $fname = basename($_FILES["eimage"]["name"]);

            $doc_root = $_SERVER['DOCUMENT_ROOT'];
            if (strpos($_SERVER['REQUEST_URI'], 'timesheet_new') !== false) {
                $doc_root = $_SERVER['DOCUMENT_ROOT']."/timesheet_new";
                
            }
            while(file_exists($doc_root."/dist/assets/profile/".$fname)) {
                $fname = $rawBaseName . $counter . '.' . $extension;
                $counter++;
            }
           
            move_uploaded_file($_FILES['eimage']['tmp_name'], $doc_root."/dist/assets/profile/".$fname);
            

        }

        $query = "update db_users set username='".$_POST['username']."', email='".$_POST['email']."', phone='".$_POST['phone']."', full_name='".$_POST['ename']."' ,company_name='".$_POST['comp']."' ,description='".$_POST['desc']."' ,type='".$_POST['user_type']."', profile_img='".$fname."' where id=".$_POST['emp_id'];

        $sql=mysqli_query($conn,$query);

    }
    
 
    $company_list = mysqli_query($conn, "select * from db_users where type='company' ");

     
   /* if(!$_SESSION['email'])  
    {  
      
        header("Location: index.php");
    }  */
  
?>


            <!-- Body: Body -->  
            <style type="text/css">
                .mb-3.manager-inner {
                    display: flex;
                    flex-wrap: wrap;
                    justify-content: space-between;
                    align-items: flex-end;
                }
                .manager-itm {
                    width: 80%;
                }

                @media(max-width:991px){
                    .manager-itm {
                        width: 100%;
                    }
                    .manager-btn, .edit-manager {
                        margin-top: 12px;
                    }
                }
                span.email_error {
                    color: red;
                }
            </style>     
            <div class="body d-flex py-lg-3 py-md-2">
                <div class="container-xxl">
                    <div class="row align-items-center">
                        <div class="border-0 mb-4">
                            <div class="card-header py-3 no-bg bg-transparent d-flex align-items-center px-0 justify-content-between border-bottom flex-wrap">
                                <?php 
                                $list_txt = 'Users List';
                                if(isset($_GET['filter_user']) && $_GET['filter_user'] == 'emp'){
                                    $list_txt = 'Employee List';
                                } else if(isset($_GET['filter_user']) && $_GET['filter_user'] == 'man') {
                                    $list_txt = 'Manager List';
                                }

                                ?>
                                <h3 class="h4 mb-0"><?= $list_txt; ?></h3>
                                <div class="col-auto d-flex w-sm-100 mt-2 mt-sm-0">
                                    <?php   
                                    if($emp_list['type'] == 'admin' || $emp_list['type'] == 'company'){ 
                                        $btn_txt = 'Add User';
                                        if(isset($_GET['filter_user']) && $_GET['filter_user'] == 'emp'){
                                            $btn_txt = 'Add Employee';
                                        } else if(isset($_GET['filter_user']) && $_GET['filter_user'] == 'man') {
                                            $btn_txt = 'Add Manager';
                                        }

                                    ?>
                                    <button type="button" class="btn btn-dark btn-set-task w-sm-100" data-bs-toggle="modal" data-bs-target="#addemp"><i class="icofont-plus-circle me-2 fs-6"></i><?= $btn_txt; ?></button>
                                <?php } ?>
                                </div>
                            </div>
                        </div>
                    </div> <!-- Row end  -->
                    <div class="row clearfix g-3">
                    <div class="col-sm-12">
                        <div class="card mb-3">
                            <div class="card-body">
                                <?php
                                    if($email_exist == 1){
                                        echo "<span style='color:red;'>Email already exist.</span>";
                                    }
                                ?>
                                <table id="myProjectTable" class="table table-hover align-middle mb-0" style="width:100%">
                                    <thead>
                                        <tr>
                                            <th><span class="table-heading">Employee Name</span></th>
                                            <th><span class="table-heading">Type</span></th>
                                            <th><span class="table-heading">Company</span></th>
                                            <th><span class="table-heading">Email</span></th>
                                            <th><span class="table-heading">Created On</span></th>
                                           
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                            $all_users = mysqli_query($conn, "select * from db_users ");
                                            if(isset($_GET['filter_user']) && !empty($_GET['filter_user'])){
                                                if($_GET['filter_user'] == 'emp'){
                                                    $all_users = mysqli_query($conn, "select * from db_users WHERE type='employee' ");
                                                }
                                                if($_GET['filter_user'] == 'man'){
                                                    $all_users = mysqli_query($conn, "select * from db_users WHERE type='manager' ");
                                                }
                                            }
                                            
                                            if(!empty($all_users)){
                                                while($res = mysqli_fetch_array($all_users)):
                                                    $comp_name = '-';
                                                    if(!empty($res['company_name'])):
                                                        $get_company = mysqli_fetch_assoc(mysqli_query($conn, "select * from db_users where id=".$res['company_name']));
                                                        $comp_name = $get_company['username'];
                                                    endif;
                                                    if($res['type'] == 'company'):
                                                        $comp_name = $res['username'];
                                                    endif;
                                                    
                                                    $pro_img = '';
                                                    $show_img = !empty($res['profile_img']) ? $site_url.'dist/assets/profile/'.$res['profile_img'] : $site_url.'assets/images/xs/avatar1.svg';
                                                echo '<tr>
                                                   <td>
                                                       <img class="avatar rounded-circle" src="'.$show_img.'" alt="">
                                                       <span class="fw-bold ms-1">'.$res['full_name'].'</span>
                                                   </td>
                                                   <td>
                                                       '.$res['type'].'
                                                   </td>
                                                   <td>
                                                        '.$comp_name .'
                                                   </td>
                                                   <td>
                                                        <a href="mailto:'.$res['email'].'">'.$res['email'].'</a>
                                                   </td>
                                                   <td>
                                                        '.date('d/m/y', strtotime($res['date_time'])).'
                                                   </td>
                                                   
                                                    <td>
                                                        <div class="btn-group" role="group" aria-label="Basic outlined example">
                                                            <button type="button" class="btn btn-outline-secondary edit-btn" data-id="'.$res['id'].'"><i class="icofont-edit text-success"></i></button>
                                                            <button type="button" class="btn btn-outline-secondary deleterow" data-id="'.$res['id'].'"><i class="icofont-ui-delete text-danger"></i></button>
                                                        </div>
                                                    </td>
                                                </tr>';
                                            endwhile;
                                            }
                                        ?>
                                        
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    </div><!-- Row End -->
                </div>
            </div>
            <!-- Create Employee-->
           <div class="modal fade" id="addemp" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-lg modal-dialog-scrollable">
                    <div class="modal-content">
                        <div class="modal-header">
                            <?php 
                                $hd_text = 'Add User';
                                if(isset($_GET['filter_user']) && $_GET['filter_user'] == 'emp'){
                                    $hd_text = 'Add Employee';
                                } else if(isset($_GET['filter_user']) && $_GET['filter_user'] == 'man') {
                                    $hd_text = 'Add Manager';
                                }
                            ?>
                            <h5 class="modal-title  fw-bold" id="createprojectlLabel"> <?= $hd_text; ?></h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body"> 
                        
                             <form name="f1" method="POST" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label for="exampleFormControlInput877" class="form-label">Full Name</label>
                                <input type="text" name="ename" class="form-control" id="exampleFormControlInput877" placeholder="Full Name Here" required="" onkeydown="if(/[a-z ]/i.test(event.key) == false || (event.which === 32 && event.target.selectionStart === 0)) {return false; } ">
                            </div>

                            <div class="mb-3 " >
                                
                                    <label for="user_type" class="form-label">User Type</label>
                                <select name="user_type" required="" class="form-control form-select" id="user_type">
                                    <option value=""> --- Select Type --- </option>
                                    <option value="admin"> Admin </option>
                                    <!-- <option value="company"> Company </option> -->
                                    <option value="employee" <?= (isset($_GET['filter_user']) && $_GET['filter_user'] == 'emp') ? "selected" : ""; ?>> Employee </option>
                                    <option value="manager" <?= (isset($_GET['filter_user']) && $_GET['filter_user'] == 'man') ? "selected" : ""; ?>> Manager </option>
                                </select>
                                
                                
                            </div>

                            <div class="mb-3 company_dropdown" style="display: none;">
                                <label for="exampleFormControlInput977" class="form-label">User Company</label>
                                 <select name="comp" required="" class="form-control form-select" readonly>
                                    <option value=""> --- Select Company --- </option>
                                    <?php
                                        while($single_co = mysqli_fetch_array($company_list)){
                                            echo '<option value="'.$single_co['id'].'">'.$single_co['username'].'</option>';
                                        }
                                    ?>
                                </select>
                            </div>
                            <?php
                               $m_style = '';
                               $m_readonly = '';
                                if($_GET['filter_user'] == 'man'){
                                    $m_style = 'style="display:none;"';
                                    $m_readonly = 'readonly';
                                }
                            ?>
                            <div class="mb-3 manager-inner" style="display:none;">
                                <div class="manager-itm">
                                    <label for="select_manager" class="form-label">Manager</label>
                                <select name="select_manager" required="" class="form-control form-select" id="select_manager" <?= $m_readonly; ?> >
                                    <option value=""> --- Select Manager --- </option>
                                    <?php
                                        $manager_list = mysqli_query($conn, "select * from db_users where type='manager' ");
                                        while($edit_single_man = mysqli_fetch_array($manager_list)){
                                            
                                            
                                            echo '<option value="'.$edit_single_man['id'].'">'.$edit_single_man['full_name'].'</option>';
                                        }
                                    ?>
                                    
                                </select>
                                </div>
                                
                                <div class="manager-btn">
                                     <button type="button" class="manager-button btn btn-dark btn-set-task w-sm-100" data-bs-toggle="modal" data-bs-target="#manager"><i class="icofont-plus-circle me-2 fs-6"></i>Add Manager</button>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="formFileMultipleoneone" class="form-label">User Image</label>
                                <input class="form-control" name="eimage" type="file" id="formFileMultipleoneone"  accept="image/jpg, image/jpeg, image/png" onchange="return fileValidation(this);">
                            </div>
                          <div class="deadline-form">
                              <div class="row mb-3">  
                           
                                <div class="col">
                                    <label for="exampleFormControlInput177" class="form-label">Password Prefence:</label> 
                                        <label class="pwd-pref">
                                            <input type="radio" name="pwd_type" class="pwd_type" value="manually" checked="">
                                            Set Manually
                                        </label>
                                        <label class="pwd-pref">
                                            <input type="radio" name="pwd_type" class="pwd_type" value="mail">
                                            Sent in Mail
                                        </label>
                                </div>
                            </div>
                               
                            
                            <div class="row g-3 mb-3">
                                <div class="col">
                                    <label for="exampleFormControlInput177" class="form-label">User Name</label>
                                    <input type="text" name="username" class="form-control" id="exampleFormControlInput177" placeholder="User Name" required="" autocomplete="new-username" onkeydown="return /[A-Za-z]/i.test(event.key);">
                                </div>
                                <div class="col">
                                    <label for="exampleFormControlInput277" class="form-label">Password</label>
                                    
                                    <div class="password-text">
                                        <input type="Password" name="password" class="form-control pwd-manually" id="exampleFormControlInput277" placeholder="Password" required="" autocomplete="new-password" onkeyup="checkPasswordStrength(this);">
                                        
                                        <i class="icofont-eye pwd-toggle"></i>
                                        <div id="password-strength-status"></div>
                                    </div>
                                    <span class="pwd-mail" style="display:none;">System Generated Password will be sent to user email id.</span>
                                </div>
                            </div> 
                            <div class="row g-3 mb-3">
                                <div class="col">
                                    <label for="exampleFormControlInput477" class="form-label">Email ID</label>
                                    <input type="email" name="email" class="form-control" id="exampleFormControlInput477" placeholder="Email Address" required="">
                                    <span class="email_error" style="display:none">Email Already Exist.</span>
                                </div>
                            <div class="col">
                                    <label for="exampleFormControlInput777" class="form-label">Phone</label>
                                    <input type="text" name="phone" class="form-control" id="exampleFormControlInput777" placeholder="Phone Number" maxlength="10" required="" onkeypress="return onlyNumberKey(event)" >
                                </div>
                            </div>
                              
                                
                        </div> 
                          <div class="mb-3">          
                                <label for="exampleFormControlTextarea78" class="form-label">Description (optional)</label>
                                <textarea class="form-control" name="desc" id="exampleFormControlTextarea78" rows="3" placeholder="Add any extra details about employee"></textarea>
                            </div> 
                            
                            <input type="submit" name="save_emp" class="save_emp" style="display: none;">
                           
                            </form>
                        </div>
                     <div class="modal-footer">
                            <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Done</button> -->
                            <button type="submit" class="btn btn-primary" name="submit" value="submit">Create</button>
                            <button type="button" class="btn btn-primary clear-btn">Clear</button>
                        </div> 
                    </div>  
                </div>
            </div>

             <!-- Edit Employee-->
           <div class="modal fade" id="editemp" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-lg modal-dialog-scrollable">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title  fw-bold" id="createprojectlLabel"> Edit User</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body"> 
                        
                             <form name="f1" method="POST" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label for="exampleFormControlInput877" class="form-label">Full Name</label>
                                <input type="text" name="ename" class="form-control" id="exampleFormControlInput877" placeholder="Full Name Here" required="" value="<?= $edit_ename; ?>" onkeydown="if(/[a-z ]/i.test(event.key) == false || (event.which === 32 && event.target.selectionStart === 0)) {return false; }">
                            </div>
                            
                             <div class="mb-3" <?= $style; ?> >
                                <label for="user_type" class="form-label">User Type</label>
                                <select name="user_type" required="" class="form-control form-select" id="user_type" required="">
                                    <option value=""> --- Select Type --- </option>
                                    <?php  
                                        if($edit_type == 'manager'){
                                            echo '<option value="manager" selected> Manager </option>';
                                        } else {
                                    ?>
                                        <option value="admin" <?= ($edit_type == 'admin') ? 'selected' : ''; ?> > Admin </option>
                                        <option value="company" <?= ($edit_type == 'company') ? 'selected' : ''; ?> > Company </option>
                                        <option value="employee" <?= ($edit_type == 'employee') ? 'selected' : ''; ?> > Employee </option>
                                     <?php  
                                        }
                                    ?>
                                </select>
                                
                            </div>
                            <?php
                                $style = '';
                                $readonly = '';
                                if($edit_type != 'employee'){
                                    $style = 'style="display:none;"';
                                    $readonly = 'readonly';
                                }
                                $m_style = '';
                                $m_readonly = '';
                                if($edit_type != 'company'){
                                    $m_style = 'style="display:none;"';
                                    $m_readonly = 'readonly';
                                }

                            ?>
                            <div class="mb-3" style="display:none;">
                                <label for="exampleFormControlInput977" class="form-label">User Company</label>
                                <select name="comp" required="" class="form-control form-select" readonly>
                                    <option value=""> --- Select Company --- </option>
                                    <?php
                                        $company_list = mysqli_query($conn, "select * from db_users where type='company' ");
                                        while($edit_single_co = mysqli_fetch_array($company_list)){
                                            $selected = ($edit_comp == $edit_single_co['id'] ) ? "selected" : "";
                                            
                                            echo '<option value="'.$edit_single_co['id'].'" '.$selected.'>'.$edit_single_co['full_name'].'</option>';
                                        }
                                    ?>
                                </select>
                                <!-- <input type="text" name="comp" class="form-control" id="exampleFormControlInput977" placeholder="Company Name" required="" value="<?= $edit_comp; ?>"> -->
                            </div>
                            <div class="mb-3 manager-inner" <?= $m_style; ?>>
                                <div class="manager-itm">
                                    <label for="select_manager" class="form-label">Manager</label>
                                <select name="select_manager" required="" class="form-control form-select" id="select_manager" <?= $m_readonly; ?>>
                                    <option value=""> --- Select Manager --- </option>
                                    <?php
                                        $manager_list = mysqli_query($conn, "select * from db_users where type='manager' ");
                                        while($edit_single_man = mysqli_fetch_array($manager_list)){
                                            $selected = ($edit_manger == $edit_single_man['id'] ) ? "selected" : "";
                                            
                                            echo '<option value="'.$edit_single_man['id'].'" '.$selected.'>'.$edit_single_man['full_name'].'</option>';
                                        }
                                    ?>
                                </select>
                                </div>
                                
                                <div class="manager-btn">
                                     <button type="button" class="manager-button btn btn-dark btn-set-task w-sm-100" data-bs-toggle="modal" data-bs-target="#manager"><i class="icofont-plus-circle me-2 fs-6"></i>Add Manager</button>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="formFileMultipleoneone" class="form-label">User Image</label>
                                <input class="form-control" name="eimage" type="file" id="formFileMultipleoneone" accept="image/jpg, image/jpeg, image/png" onchange="return fileValidation(this);">
                                <input type="hidden" name="old_img_name" value="<?= $edit_img; ?>">
                            </div>
                          <div class="deadline-form">
                               
                            
                            <div class="row g-3 mb-3">
                                <div class="col">
                                    <label for="exampleFormControlInput177" class="form-label">User Name</label>
                                    <input type="text" name="username" class="form-control" id="exampleFormControlInput177" placeholder="User Name" required="" autocomplete="new-username" value="<?= $edit_uname; ?>" onkeydown="return /[A-Za-z]/i.test(event.key);">
                                </div>
                                <!-- <div class="col">
                                    <label for="exampleFormControlInput277" class="form-label">Password</label>
                                    <input type="Password" name="password" class="form-control" id="exampleFormControlInput277" placeholder="Password" required="" autocomplete="new-password">
                                </div> -->
                            </div> 
                            <div class="row g-3 mb-3">
                                <div class="col">
                                    <label for="exampleFormControlInput477" class="form-label">Email ID</label>
                                    <input type="email" name="email" class="form-control" id="exampleFormControlInput477" placeholder="Email Address" required="" value="<?= $edit_email; ?>">
                                </div>
                            <div class="col">
                                    <label for="exampleFormControlInput777" class="form-label">Phone</label>
                                    <input type="text" name="phone" class="form-control" id="exampleFormControlInput777" placeholder="Phone Number" maxlength="10" required="" value="<?= $edit_phone; ?>" onkeypress="return onlyNumberKey(event)">
                                </div>
                            </div>
                              
                                
                        </div> 
                          <div class="mb-3">          
                                <label for="exampleFormControlTextarea78" class="form-label">Description (optional)</label>
                                <textarea class="form-control" name="desc" id="exampleFormControlTextarea78" rows="3" placeholder="Add any extra details about employee"></textarea>
                            </div> 
                            <p><u class="reset_u" data-id="<?= $emp_id; ?>" style="cursor: pointer;">Reset Password here</u></p>
                        
                            <input type="hidden" name="emp_id" value="<?= $emp_id; ?>">
                            <input type="submit" name="update_emp" class="update_emp" style="display: none;">
                           
                            </form>
                        </div>
                        <div class="modal-footer">
                            <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Done</button> -->
                            <button type="submit" class="btn btn-primary" name="update_profile" value="Update" onclick="$('.update_emp').click();">Update</button>
                            <button type="button" class="btn btn-primary clear-btn" >Clear</button>

                        </div> 
                    </div>  
                </div>
            </div>

            <div class="modal fade" id="manager" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-lg modal-dialog-scrollable">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title  fw-bold" id="createprojectlLabel"> Add Manager</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body"> 
                        
                             <form name="f1" method="POST" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label for="exampleFormControlInput877" class="form-label">Full Name</label>
                                <input type="text" name="ename" class="form-control" id="exampleFormControlInput877" placeholder="Full Name Here" required="" onkeydown="if(/[a-z ]/i.test(event.key) == false || (event.which === 32 && event.target.selectionStart === 0)) {return false; }">
                            </div>

                            <div class="mb-3">
                                <label for="formFileMultipleoneone" class="form-label">User Image</label>
                                <input class="form-control" name="eimage" type="file" id="formFileMultipleoneone" accept="image/jpg, image/jpeg, image/png" onchange="return fileValidation(this);">
                            </div>
                          <div class="deadline-form">
                               
                            
                            <div class="row g-3 mb-3">
                                <div class="col">
                                    <label for="exampleFormControlInput177" class="form-label">User Name</label>
                                    <input type="text" name="username" class="form-control" id="exampleFormControlInput177" placeholder="User Name" required="" autocomplete="new-username" onkeydown="return /[A-Za-z]/i.test(event.key);">
                                </div>
                                <div class="col">
                                    <label for="exampleFormControlInput277" class="form-label">Password</label>
                                    <input type="Password" name="password" class="form-control" id="exampleFormControlInput277" placeholder="Password" required="" autocomplete="new-password">
                                    <i class="icofont-eye pwd-toggle"></i>
                                </div>
                            </div> 
                            <div class="row g-3 mb-3">
                                <div class="col">
                                    <label for="exampleFormControlInput477" class="form-label">Email ID</label>
                                    <input type="text" name="email" class="form-control" id="exampleFormControlInput477" placeholder="Email Address" required="">
                                </div>
                            <div class="col">
                                    <label for="exampleFormControlInput777" class="form-label">Phone</label>
                                    <input type="text" name="phone" class="form-control" id="exampleFormControlInput777" placeholder="Phone Number" maxlength="10" required="" onkeypress="return onlyNumberKey(event)">
                                </div>
                            </div>
                              
                                
                        </div> 
                          <div class="mb-3">          
                                <label for="exampleFormControlTextarea78" class="form-label">Description (optional)</label>
                                <textarea class="form-control" name="desc" id="exampleFormControlTextarea78" rows="3" placeholder="Add any extra details about employee"></textarea>
                            </div> 
                            <input type="hidden" name="user_type" value="manager">
                            <input type="submit" name="save_manager" class="save_manager" style="display: none;">
                           
                            </form>
                        </div>
                        <div class="modal-footer">
                            <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Done</button> -->
                            <button type="submit" class="btn btn-primary" name="update_profile" onclick="$('.save_manager').click();"> Add Manager</button>
                            <button type="button" class="btn btn-primary clear-btn">Clear</button>
                        </div> 
                    </div>  
                </div>
            </div>
            <div class="modal fade" id="reset_password" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-lg modal-dialog-scrollable">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title  fw-bold" id="createprojectlLabel"> Reset Password</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body"> 
                        
                             <form name="f2" method="POST">
                                <div class="mb-3">
                                    <label for="FormNewPwd" class="form-label">New Password</label>
                                    <input type="password" name="new_pwd" class="form-control" id="FormNewPwd" placeholder="New Password Here" required="" onkeyup="checkPasswordStrength(this);">
                                    <i class="icofont-eye pwd-toggle"></i>
                                    <div id="password-strength-status"></div>
                                </div>

                                <div class="mb-3">
                                    <label for="formConfirmPwd" class="form-label">Confirm Password</label>
                                    <input class="form-control" name="cnf_pwd" type="password" id="formConfirmPwd" placeholder="Confirm Password Here" required="" onkeyup="checkPasswordStrength(this);">
                                    <i class="icofont-eye pwd-toggle"></i>
                                    <div id="password-strength-status"></div>
                                </div>
                          
                            <input type="hidden" name="hidden_user_id" value="">
                            <input type="submit" name="save_new_pwd" class="save_new_pwd" style="display: none;">
                           
                            </form>
                        </div>
                        <div class="modal-footer">
                            <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Done</button> -->
                            <button type="submit" class="btn btn-primary" name="update_profile" onclick="$('.save_new_pwd').click();"> Save</button>
                            <button type="button" class="btn btn-primary clear-btn">Clear</button>
                        </div> 
                    </div>  
                </div>
            </div>


            <style type="text/css">
            .form-control[name="password"], .form-control[name="cnf_pwd"], .form-control[name="new_pwd"] {
                width: 94%;
                display: inline-block;
                border-right: 0px;
                border-radius: 0.25rem 0px 0px 0.25rem;
            }
            i.pwd-toggle {
                padding: 11px 6px 9px 0px;
                cursor: pointer;
                background: #fff;
                margin-left: -5px;
                border: 1px solid #f0f0f0;
                border-left: 0px;
                border-radius: 0px 0.25rem 0.25rem 0px;
            }
            .form-control:focus + i.pwd-toggle {
                /* box-shadow: 0 0 10px rgb(33 37 41 / 15%); */
                background-color: var(--card-color);
                border-color: var(--primary-color);
            }
            @media(max-width:768px){
                .form-control[type="Password"] {
                width: 94% !important;
            }
            }
            .modal-body {
                padding-top: 25px;
            }
            div#reset_password .modal-content {
                width: 75%;
            }
            .spinner-border {
                z-index: 99999;
                position: fixed;
                top: 50%;
                left: 50%;
            }
            table.dataTable thead .sorting::before,
            table.dataTable thead .sorting_asc::before,
            table.dataTable thead .sorting_desc::before,
            table.dataTable thead .sorting_asc_disabled::before,
            table.dataTable thead .sorting_desc_disabled::before {
                content: "";
            }
             
            table.dataTable thead .sorting::after,
            table.dataTable thead .sorting_asc::after,
            table.dataTable thead .sorting_desc::after,
            table.dataTable thead .sorting_asc_disabled::after,
            table.dataTable thead .sorting_desc_disabled::after {
                content: "";
            }  
</style>
<div class="spinner-border float-right" role="status" style="display:none;">
    <span class="sr-only">Loading...</span>
</div>
<?php include("footer.php"); ?>
<script type="text/javascript">
        jQuery(document).on("click",".edit-btn", function(){
            jQuery("#editemp").modal('show');
            var edit_id = jQuery(this).attr("data-id");
            jQuery.ajax({
                type:"post",
                url:"",
                data:{action:"edit_profile",edit_id:edit_id},
                success:function(res){
                    jQuery('#editemp').html(jQuery(res).find('#editemp').html());
                }
            });
        });
        jQuery(document).on("click", '.deleterow',function(){
            var tablename = $(this).closest('table').DataTable();  
            var del_id = jQuery(this).attr("data-id");
            jQuery(".spinner-border").show();
            if(confirm("Are you sure?")){
                 jQuery.ajax({
                    type:"post",
                    url:"",
                    data:{action:"del_profile",del_id:del_id},
                    success:function(res){
                        jQuery('#editemp').html(jQuery(res).find('#editemp').html());
                        jQuery(".spinner-border").hide();
                    }
                });

                tablename.row( $(this).parents('tr') ).remove().draw();
            }    

        });

        jQuery(document).on("click",".manager-button", function(){
            jQuery("#manager").modal('show');
            var edit_id = jQuery(this).attr("data-id");
            jQuery.ajax({
                type:"post",
                url:"",
                data:{action:"edit_profile",edit_id:edit_id},
                success:function(res){
                    jQuery('#manager').html(jQuery(res).find('#manager').html());
                }
            });
        });
        /*jQuery(document).on("click", '.deleterow',function(){
            var tablename = $(this).closest('table').DataTable();  
            var del_id = jQuery(this).attr("data-id");
            if(confirm("Are you sure?")){
                 jQuery.ajax({
                    type:"post",
                    url:"",
                    data:{action:"del_profile",del_id:del_id},
                    success:function(res){
                        //jQuery('#manager').html(jQuery(res).find('#manager').html());
                    }
                });

                tablename.row( $(this).parents('tr') ).remove().draw();
            }    

        });*/


        // jQuery(document).on("click",".edit-manager", function(){
        //     jQuery("#editmanager").modal('show');
        //     var edit_id = jQuery(this).attr("data-id");
        //     jQuery.ajax({
        //         type:"post",
        //         url:"",
        //         data:{action:"edit_profile",edit_id:edit_id},
        //         success:function(res){
        //             jQuery('#editmanager').html(jQuery(res).find('#editmanager').html());
        //         }
        //     });
        // });
        /*jQuery(document).on("click", '.deleterow',function(){
            var tablename = $(this).closest('table').DataTable();  
            var del_id = jQuery(this).attr("data-id");
            if(confirm("Are you sure?")){
                 jQuery.ajax({
                    type:"post",
                    url:"",
                    data:{action:"del_profile",del_id:del_id},
                    success:function(res){
                        jQuery('#editmanager').html(jQuery(res).find('#editmanager').html());
                    }
                });

                tablename.row( $(this).parents('tr') ).remove().draw();
            }    

        });*/

        jQuery(document).on("change", 'select[id="user_type"]', function(){
    
           if(jQuery(this).val() == 'employee' || jQuery(this).val() == 'manager'){
               
               jQuery(this).closest("form").find('.manager-inner').hide();
               jQuery(this).closest("form").find('#select_manager').attr('readonly','');
               if(jQuery("body").hasClass("login-as-admin")){
                  
                    jQuery(this).closest("form").find(".company_dropdown").show();
                    jQuery(this).closest("form").find(".company_dropdown").find('select').removeAttr('readonly');
                }
               

           } else if(jQuery(this).val() == 'company'){

                jQuery(this).closest(".mb-3").next('div').hide();
                jQuery(this).closest(".mb-3").next('div').find('select').attr('readonly','');
                jQuery(this).closest("form").find('.manager-inner').show();
                jQuery(this).closest("form").find('#select_manager').removeAttr('readonly');
                
           } else {

                jQuery(this).closest(".mb-3").next('div').hide();
                jQuery(this).closest("form").find('.manager-inner').hide();
                jQuery(this).closest("form").find('#select_manager').attr('readonly','');
                jQuery(this).closest(".mb-3").next('div').find('select').attr('readonly','');
           }

        });
        jQuery(document).on('click', '.reset_u', function(){
            jQuery("#reset_password").modal('show');
            jQuery("#reset_password input[name='hidden_user_id']").val(jQuery(this).attr('data-id'));
        });
        jQuery(document).on('show.bs.modal', '#addemp', function(){
            jQuery("select#user_type").change();
        });
        jQuery(document).on("click", "#addemp button[name='submit']", function(){
            let valid = true;
            jQuery('#addemp form [required]:not([readonly])').each(function() {
                if (jQuery(this).is(':invalid') || !jQuery(this).val()) valid = false;
            });
            var pwd = $(this).closest(".modal-content").find("input[name='password']");
    
            if (!valid){
                 jQuery('.save_emp').click();
            } else if(!checkPasswordStrength(pwd) && $(this).closest(".modal-content").find("input[name='password']:visible").length){

                alert("Password Must be strong.");

            } else {
                jQuery(".spinner-border").show();
                var form_arr = new FormData(jQuery("#addemp form")[0]);
                form_arr.append('save_emp',1);
                
                jQuery.ajax({
                    type:"post",
                    url:window.location.pathname,
                    data:form_arr,
                    contentType: false,
                    cache: false,
                    processData:false,
                    success:function(res){
                        if(res == 'email exist'){
                            jQuery(".email_error").show();
                        } else {
                            jQuery(".email_error").hide();
                            jQuery("#addemp").modal('hide');
                            window.location.href = window.location.pathname;
                            //location.reload();
                        }
                        jQuery(".spinner-border").hide();
                    }

                });
              }
            
         });
        jQuery(document).on("click", "button.clear-btn", function(){
               jQuery(this).closest(".modal-content").find("input").val('');
            jQuery(this).closest(".modal-content").find("select").val('').change();
        });
        jQuery(document).on("click", ".pwd-toggle", function(){
            var cur_type = jQuery(this).prev('input').attr('type');
            if(cur_type == 'password'){
                jQuery(this).prev('input').attr('type','text');
                jQuery(this).removeClass('icofont-eye');
                jQuery(this).addClass('icofont-eye-blocked');
            } else {
                jQuery(this).prev('input').attr('type','password');
                jQuery(this).removeClass('icofont-eye-blocked');
                jQuery(this).addClass('icofont-eye');
                
            }
          });
          jQuery(document).on("click", ".pwd_type", function(){
                if(jQuery(this).val() == 'manually'){
                    jQuery(this).closest("form").find(".pwd-manually").removeAttr('readonly');
                    jQuery(this).closest("form").find(".pwd-manually, i.icofont-eye.pwd-toggle").show();
                    jQuery(this).closest("form").find(".pwd-mail").hide();
                } else {
                    jQuery(this).closest("form").find(".pwd-manually").attr('readonly','');
                    jQuery(this).closest("form").find(".pwd-manually, i.icofont-eye.pwd-toggle").hide();
                    jQuery(this).closest("form").find(".pwd-mail").show();
                }
            });
function onlyNumberKey(evt) {
      
    // Only ASCII character in that range allowed
    var ASCIICode = (evt.which) ? evt.which : evt.keyCode
    if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
        return false;
    return true;
}
function fileValidation(e){
    var fileInput = e;
    var filePath = fileInput.value;
    if(filePath == ''){ return false; }
    var allowedExtensions = /(\.jpg|\.jpeg|\.png)$/i;
    if(!allowedExtensions.exec(filePath)){
        alert('Please upload file having extensions .jpeg/.jpg/.png only.');
        fileInput.value = '';
        return false;
    }
}

function checkPasswordStrength(curr) {
    var number = /([0-9])/;
    var alphabets = /([a-zA-Z])/;
    var special_characters = /([~,!,@,#,$,%,^,&,*,-,_,+,=,?,>,<])/;
    var password = $(curr).val().trim();
    if (password.length < 6) {
        $(curr).closest("div").find('#password-strength-status').removeClass();
        $(curr).closest("div").find('#password-strength-status').addClass('weak-password');
        $(curr).closest("div").find('#password-strength-status').html("Weak (should be atleast 6 characters.)");
    } else {
        if (password.match(number) && password.match(alphabets) && password.match(special_characters)) {
            $(curr).closest("div").find('#password-strength-status').removeClass();
            $(curr).closest("div").find('#password-strength-status').addClass('strong-password');
            $(curr).closest("div").find('#password-strength-status').html("Strong");
            return true;
        }
        else {
            $(curr).closest("div").find('#password-strength-status').removeClass();
            $(curr).closest("div").find('#password-strength-status').addClass('medium-password');
            $(curr).closest("div").find('#password-strength-status').html("Medium (should include alphabets, numbers and special characters.)");
        }
    }
    return false;
}
$(document).on("submit", "form[name='f2']", function(e){
    var pass = 0;
    var new_pwd = $(this).find("input[name='new_pwd']");
    var cnf_pwd = $(this).find("input[name='cnf_pwd']");
    if(!checkPasswordStrength(new_pwd)){
        e.preventDefault();
        alert("Password Must be strong.");
        
        return false;
    } else { pass += 1; }
    if(!checkPasswordStrength(cnf_pwd)){
        e.preventDefault();
        
        alert("Password Must be strong.")
        return false;
    } else { pass += 1; }

    if(pass >= 2){
        return true;
    }
});

</script>