<?= $this->extend('template/layout') ?>

<?= $this->section('title') ?>User Privileges - <?= env('app.name') ?><?= $this->endSection() ?>

<!-- main section start-->
<?= $this->section('main') ?>
<?php
    $uri      = current_url(true);
    $segment1 = $uri->setSilent()->getSegment(1);
    $segment2 = $uri->setSilent()->getSegment(2);
    $segment3 = $uri->setSilent()->getSegment(3);
?>
<!-- Breadcumb -->
<ol class="breadcrumb page-breadcrumb">
    <li class="breadcrumb-item"><a href="javascript:void(0);"><?= env('app.name') ?></a></li>
    <li class="breadcrumb-item"><?= ucfirst($segment1) ?></li>
    <li class="breadcrumb-item">User Privileges</li>
    <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
</ol>

<div class="row">
    <div class="col-xl-6">
        <div id="panel-1" class="panel">
            <div class="panel-hdr border-faded border-top-1 border-right-0 border-left-0 shadow-0">
                <h2>Data User</h2>
                <div class="panel-toolbar pr-3">
                    <ul class="nav nav-pills border-bottom-0" role="tablist">
                        <li class="nav-item">
                            <?= form_button('reload', '<i class="fal fa-sync"></i>', 'reload_datagrid_user()') ?>&nbsp;
                        </li>
                        <?php if ($rekam == 1) { ?>
                        <li class="nav-item">
                            <button type="button" id="rekam-modal" class="btn btn-default waves-effect waves-themed" onclick="rekam_data()"><i class="fal fa-plus"></i></button>&nbsp;
                        </li>
                        <?php } ?>
                    </ul>
                </div>
            </div><!-- end panel hdr -->

            <div class="panel-container show">
                <div class="panel-content">
                    <div id="panelfit-1" data-options="border:false">
                        <!-- grid start -->
                        <table id="datagrid_user" toolbar="#toolbar_user" url="<?= site_url('admin/user_priv/datagrid_user') ?>" data-options="nowrap:true,striped:false,ctrlSelect:true,rownumbers:true,pagination:true,multiSort:true,remoteFilter:true,remoteSort:true,pageSize:10,pageList:[10,20,50,100],clientPaging:false,fit:true">
                            <thead data-options="frozen:true">
                                <tr>
                                    <th data-options="field:'ck',checkbox:true"></th>
                                </tr>
                            </thead>
                            <thead>
                                <tr>
                                    <th data-options="field:'username',sortable:true,width:200">Nama</th>
                                    <th data-options="field:'nip',sortable:true,width:150,align:'center'">NIP</th>
                                    <th data-options="field:'nama_sunit',sortable:true,width:100">Unit</th>
                                    <th data-options="field:'nama_sjab',sortable:true,width:100">Jabatan</th>
                                </tr>
                            </thead>
                        </table>
                        <!-- grid end -->
                    </div>
                </div>

            </div><!-- end panel main content -->
        </div>
    </div>

    <div class="col-xl-6">
        <div id="panel-2" class="panel">
            <div class="panel-hdr border-faded border-top-1 border-right-0 border-left-0 shadow-0">
                <h2>Data Privileges</h2>
                <div class="panel-toolbar pr-3">
                    <ul class="nav nav-pills border-bottom-0" role="tablist">
                        <li class="nav-item">
                            <?= form_button('reload', '<i class="fal fa-sync"></i>', 'reload_datagrid_am()') ?>&nbsp;
                        </li>
                        <?php if ($ubah == 1) { ?>
                        <li class="nav-item">
                            <button type="button" class="btn btn-default waves-effect waves-themed" onclick="edit_priv()"><i class="fal fa-edit"></i></button>&nbsp;
                        </li>
                        <?php } ?>
                        <li class="nav-item">
                            <?= form_button('delete', '<i class="fal fa-trash-alt"></i>', 'delete_priv()') ?>
                        </li>
                    </ul>
                </div>
            </div><!-- end panel hdr -->

            <div class="panel-container show">
                <div class="panel-content">
                    <div id="panelfit-2" data-options="border:false">
                        <!-- grid start -->
                        <table id="datagrid_am" toolbar="#toolbar_am" url="<?= site_url('admin/user_priv/datagrid_am') ?>" data-options="nowrap:true,striped:false,ctrlSelect:true,rownumbers:true,pagination:true,multiSort:true,remoteFilter:true,remoteSort:true,pageSize:10,pageList:[10,20,50,100],clientPaging:false,fit:true">
                            <thead data-options="frozen:true">
                                <tr>
                                    <th data-options="field:'ck',checkbox:true"></th>
                                </tr>
                            </thead>
                            <thead>
                                <tr>
                                    <th data-options="field:'id_ug',sortable:true,hidden:true">ID UG</th>
                                    <th data-options="field:'group_id',sortable:true,hidden:true">Group ID</th>
                                    <th data-options="field:'user_id',sortable:true,hidden:true">User ID</th>
                                    <th data-options="field:'nama_modul',sortable:true,width:200">Nama Modul</th>
                                    <th data-options="field:'nama_group',sortable:true,width:200">Nama Group</th>
                                    <th data-options="field:'ket_rg',sortable:true,width:250">Keterangan</th>
                                </tr>
                            </thead>
                        </table>
                        <!-- grid end -->
                    </div>
                </div>
            </div><!-- end panel main content -->
        </div>
    </div>
