<?php
include "pin/header.php";
include "pin/sidenav.php";

$user_id = $_SESSION['user_id'];
$emp_id = $_SESSION['emp_id'];
$user_role = $_SESSION['user_role'];

if (isset($_GET['delete'])) {
    $q = mysqli_query($db, "DELETE FROM `users` WHERE `id`='$_GET[delete]' ");

    if ($q) {
        echo "<script>alert('User Deleted Successfully !');</script>";
        echo "<script>location.href='all_users';</script>";
    }
}

// $edit = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM `users` WHERE `id`='$_GET[edit]' "));


?>


<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->

<div class="content-page">
    <div class="content">
        <div class="container-fluid">

            <div class="row page-title align-items-center">
                <div class="col-sm-4 col-xl-6">

                </div>
                <div class="col-sm-8 col-xl-6">
                    <form class="form-inline float-sm-right mt-3 mt-sm-0">
                        <div class="btn-group mr-2">
                            <button type="button" class="btn btn-primary" onclick="exportDataIds();">
                                <i class='uil uil-file-alt mr-1'></i>Download Excel<i class="uil uil-down-arrow ml-1"></i>
                            </button>
                        </div>
                        <div class="btn-group">
                            <button type="button" class="btn btn-danger" onclick="update_login_status();">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-door-closed" viewBox="0 0 16 16">
                                    <path d="M3 2a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v13h1.5a.5.5 0 0 1 0 1h-13a.5.5 0 0 1 0-1H3zm1 13h8V2H4z"/>
                                    <path d="M9 9a1 1 0 1 0 2 0 1 1 0 0 0-2 0"/>
                                </svg>
                                <span>Logout All</span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="row mb-3" id="filter_block">
                <div class="col-md-3">
                    <div class="form-group">
                        <label class="form-label" for="employee_id">User (Name, E-mail, Phone)</label>
                        <select required id="employee_id" name="employee_id" data-plugin="customselect" class="form-control custom-select-picker-ajax" data-search="employees" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select user">
                            <option></option>
                        </select>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="form-group">
                        <label class="form-label" for="leader">Leader (Name, E-mail, Phone)</label>
                        <select required id="leader" name="leader" data-plugin="customselect" class="form-control custom-select-picker-ajax" data-search="managers" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Leader">
                            <option></option>
                        </select>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="form-group">
                        <label class="form-label" for="department">Department</label>
                        <select required id="department" name="department" data-plugin="customselect" class="form-control custom-select-picker-ajax" data-search="departments" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Department">
                            <option></option>
                        </select>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="form-group">
                        <label class="form-label" for="new_designation">Designation</label>
                        <select required id="new_designation" name="new_designation" data-plugin="customselect" class="form-control custom-select-picker-ajax" data-search="designations" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Designation">
                            <option></option>
                        </select>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="form-group">
                        <label class="form-label" for="working_status_final">Working Status</label>
                        <select required id="working_status_final" name="working_status_final" data-plugin="customselect" class="form-control custom-select-picker" data-placeholder="Select Working Status">
                            <option></option>
                            <option value="Active">Active</option>
                            <option value="Resigned">Resigned</option>
                            <option value="Terminated">Terminated</option>
                            <option value="Abscond">Abscond</option>
                        </select>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="form-group">
                        <label class="form-label" for="joining_date">Joining Date</label>
                        <input required id="joining_date" name="joining_date" class="form-control flatpickr_date" placeholder="Select Joining Date" data-isDate="true">
                    </div>
                </div>
              
                <div class="col-md-2">
                    <div class="d-flex flex-column mb-3">
                        <button type="button" class="btn btn-danger btn-padding mb-1" name="clear_filter" id="clear_filter">Clear</button>
                        <button class="btn btn-success btn-padding" type="button" name="search_filter" id="search_filter">Search</button>
                    </div>
                </div>
                <div class="col-sm-12">
                    <div id="filter_options" class="d-flex align-items-center flex-wrap" style="gap:0.25rem"></div>
                </div>
            </div>


            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <label class="form-label" for="employee_action_for">Action For</label>
                        <select required id="employee_action_for" name="employee_action_for" data-plugin="customselect" class="form-control custom-select-picker" data-placeholder="Select Action For">
                            <option></option>
                            <option value="Department">Department</option>
                            <option value="Leader">Leader</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3" id="leader_update" style="display:none;">
                    <div class="form-group">
                        <label class="form-label" for="u_leader">Leader (Name, E-mail, Phone)</label>
                        <select required id="u_leader" name="u_leader" data-plugin="customselect" class="form-control custom-select-picker-ajax" data-search="managers" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Leader">
                            <option></option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3" id="department_update" style="display:none;">
                    <div class="form-group">
                        <label class="form-label" for="u_department">Department</label>
                        <select required id="u_department" name="u_department" data-plugin="customselect" class="form-control custom-select-picker-ajax" data-search="departments" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Department">
                            <option></option>
                        </select>
                    </div>
                </div>

                <div class="col-md-2" id="action_perform_button" style="display:none;">
                    <div class="d-flex flex-column mb-3">
                        <button type="button" class="btn btn-danger btn-padding mb-1" onclick="location.reload();">Cancel</button>
                        <button class="btn btn-success btn-padding" type="button" name="perform_action" id="perform_action"></button>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body p-4">
                            <h4 class="header-title mt-0 mb-1 mb-4">
                                <?php echo ($user_role < 2) ? 'All Employees' : 'Employee'; ?>
                            </h4>

                            <table id="basic-datatable" class="table dt-responsive nowrap">
                                <thead>
                                    <tr>
                                        <th>
                                            <!-- # -->
                                            <input id="checkAll" type="checkbox">
                                        </th>
                                        <th>Profile</th>
                                        <!-- <th>ID</th> -->
                                        <th>Employee Id</th>

                                        <th>Personal Details</th>
                                        
                                        <th>Professional Details</th>
                                        
                                        <th>Account Details</th>
                                        <th>ESIC Details</th>
                                        <th>EPF Details</th>

                                        <th>Working Status</th>
                                        <th>Login Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>

                            </table>
                            <!-- </div> -->

                        </div> <!-- end card body-->
                    </div> <!-- end card -->
                </div><!-- end col-->
            </div>
            <!-- end row-->

        </div>
    </div> <!-- content -->

