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

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

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

    if ($q) {
        mysqli_query($db, "DELETE FROM password_assign WHERE pass_id='$_GET[delete]' ");
        echo "<script>alert('Password Deleted Successfully !');</script>";
        echo "<script>location.href='all_password';</script>";
    }
}


if (isset($_POST['assign_employee'])) {

    $checked = explode(',', $_POST['all_selected_ids']);
    $employees = $_POST['employee_id'];


    $sql = "";
    foreach ($checked as $pass_id) {
        foreach ($employees as $e_id) {
            $count = mysqli_num_rows(mysqli_query($db, "SELECT * from password_assign where pass_id='$pass_id' and assigned_to='$e_id' "));
            if ($count > 0) {
                continue;
            }
            $sql .= " ('$pass_id', '$e_id', '$emp_id'),";
        }
    }
    $sql = trim($sql, ",");

    if (!empty($sql)) {
        $q = mysqli_query($db, "INSERT INTO password_assign (pass_id, assigned_to, assigned_by) VALUE $sql;");
        if ($q) {
            echo "<script>alert('Password Assigned Successfully!');</script>";
        } else {
            echo mysqli_error($db);
        }
    } else {
        echo "<script>alert('All Passwords Already Assigned!');</script>";
    }
    echo "<script>location.href='all_password';</script>";
}



?>


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

<div class="content-page">
    <div class="content">
        <div class="container-fluid">
            <div class="mt-4"></div>

            <?php if ($user_role < 2) { ?>
            <div class="row mb-3" id="filter_block">
                <?php if ($user_role == 0) { ?>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="l_eid">Added By</label>
                            <select data-plugin="customselect" name="l_eid" class="form-control custom-select-picker-ajax" data-search="employees" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Added By" id="l_eid" required>
                                <option></option>
                            </select>
                        </div>
                    </div>
                <?php } ?>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="u_eid">Assigned To</label>
                        <select data-plugin="customselect" name="u_eid" class="form-control custom-select-picker-ajax" data-search="employees" data-param="<?php echo htmlspecialchars(json_encode(['default'=>'', 'current_page'=>$currentPageName])); ?>" data-placeholder="Select Assigned To" id="u_eid" data-comma_separated="true" required>
                            <option></option>
                        </select>
                    </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>
            <?php } ?>


            <form id="assigned_employee_submit" method="post">

                <?php if ($user_role < 2) { ?>
                    <div class="row">
                        <div class="col-sm-3">
                            <div class="form-group">
                                <label for="employee_id">Employee<span class="text-danger">*</span></label>
                                <select data-plugin="customselect" name="employee_id[]" class="form-control custom-select-picker" data-placeholder="Select Employee" id="employee_id" required multiple>
                                    <option></option>
                                    <?php
                                        $today_date = date('Y-m');
                                        $users = mysqli_query($db, "select name,employee_id from users where (COALESCE(joining_date,'') = '' OR DATE_FORMAT(STR_TO_DATE(joining_date, '%Y-%m-%d'),'%Y-%m') <= '$today_date') AND (COALESCE(working_status_date,'')='' or DATE_FORMAT(STR_TO_DATE(working_status_date, '%Y-%m-%d'),'%Y-%m')>='$today_date') ");
                                        while ($user = mysqli_fetch_assoc($users)) {
                                            echo "<option value='". $user['employee_id']. "'>". $user['name']. "</option>";
                                        }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <input type="hidden" name="all_selected_ids" id="all_selected_ids">

                        <div class="col-sm-2">
                            <div class="form-group">
                                <div class="d-flex flex-column">
                                    <label for="assign_employee">Assign:</label>
                                    <button type="submit" class="btn btn-danger btn-padding" name="assign_employee" id="assign_employee">Assign Employee</button>
                                </div>
                            </div>
                        </div>

                    </div>
                <?php } ?>

                <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">
                                    All Passwords
                                </h4>

                                <table id="basic-datatable" class="table dt-responsive nowrap">
                                    <thead>
                                        <tr>
                                            <?php if ($user_role < 2) { ?>
                                                <th><input id="checkAll" type="checkbox"></th>
                                            <?php } ?>
                                            <th>ID</th>
                                            <th>Added By</th>
                                            <th>Passwords</th>
                                            <?php if ($user_role < 2) { ?>
                                                <th>Assigned to Employees</th>
                                                <th>Action</th>
                                            <?php } ?>
                                        </tr>
                                    </thead>

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

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

            </form>


        </div>
    </div>