</div>

<!-- MODAL REKAM -->
<div id="modal-rekam" class="modal fade default-example-modal-left-lg" data-backdrop="static" tabindex="-1" style="display: none;" aria-hidden="true">
    <div class="modal-dialog modal-dialog-left modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title h4">Rekam Data Privileges User</h5>
            </div>
            
            <?= form_open('', 'id="form_rekam"') ?>
                <div class="modal-body">
                    <div class="table-responsive">
                        <table class="table">
                            <tr>
                                <td>Nama</td>
                                <td>:</td>
                                <td class="nama"></td>
                            </tr>
                            <tr>
                                <td>NIP</td>
                                <td>:</td>
                                <td class="nip"></td>
                            </tr>
                            <tr>
                                <td>Unit/Jabatan</td>
                                <td>:</td>
                                <td>
                                    <span class="unit"></span>&nbsp;/&nbsp;
                                    <span class="jabatan"></span>
                                </td>
                            </tr>
                        </table>
                    </div>                
                    <div class="table-responsive">
                        <table id="tb-modul" class="table table-bordered">
                            <thead>
                                <tr>
                                    <th width="70" class="text-center">No.</th>
                                    <th width="300">Modul</th>
                                    <th>Role</th>
                                    <th width="100" class="text-center">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                
                            </tbody>
                        </table>
                    </div>
                    <hr/>
                </div><!-- end modal body -->
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary waves-effect waves-themed" data-dismiss="modal">Close</button>
                    <button type="submit" id="btn_usersx" class="btn btn-primary waves-effect waves-themed">
                      Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>
</div><!-- END MODAL REKAM -->

<!-- MODAL EDIT -->
<div id="modal-ubah" class="modal fade default-example-modal-right" tabindex="-1" style="display: none;" aria-hidden="true">
    <div class="modal-dialog modal-dialog-right">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title h4">Update Data Privilege</h5>
            </div>
         
            <?= form_open('', 'id="form_ubah"') ?>
                <div class="modal-body">
                    <div class="form-group" id="fg_nama_modul">
                        <label class="control-label" for="nama_modul">Nama Modul :</label>
                        <input type="text" id="nama_modul" value="" disabled class="form-control">
                    </div>
                    <div class="form-group" id="fg_group_id">
                        <label class="control-label" for="group_id">Role :</label>
                        <select class="form-control" id="group_id" name="group_id">
                            <option value="">Pilih Role...</option>
                        </select>
                    </div>
                    <hr/>
                </div><!-- end modal body -->
                <div class="modal-footer">
                   <button type="button" class="btn btn-secondary waves-effect waves-themed" data-dismiss="modal">Close</button>
                   <button type="submit" id="btn_ubah" class="btn btn-primary waves-effect waves-themed">
                      Save Changes
                    </button>
                </div>
            </form>

        </div>
    </div>
</div><!-- END MODAL EDIT -->
<?= $this->endSection() ?>
<!-- main section end-->

<!-- pageScripts section start-->
<?= $this->section('pageScripts') ?>

<script type="text/javascript" src="<?= base_url('smart/dist/adlte/jquery-easyui-1.10.17/jquery.easyui.min.js') ?>"></script>
<script type="text/javascript" src="<?= base_url('smart/dist/adlte/jquery-easyui-1.10.17/datagrid-filter-1.0.6/datagrid-filter.js') ?>"></script>

<script type="text/javascript">
   $(document).ready(function () {
        adjustpanelfit();
    })

    $(window).resize(function() {
        adjustpanelfit();
    });

    function adjustpanelfit(){
        var height = $(window).height();
        $('#panelfit-1, #panelfit-2').panel({
            height:height - 400
        });
    }
</script>