</div>

<!-- ============================================================== -->
<!-- End Page content -->
<!-- ============================================================== -->

<!-- Modal -->
<div class="modal fade" id="employee_time" tabindex="-1" aria-labelledby="employee_timeLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body p-3">
                <div class="d-flex align-items-center justify-content-between mb-4">
                    <h5 class="mb-2">Add <span id="time_name"></span>'s Time</h5>
                    <i data-feather="x" onclick="$('#employee_time').modal('hide');"></i>
                </div>
                <div>
                    <form id="employee_id_form">
                        <div class="row">
                            <input type="hidden" name="employee_time_id" id="employee_time_id">
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <input type="text" class="form-control" name="punch_in_time" id="punch_in_time" placeholder="Punch In (9:45 AM)">
                                </div>
                            </div>

                            <div class="col-sm-6">
                                <div class="form-group">
                                    <input type="text" class="form-control" name="punch_out_time" id="punch_out_time" placeholder="Punch Out (6:30 PM)">
                                </div>
                            </div>

                        </div>

                        <div class="row">
                            <div class="col-12">
                                <div class="w-100 d-flex align-items-center justify-content-end">
                                    <button type="submit" name="set_employee_time" class="btn btn-primary">Add Time</button>
                                </div>
                            </div>
                        </div>

                    </form>
                </div>

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