</div>



<?php
include "pin/footer.php";
?>

<script>

    function eye_button(id) {
        if ($(`#span_${id}`).css('filter') == 'blur(0px)') {
            $(`#span_${id}`).css('filter', 'blur(2px)');
            $(`#span_${id}`).attr('title', 'Show');
            $(`#eye_${id}`).removeClass('uil-eye-slash').addClass('uil-eye');
        } else {
            $(`#span_${id}`).css('filter', 'blur(0px)');
            $(`#span_${id}`).attr('title', 'Hide');
            $(`#eye_${id}`).removeClass('uil-eye').addClass('uil-eye-slash');
        }
    }

    function copy_button(id) {
        var copyText = document.getElementById(`input_${id}`).value;
        navigator.clipboard.writeText(copyText)
            .then(function() {
                successMessage('Text Copied Successfully!', '<?php echo $user_name; ?>');
            })
            .catch(function(err) {
                failedMessage(`Error copying text: ${err}`,'<?php echo $user_name; ?>');
            });
    }

    function removePassAssign(id) {
        if (confirm('Do You want to delete Assigned employee ?')) {
            $.ajax({
                url: "fun/function",
                type: "POST",
                data: {
                    password_assigned_id: id
                },
                success: function(res) {
                    if (res == 1) {
                        $(`#assign_emp${id}`).remove();
                        successMessage('Assigned employee deleted Successfully!', '<?php echo $user_name; ?>');
                    } else {
                        failedMessage('Some Error Occurred, Please Try after some time.', '<?php echo $user_name; ?>');
                    }
                }
            });
        }
    }

    $("#assigned_employee_submit").submit(function(e) {

        if (all_checkboxes_val.length == 0) {
            // $("#assign_employee").click();
            e.preventDefault();
            failedMessage('Please, Check at least one password.', '<?php echo $user_name; ?>')
        }else{
            $('#all_selected_ids').val(all_checkboxes_val);
            $("#assigned_employee_submit").submit();
        }

    });

    $(document).ready(function() {

        // ############################### columns
        let columns = [];
        <?php if ($user_role < 2) { ?>
            columns.push({data: 'check_id'})
        <?php } ?>
            columns.push({data: 'row_num'}, {data: 'l_name'}, {data: 'passwords'});
        <?php if ($user_role < 2) { ?>
            columns.push({data: 'u_name'}, {data: 'password_assign_id'})
        <?php } ?>
        // ############################### columns
        let default_order = [1, "asc"];

        function show_hierarchy_data() {

            // ############################### setArray
            <?php if ($user_role == 1) { ?>
                setArray.push(`l_eid='<?php echo $emp_id; ?>' OR CONCAT(',', u_eid, ',') LIKE '%,<?php echo $emp_id; ?>,%' OR p_eid='<?php echo $emp_id; ?>'`);
            <?php }else if($user_role == 2){ ?>
                setArray.push(`l_eid='<?php echo $emp_id; ?>' OR CONCAT(',', u_eid, ',') LIKE '%,<?php echo $emp_id; ?>,%' OR p_eid='<?php echo $emp_id; ?>'`);
                default_order = [0, "asc"];
            <?php } ?>
            // ############################### setArray

            $("#filter_options").html('');
            form_fields.each(function() {
                search_filter(this);
            });

            if (setArray.length > 0) {
                loadTable('#basic-datatable', 'get_from_server/all_password_get', columns, default_order, setArray);
            } else {
                loadTable('#basic-datatable', 'get_from_server/all_password_get', columns, default_order);
            }
            // console.log(setArray);
            setArray = [];
            // console.log(setArray);
        }

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

</script>