<script type="text/javascript">
    /*datagrid user*/
    var datagrid_user = $('#datagrid_user').datagrid({
        queryParams: {
            "<?= csrf_token() ?>": "<?= csrf_hash() ?>",
        },
        onDblClickRow : function(index,row){
            show_userpriv();
        }
    });
    datagrid_user.datagrid('enableFilter');

    /*function datagrid user*/
    //double klik row rolegroup tarik data child
    function show_userpriv()
    {
        var row = $('#datagrid_user').datagrid('getSelected');
        if (row) {
            var id_usr = row.id;
            $.ajax({
                url: '<?= base_url('admin/user_priv/datagrid_am') ?>',
                type: "post",
                dataType: 'json',
                data: {
                    id_usr: id_usr,
                    "<?= csrf_token() ?>": "<?= csrf_hash() ?>",
                },
                error: function (xhr, status, message) {
                    $.messager.alert(status,message,'warning');
                },
                success: function(res) {
                    $('#datagrid_am').datagrid('loadData', res);
                }
            });
        } else {
          $.messager.alert('<?= lang('App.warning') ?>','<?= lang('App.select_data') ?>','warning');
        }
    }

    /*reload datagrid usergroup*/
    function reload_datagrid_user()
    {
        $('#datagrid_user').datagrid('removeFilterRule');
        $('#datagrid_user').datagrid('load');
    }

    /*datagrid am =====================================*/
    var datagrid_am = $('#datagrid_am').datagrid({
        queryParams: {
            "<?= csrf_token() ?>": "<?= csrf_hash() ?>",
        },

        onDblClickRow : function(index,row){
            //do nothing
        }
    });
    datagrid_am.datagrid('enableFilter');

    /*reload datagrid am*/
    function reload_datagrid_am()
    {
        $('#datagrid_am').datagrid('removeFilterRule');
        $('#datagrid_am').datagrid('load');
    }
</script>

<?php if ($rekam == 1) { ?>
<!-- FUNCTION REKAM -->
<script type="text/javascript">
    let id_usr = null;

    function rekam_data()
    {
        var row = $('#datagrid_user').datagrid('getSelected');
        if (row) {
            id_usr = row.id;
            $.ajax({
                url: '<?= base_url('admin/user_priv/get_modul') ?>',
                type: "post",
                dataType: 'json',
                data: {
                    id_usr: id_usr,
                    "<?= csrf_token() ?>": "<?= csrf_hash() ?>",
                },
                error: function (xhr, status, message) {
                    $.messager.alert(status,message,'warning');
                },
                success: function(res) {
                    const dtmodul = res.dtmodul;
                    let tbody = $('#tb-modul tbody');
                    tbody.empty();

                    // Variabel untuk nomor urut
                    let no = 1;

                    // Iterasi melalui setiap modul
                    $.each(dtmodul, function(key, modul) {
                        // Membuat string untuk role
                        let roleOptions = modul.role.map(role => `<option value="${role.id_group}">${role.nama_group}</option>`).join('');

                        // Menambahkan baris ke tbody
                        tbody.append(`
                            <tr>
                                <td class="text-center">${no}</td>
                                <td>${modul.nama_modul}</td>
                                <td>
                                    <select class="form-control" name="id_group[]">
                                        <option value="">Pilih Role</option>
                                        ${roleOptions}
                                    </select>
                                </td>
                                <td class="text-center">
                                    <button class="btn btn-danger btn-delete" data-id="${modul.id_modul}"><i class="fal fa-trash"></i></button>
                                </td>
                            </tr>
                        `);

                        no++; // Increment nomor urut
                    });

                    // Event listener untuk tombol delete
                    $('.btn-delete').on('click', function() {
                        $(this).closest('tr').remove();
                    });

                    $('.nama').html(row.username);
                    $('.nip').html(row.nip);
                    $('.unit').html(row.nama_sunit);
                    $('.jabatan').html(row.nama_sjab);
                    $('#modal-rekam').modal('show');
                }
            });
        } else {
            $.messager.alert('<?= lang('App.warning') ?>','<?= lang('App.select_data') ?>','warning');
        }
    }

    $("#form_rekam").submit(function(e){
        e.preventDefault();
        // Mengambil semua id_group
        let idGroup = [];

        $('select[name="id_group[]"]').each(function() {
            idGroup.push($(this).val());
        });

        // Pastikan id_group dipilih
        if (idGroup.includes("")) {
            $.messager.alert('<?= lang('App.warning') ?>','<?= lang('App.select_data') ?>','warning');
            return;
        }

        // Data yang akan dikirim ke server
        let formData = {
            id_usr: id_usr,
            id_group: idGroup,
            "<?= csrf_token() ?>": "<?= csrf_hash() ?>"
        };

        var url = '<?= $link_rekam ?>';
        $.ajax({
            url: url,
            type: "post",
            dataType: 'json',
            data: formData,
            beforeSend  : function() {
                BtnLoading($("#btn_usersx"));
            },
            success: function(result) {
                toastr.success(result.message, 'Updated!!', {timeOut: 3000});
                $('#modal-rekam').modal('hide');
                $('#datagrid_users').datagrid('load');
                $('#datagrid_am').datagrid('load');
            },
            complete: function() {
                BtnReset($("#btn_usersx"));
            }
        });
    });
</script>
<?php } ?>