<?php
include "pin/footer.php";
?>
<!-- <script src="https://cdn.datatables.net/plug-ins/1.11.5/api/stateSave.js"></script> -->
<script>

    function viewEmployeeLifeCycle(emp_id){
        // console.log(emp_id);
        if(emp_id!=''){

            $.ajax({
                url:"fun/life_cycle",
                type:"GET",
                data:{
                    employee_life_cycle_id:emp_id
                },
                success:function(result){
                    // console.log(result);
                    if(result!=''){
                        $('#right_sidebar_title').html('Employee Life Cycle');
                        $('#right_sidebar_details').html(result);
                        show_hide_right_bar();
                    }else{
                        failedMessage('Some Error Occurred.');
                    }
                }
            });
        }else{
            failedMessage('Some Error Occurred.');
        }
    }

    function exportDataIds() {
        // console.log(users, from, to);
        if (confirm("Export Employees to Excel....?")) {
            $.ajax({
                url:'fun/exportEmployees',
                type:"GET",
                data:{users:1},
                dataType: "json",
                success:function(res){
                    // console.log(res);
                    if (res.status=200) {
                        successMessage(res.message, '<?php echo $_SESSION['user_name'] ?>');
                        setTimeout(() => {
                            location.href='download_files';
                        }, 1000);
                    } else {
                        failedMessage(res.message, '<?php echo $_SESSION['user_name'] ?>');
                    }
                },
                error: function(xhr, status, error) {
                    console.log(`Error: ${JSON.stringify(error)}`);
                }
            });
        } else {
            return false;
        }
    }

    function resetPasswordSendMail(data, id) {
        // console.log(data);
        $.ajax({
            url: "fun/function",
            type: "POST",
            data: {
                resetPasswordFunction: JSON.stringify(data)
            },
            success: function(response) {
                // console.log(response)
                if (response == 1) {
                    // console.log('Mail Send Successfully !');
                    $("#addTickSend" + id).removeClass('uil-envelope-share').addClass('uil-envelope-check');
                    successMessage('Mail Send Successfully!', '<?php echo $_SESSION['user_name'] ?>');
                } else if (response == 2) {
                    failedMessage('Some Error Occurred.');
                } else {
                    failedMessage('Some Error Occurred.');
                }
                setTimeout(() => {
                    $("#addTickSend" + id).removeClass('uil-envelope-check').addClass('uil-envelope-share')
                }, 5000)
            }
        });
    }

    function workingStatus(id, name) {
        let status = $("#workingStatus" + id).val();
        let date = $("#workingStatusDate" + id).val();
        if (status != '' && date != '') {
            $.ajax({
                url: "fun/function",
                type: "POST",
                data: {
                    working_id: id,
                    working_status: status,
                    working_status_date: date
                },
                success: function(response) {
                    console.log(response);
                    if (response == 1) {
                        successMessage('Working Status and Date Updated', name + "\'s");
                        $("#workingStatus" + id).prop('disabled',true);
                        $("#workingStatusDate" + id).prop('disabled',true);
                        $("#statusButton" + id).prop('disabled',true);
                    } else {
                        failedMessage('Some Error Occurred.');
                    }

                }
            });
        } else {
            failedMessage('Please Fill both field working status and date!');
        }

    }

    async function employee_time(id,name){
        $("#time_name").text(name);
        $("#employee_time_id").val(id);
        await $.ajax({
            url:"fun/function",
            type:"GET",
            data:{
                employee_get_time_id:id
            },
            success:function(result){
                if(result!=''){
                    let data = JSON.parse(result)
                    // console.log(data);
                    $("#punch_in_time").val(data.punch_in);
                    $("#punch_out_time").val(data.punch_out);
                }
            }
        });
        $("#employee_time").modal('show');
    }

    $("#employee_id_form").submit(function(e){
        e.preventDefault();
        let form = $(this).serialize();
        // console.log(form);
        if(($("#punch_in_time").val()!='' && $("#punch_out_time").val()!='') || ($("#punch_in_time").val()=='' && $("#punch_out_time").val()=='')){
            $.ajax({
                url:"fun/function",
                type:"POST",
                data:form,
                success:function(result){
                    // console.log(result);
                    $("#employee_time").modal('hide');
                    if(result==1){
                        successMessage('Time Set Successfully!', $("#time_name").text() + "\'s");
                    }else{
                        failedMessage('Some Error Occurred.');
                    }
                }
            });
        }else{
            failedMessage('Please Fill or Empty both fields');
        }
    });


    function update_login_status(id=null, name=null){
        if(confirm(`Do you want to logout ${name??'All'}`)){
            $.ajax({
                url:"fun/function",
                type:"POST",
                data:{logout_id:id},
                success:function(result){
                    // console.log(result);
                    if(result==1){
                        successMessage(`${name} Successfully Logout`);
                        // location.reload();
                    }else{
                        failedMessage('Some Error Occurred.');
                    }
                }
            });
        }
    }

    let columns = [];
    // ############################### columns
    let columns_visible = [{data: 'id'}, {data: 'image'}, 
    // {data: 'row_num'}, 
    {data: 'employee_id'}, {data: 'name'}, {data: 'joining_date'}, {data: 'pan_no'}, {data: 'esi_no'}, {data: 'uan_no'}, {data: 'working_status'}, {data: 'working_status_date'}, {data: 'account_no'}];

    let columns_hide = [{data: 'ifsc_code', visible: false}, {data: 'epf_applicable_status', visible: false}, {data: 'email', visible: false}, {data: 'phone', visible: false}, {data: 'gender', visible: false}, {data: 'dob', visible: false}, {data: 'notice_period', visible: false}, {data: 'department_name', visible: false}, {data: 'designation_name', visible: false}, {data: 'role', visible: false}, {data: 'l_name', visible: false}, {data: 'consider_as', visible: false}, {data: 'remember_token', visible: false}, {data: 'last_login_time', visible: false}, {data: 'working_status_final', visible: false}];

    columns = [...columns_visible, ...columns_hide]
    // ############################### columns
    function show_hierarchy_data() {

        // ############################### setArray
        <?php if ($user_role == 1) { ?>
            setArray.push(`(employee_id='<?php echo $emp_id; ?>' OR leader='<?php echo $emp_id; ?>')`);
        <?php }else if($user_role == 2){ ?>
            setArray.push(`id='<?php echo $user_id; ?>'`);
        <?php } ?>
        // ############################### setArray

        $("#filter_options").html('');
        form_fields.each(function() {
            search_filter(this);
        });
        if (setArray.length > 0) {
            loadTable('#basic-datatable', 'get_from_server/all_users_get', columns, [0, 'asc'], setArray);
        } else {
            loadTable('#basic-datatable', 'get_from_server/all_users_get', columns, [0, 'asc']);
        }
        // console.log(setArray);
        setArray = [];
        // console.log(setArray);
    }
    $(document).ready(function() {
        

        show_hierarchy_data();
        $("#search_filter").click(show_hierarchy_data);
    });

    $("#employee_action_for").change(function(e){
        console.log(this.value);
        if(this.value=='Department'){
            $("#leader_update").hide();
            $("#department_update").show();
        }else{
            $("#leader_update").show();
            $("#department_update").hide();
        }
        $('#action_perform_button').show();
        $('#perform_action').text(`Update ${this.value}`)
    });

     $('#perform_action').click(function(e){
        let employee_action_for = $('#employee_action_for').val();
        let u_department = $('#u_department').val();
        let u_leader = $('#u_leader').val();

        if(employee_action_for=='Department' && u_department==''){
            failedMessage('Please, Select Department.', '<?php echo $_SESSION['user_name']; ?>');
            return false;
        }
        if(employee_action_for=='Leader' && u_leader==''){
            failedMessage('Please, Select Leader.', '<?php echo $_SESSION['user_name']; ?>');
            return false;
        }

        if(all_checkboxes_val.length==0){
            failedMessage('Please, Check At least one Employee.','<?php echo $_SESSION['user_name']; ?>');
            return false;
        }

        $.ajax({
            url:'fun/function',
            type:'post',
            data:{
                employee_action_for,
                u_department,
                u_leader,
                all_checkboxes_val
            },
            success:function(res){
                console.log(res);
                if(res==1){
                    show_hierarchy_data();
                    successMessage(`Employee ${employee_action_for} Updated Successfully!`, '<?php echo $_SESSION['user_name']; ?>');
                    $("#leader_update").hide();
                    $("#department_update").hide();
                    $('#action_perform_button').hide();

                    $('#employee_action_for option').first().prop('selected',true).trigger('change');
                    $('#u_department option').first().prop('selected',true).trigger('change');
                    $('#u_leader option').first().prop('selected',true).trigger('change');
                }else{
                    failedMessage('Some Error Occurred.', '<?php echo $_SESSION['user_name']; ?>');
                }
            }
        });
    });
   
</script>