<?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'];


?>

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

            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body py-4 px-sm-5 px-4">

                            <div class="mb-5">
                                <h4 class="header-title mt-1 mb-1"><i class="uil uil-lock-open-alt mr-2 text-primary"></i>Set Access</h4>
                            </div>

                            <div>
                            <div class="form-group mb-5">
                                <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>
                                <h5>Select Nav Options</h5>
                            </div>
                            <div class="row">
                                <?php
                                    $parent = mysqli_query($db, "SELECT * FROM emp_files WHERE parent=0");
                                    while($p_row = mysqli_fetch_assoc($parent)){

                                ?>
                                    <div class="col-lg-3 col-md-4 col-sm-6 mb-3">
                                        <div class="custom-control custom-checkbox mb-1">
                                            <input type="checkbox" class="custom-control-input" name="parent[]" id="parent_<?php echo $p_row['id']; ?>" value="<?php echo $p_row['id']; ?>" onclick="parent_click('<?php echo $p_row['id']; ?>');">
                                            <label class="custom-control-label text-primary" style="font-weight: bolder; font-size:16px;" for="parent_<?php echo $p_row['id']; ?>"><?php echo $p_row['name']; ?></label>
                                        </div>

                                        <?php
                                            $child = mysqli_query($db, "SELECT * FROM emp_files WHERE parent='$p_row[id]'");
                                            while($c_row = mysqli_fetch_assoc($child)){
                                        ?>
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" name="child_<?php echo $p_row['id']; ?>[]" id="child_<?php echo "$p_row[id]_$c_row[id]"; ?>" value="<?php echo $c_row['id']; ?>" onclick="child_click('<?php echo $p_row['id']; ?>');">
                                            <label class="custom-control-label" for="child_<?php echo "$p_row[id]_$c_row[id]"; ?>"><?php echo $c_row['name']; ?></label>
                                        </div>
                                        <?php } ?>
                                    </div>
                                <?php } ?>

                            </div>


                            <div class="d-flex align-items-end justify-content-end mt-4">
                                <button type="button" class="btn btn-primary" id="set_permission">Save Changes</button>
                            </div>

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

            </div>
            <!-- end row -->

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

</div>

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


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

<script>
    function parent_click(p_id){
        let p_check_val = p_id;
        let p_check_status = $(`#parent_${p_id}`).is(':checked');
        // console.log(p_check_val, p_check_status);
        $(`input[name="child_${p_check_val}[]"`).prop('checked', p_check_status);
    }

    function child_click(p_id) {
        let allUnchecked = true;

        $(`input[name="child_${p_id}[]"]`).each((index, ele) => {
            if ($(ele).is(":checked")) {
                $(`#parent_${p_id}`).prop('checked', true);
                allUnchecked = false;
                return false;
            }
        });

        if (allUnchecked) {
            $(`#parent_${p_id}`).prop('checked', false);
        }
    }

    $('#employee_id').change(function(e){

        $('input[type="checkbox"]').prop('checked', false);
        let user = $(this).val();

        $.ajax({
            url: 'fun/function',
            type: 'GET',
            data: {get_user_nav_details:1, user},
            success: function(res){
                // console.log(res);
                let permission = JSON.parse(res);
                // console.log(permission)

                for(var [parent, children] of Object.entries(permission)){
                    // console.log(parent, children);
                    $(`#parent_${parent}`).prop("checked",true);
                    for(let child of children){
                        $(`#child_${parent}_${child}`).prop("checked",true);
                    }
                }

            }
        })
    });


    $('#set_permission').click(function(e){
        let parent_arr = [];
        let child_arr = [];
        let access = {};

        let select_user = $('#employee_id').val();

        $('input[name="parent[]"]').each((index, ele) => {
            if($(ele).is(":checked")){
                parent_arr.push($(ele).val());
            }
        });
        // console.log(parent_arr);

        for (const parent of parent_arr) {
            $(`input[name="child_${parent}[]"]`).each((index, ele) => {
                if($(ele).is(":checked")){
                    child_arr.push($(ele).val());
                }
            });

            if(child_arr.length>0){
                access[parent] = child_arr;
            }else{
                access[parent] = [];
            }
            child_arr = [];
        }
        // console.log(access);
        // console.log(Object.keys(access).length);
        if(Object.keys(access).length==0){
            failedMessage("Please check some checkboxes", '<?php echo $_SESSION['user_name']; ?>');
            return false;
        }
        
        if(select_user==''){
            failedMessage("Please Select Any employee", '<?php echo $_SESSION['user_name']; ?>');
            return false;
        }
        
        let nav_access = JSON.stringify(access);
        // console.log(access);
        $.ajax({
            url: "fun/function",
            type: "POST",
            data: {nav_access,select_user},
            success: function(res){
                // console.log(res);
                if(res == 1){
                    successMessage("Permissions Updated Successfully!", '<?php echo $_SESSION['user_name']; ?>');
                    $('input[type="checkbox"]').prop('checked', false);
                    $('#employee_id').select2("destroy");
                    $(`#employee_id option`).first().prop("selected", true)
                    $('#employee_id').select2();
                }else{
                    failedMessage("Some error occurred!", '<?php echo $_SESSION['user_name']; ?>');
                }
            }
        });


    });


</script>