<?php 

$email_exist = 0;
if (isset($_POST['save_emp']))
{
      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'];
        $fname      =   "";
        $time       =   date('Y-m-d h:i:s');
        
        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);

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

            $query = "insert into db_users(username, password, email,phone,full_name,company_name,description,profile_img,type,date_time) values ('$username', '$password', '$email', '$phone','$ename', '$comp', '$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 : $site_url)</small> <br><br> Regards,<br> Timesheethub.";
                $headers = "MIME-Version: 1.0" . "\r\n"; 
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
                //mail($email,"System Generated Password",$msg,$headers);
                send_zoho_mail($email,"System Generated Password",$msg);
            }

        } else {
            $email_exist = 1;
        }
       die(); 
}
    include("header.php"); 
    
    $edit_ename = '';
    $edit_comp  = '';
    $edit_img   = '';
    $edit_uname = '';
    $edit_pwd   = '';
    $edit_email = '';
    $edit_phone = '';
    $edit_desc  = '';
    $emp_id     = '';
    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. <br><br> 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_pwd   = $single_emp['password'];
        $edit_email = $single_emp['email'];
        $edit_phone = $single_emp['phone'];
        $edit_desc  = $single_emp['description'];
        $emp_id     = $_POST['edit_id'];
    }
    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'])){
        $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']."' 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 -->       
            <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">
                                <h3 class="h4 mb-0">Managers List</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'){ ?>
                                    <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>Add Manager</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">Manager Name</span></th>
                                            <th><span class="table-heading">Project</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_employes = array();
                                            if($emp_list['type'] == 'admin'){
                                                $all_employes = mysqli_query($conn, "select * from db_users where type='manager' ");
                                            } else if($emp_list['type'] == 'company') {
                                                $all_employes = mysqli_query($conn, "select * from db_users where type='manager' and company_name=".$emp_list['id']);
                                            
                                            }
                                            
                                            if(!empty($all_employes)){
                                                while($res = mysqli_fetch_array($all_employes)):
                                                    $company_name = '-';
                                                    if(!empty($res['company_name'])){
                                                        $get_company = mysqli_fetch_assoc(mysqli_query($conn, "select * from db_users where id=".$res['company_name']));
                                                        $company_name = $get_company['username'];
                                                    }
                                                   
                                                    
                                                    $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>
                                                       -
                                                   </td>
                                                   <td>
                                                        '.$company_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">
                            <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">Manager Name</label>
                                <input type="text" name="ename" class="form-control" id="exampleFormControlInput877" placeholder="Employee 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" style="display:none;">
                                <label for="exampleFormControlInput977" class="form-label">Employee 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)){
                                            $sel = ($_SESSION['loggedin_user'] == $single_co['id']) ? "selected" : "";
                                            echo '<option value="'.$single_co['id'].'" '.$sel.'>'.$single_co['full_name'].'</option>';
                                        }
                                    ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="formFileMultipleoneone" class="form-label">Manager Profile</label>
                                <input class="form-control" name="eimage" type="file" accept="image/jpg, image/jpeg, image/png" id="formFileMultipleoneone" 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="text" 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" required="" maxlength="10" 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_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 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">Manager Name</label>
                                <input type="text" name="ename" class="form-control" id="exampleFormControlInput877" placeholder="Employee 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="display:none;">
                                <label for="exampleFormControlInput977" class="form-label">Manager Company</label>
                                <select name="comp" required="" class="form-control form-select">
                                    <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">
                                <label for="formFileMultipleoneone" class="form-label">Manager Profile</label>
                                <input class="form-control" name="eimage" type="file" accept="image/jpg, image/jpeg, image/png" id="formFileMultipleoneone" 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" value="<?= $edit_pwd; ?>">
                                </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="" value="<?= $edit_email; ?>">
                                    <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="" 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="user_type" value="manager">
                            <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="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">
            span.email_error {
                    color: red;
                }
            .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: "";
            } 
            span.pwd-mail {
                width: 100%;
                display: block;
                border: 1px dotted gray;
                padding: 3px 10px;
                font-size: 13px;
            }
            label.pwd-pref {
                padding: 0 15px;
            }
            .form-control[type="Password"] {
                border-right: 0px;
                border-radius: 0.25rem 0px 0px 0.25rem;
            }
            .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);
            }
            .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;
            }
            /* .password-text {
                display: flex;
                justify-content: space-between;
            } */
            </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");
            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());
                    }
                });

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

            } );
        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("click", "button.clear-btn", function(){
               jQuery(this).closest(".modal-content").find("input").val('');
            jQuery(this).closest(".modal-content").find("select").val('').change();
        });
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;
    }
}

jQuery(document).on("click", "#addemp button[name='submit']", function(){
            let valid = true;
            var pwd = $(this).closest(".modal-content").find("input[name='password']");
            jQuery('#addemp form [required]:not([readonly])').each(function() {
                if (jQuery(this).is(':invalid') || !jQuery(this).val()) valid = false;
            })
           
            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", ".pwd_type", function(){
    if(jQuery(this).val() == 'manually'){
        jQuery(".pwd-manually").removeAttr('readonly');
        jQuery(".pwd-manually, i.icofont-eye.pwd-toggle").show();
        jQuery(".pwd-mail").hide();
    } else {
        jQuery(".pwd-manually").attr('readonly','');
        jQuery(".pwd-manually, i.icofont-eye.pwd-toggle").hide();
        jQuery(".pwd-mail").show();
    }
});
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');
        
    }
  });

  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>