<?php if ($ubah == 1) { ?>
<!-- FUNCTION UBAH -->
<script type="text/javascript">
    let sel_id_ug = null;

    function edit_priv()
    {
        var row = $('#datagrid_am').datagrid('getSelected');
        if (row) {
            var id_modul = row.id_modul;
            $.ajax({
                url: '<?= base_url('admin/user_priv/get_role') ?>',
                type: "post",
                dataType: 'json',
                data: {
                    id_modul: id_modul,
                    "<?= csrf_token() ?>": "<?= csrf_hash() ?>",
                },
                error: function (xhr, status, message) {
                    $.messager.alert(status,message,'warning');
                },
                success: function(res) {
                    let selectRole = $('#group_id');
                    selectRole.empty();
                    selectRole.append('<option value="">Pilih Role...</option>');
                    // Iterasi melalui data respons untuk menambahkan opsi
                    $.each(res, function(index, role) {
                        selectRole.append(`<option value="${role.id_group}">${role.nama_group}</option>`);
                    });

                    // Set opsi yang dipilih sesuai dengan group_id saat ini
                    if (row.group_id) {
                        selectRole.val(row.group_id).trigger('change'); // Set nilai dan trigger change
                    }
                }
            });

            sel_id_ug = row.id_ug;
            $('#nama_modul').val(row.nama_modul);
            $('#modal-ubah').modal('show');
        } else {
            $.messager.alert('<?= lang('App.warning') ?>','<?= lang('App.select_data') ?>','warning');
        }
    }

    $("#form_ubah").submit(function(e){
        e.preventDefault();
        var url = '<?= $link_ubah ?>'
        var formData = $(this).serialize();
        formData += '&id_ug=' + encodeURIComponent(sel_id_ug);
        $.ajax({
            url: url,
            type: "post",
            dataType: 'json',
            data: formData,
            beforeSend  : function() {
                $(".form-group").removeClass("has-error");
                $(".error-message").html('').hide();
                BtnLoading($("#btn_ubah"));
            },
            error: function (xhr, status, message) {
                var res = JSON.parse(xhr.responseText);
                $(res.messages).each(function(i,val){
                    var inputname = Object.keys(val)[0];
                    $.each(val,function(k,v){
                        $("#r"+inputname).focus();
                        $("#fgr_"+k).addClass("has-error");
                        $("#rem_"+k).html(v).fadeIn();
                    });
                });
            },
            success: function(result) {
                toastr.success(result.message, 'Updated!!', {timeOut: 3000});
                $('#modal-ubah').modal('hide');
                $('#datagrid_am').datagrid('load');
            },
            complete: function() {
                BtnReset($("#btn_ubah"));
            }
        });
    });
</script>
<?php } ?>

<?php if ($hapus == 1) { ?>
<!-- FUNCTION HAPUS -->
<script type="text/javascript">
    function delete_priv()
    {
        var rows = $('#datagrid_am').datagrid('getSelections');
        var ids = [];
        for(var j=0;j<rows.length;j++){
            ids[j] = rows[j].id_ug;
        }
        if (ids.length > 0) {
            $.messager.confirm('<?= lang('App.delete') ?>', '<?= lang('App.delete') ?> ' + rows.length + ' data ?', function(r){
                if (r){
                    $.ajax({
                        url: '<?= $link_hapus ?>',
                        type: "post",
                        dataType: 'json',
                        data: {
                            ids: ids,
                            "<?= csrf_token() ?>": "<?= csrf_hash() ?>",
                        },
                        error: function (xhr, status, message) {
                            $.messager.alert(status,message,'warning');
                        },
                        success: function(res) {
                            toastr.success(res.message, 'Updated!!', {timeOut: 3000});
                            $('#datagrid_am').datagrid('reload');
                        }
                    });
                }
            });
        } else {
          $.messager.alert('<?= lang('App.warning') ?>','<?= lang('App.select_data') ?>','warning');
        }
    }
</script>
<?php } ?>

<?= $this->endSection() ?>
<!-- pageScripts section end-->