{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{title}}</title>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>

    
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.css">
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.Default.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol/dist/L.Control.Locate.min.css" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
    <link rel="stylesheet" href="https://unpkg.com/esri-leaflet-geocoder@2.3.3/dist/esri-leaflet-geocoder.css">

    <script src="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol/dist/L.Control.Locate.min.js" charset="utf-8"></script>

    <!-- Global stylesheets -->
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900" rel="stylesheet" type="text/css">
    <link href="{% static 'css/icons/icomoon/styles.css' %}" rel="stylesheet" type="text/css">
    <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet" type="text/css">
    <link href="{% static 'css/core.css' %}" rel="stylesheet" type="text/css">
    <link href="{% static 'css/components.css' %}" rel="stylesheet" type="text/css">
    <link href="{% static 'css/colors.css' %}" rel="stylesheet" type="text/css">
    <script src="{% static 'js/Leaflet.Editables.js' %}"></script>

    <!-- /global stylesheets -->
    <style>
        .page-container {
            padding: 0;
            height: 100%;
        }

        .modal-backdrop {
            z-index: -999!important;
        }
        
        .sidebar {
            padding: 0;
        }
        
        .form-group {
            margin-bottom: 0px;
        }
        
        .panel-body {
            padding: 0px 20px;
        }
        
        .row {
            margin-left: 0px;
            margin-right: 0px;
        }
        
        .modal-colors{
            background-color: #1a222f;
        }

        .lbl-top{
            margin-top: 10px;
        }

        .select2-selection--multiple:not([class*=bg-]) .select2-selection__choice {
            background-color: #eee;
            color: #333333;
            margin-top: 3px;
            margin-bottom: 3px;
            border-radius: 0px;
        }

        .page_loader {
            position: fixed;
            background: url('../../static/img/loadingz.gif') 50% 50% no-repeat rgb(249, 249, 249);
            left: 0px;
            top: 0px;
            width: 100%;
            height: 100%;
            z-index: 9999;
            opacity: .5;
        }
        
         ::-webkit-scrollbar {
            width: 10px;
        }
        /* Track */
        
         ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        /* Handle */
        
         ::-webkit-scrollbar-thumb {
            background: #888;
        }
        /* Handle on hover */
        
         ::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
    </style>
</head>

<body style="padding-right: 0px !important;">

    <!-- Main navbar -->
    <!-- Main navbar -->
    <div class="navbar navbar-inverse">
        <div class="navbar-header">
            <a class="navbar-brand" href="{% url 'apps:dashboard' %}">
                <!-- <h3>NationalAddress</h3> -->
                <i class=" icon-location4"></i>
                <b>&nbsp;&nbsp;OKU-GISs</b>
            </a>

            <ul class="nav navbar-nav pull-right visible-xs-block">
                <li><a data-toggle="collapse" data-target="#navbar-mobile"><i class="icon-tree5"></i></a></li>
            </ul>
        </div>
        <div class="navbar-collapse collapse" id="navbar-mobile">

            <p class="navbar-text"><span class="label bg-success-400">Online</span></p>
            <ul class="nav navbar-nav navbar-right">
                <li class="dropdown dropdown-user">
                    <a class="dropdown-toggle" data-toggle="dropdown">
                        <img src="{% static 'img/placeholder.jpg' %}" alt="">
                        <span>{{user.username}}</span>
                        <i class="caret"></i>
                    </a>

                    <ul class="dropdown-menu dropdown-menu-right">
                        <li><a href="#"><i class="icon-user-plus"></i> My profile</a></li>
                        <li><a href="#"><i class="icon-cog5"></i> Account settings</a></li>
                        <li class="divider"></li>
                        <li><a href="{% url 'logout' %}"><i class="icon-cog5"></i> Logout</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
    <!-- /main navbar -->


    <!-- Page container -->
    <div class="page-container">

        <!-- Page content -->
        <div class="page-content">

            <!-- Main sidebar -->
            <div class="sidebar sidebar-main" style="height: 95vh;
            min-height: 607px;">
                <div class="sidebar-content" style="height: 100%;">

                    <!-- User menu -->
                    <div class="sidebar-user">
                        <div class="category-content">
                            <div class="media">
                                <a href="#" class="media-left"><img src="{% static '/img/placeholder.jpg' %}" class="img-circle img-sm" alt=""></a>
                                <div class="media-body">
                                    <span class="media-heading text-semibold">{{user.username}}</span>
                                    <div class="text-size-mini text-muted">
                                        <i class="icon-pin text-size-small"></i>
                                    </div>
                                </div>

                                <div class="media-right media-middle">
                                    <ul class="icons-list">
                                        <li>
                                            <a href="#"><i class="icon-cog3"></i></a>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- /user menu -->


                    <!-- Main navigation -->
                    <div class="sidebar-category sidebar-category-visible">
                        <div class="category-content no-padding">
                            <ul class="navigation navigation-main navigation-accordion">

                                <!-- Main -->
                                <li class="navigation-header"> <i class="icon-menu" title="Main pages"></i></li>
                                <li><a href="?page=user" class="tablinks"  id="defaultOpen"><i class="icon-user"></i><span>User Management</span></a></li>
                                <li><a href="?page=group" class="tablinks"  id="defaultOpen"><i class="icon-users4"></i><span>Group</span></a></li>
                                <!-- <li><a class="tablinks" onclick="openInfo(event, 'info-penduduk')" id="defaultOpen"><span>Kependudukan</span></a></li>
                                <li><a class="tablinks" onclick="openInfo(event, 'info-pendidikan')" id="defaultOpen"><span>Pendidikan</span></a></li>
                                <li><a class="tablinks" onclick="openInfo(event, 'info-pekerjaan')" id="defaultOpen"><span>Pekerjaan</span></a></li>
                                <li><a class="tablinks" onclick="openInfo(event, 'info-poi')" id="defaultOpen"><span>POI</span></a></li> -->
                                
                            <!-- /page kits -->

                            </ul>
                        </div>
                    </div>
                    <!-- /main navigation -->

                </div>
            </div>
            <!-- /main sidebar -->


            <!-- Main content -->
            <!-- User management Tab -->
            <div class="content-wrapper" id="info-maps">
                <div>
                    <!-- Page header -->
                    <div class="page-header page-header-default" style="margin-bottom: 0px;">
                        <div class="breadcrumb-line">
                            <ul class="breadcrumb">
                                <li>User Management</li>
                            </ul>
                        </div>
                    </div>
                    <!-- /page header -->

                    <!-- Content area -->
                    <div class="content" style="padding: 15px;">
                        <!-- Main charts -->
                        <!-- Sales stats -->
                        <div class="panel panel-flat" style="display: none;">
                            <div class="panel-heading">
                                <h6 class="panel-title">Table User</h6>
                                <button id="modalAddButton" class="btn btn-primary btn-sm" value="SAVE" style="bottom: 15px; float: right; display:none;" data-toggle="modal" data-target="#modal_theme_info"></button>
                            </div>

                            <hr style="margin-top: 0px;">

                            <div class="panel-body">
                                <table class="table table-responsive datatable-show-all table-sm" id="userList" style="word-wrap:break-word;">
                                    <thead>
                                        <tr>
                                            <th>No.</th>
                                            <th>Username</th>
                                            <th>Name</th>
                                            <th>Email</th>
                                            <th>Group</th>
                                            <th>Last login</th>
                                            <th>Status</th>
                                            <th class="text-center">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {% for user in data %}
                                        <tr>
                                            <td>{{forloop.counter}}</td>
                                            <td>{{user.username}}</td>
                                            <td>{{user.name}}</td>
                                            <td>{{user.email}}</td>
                                            <td>{{user.group}}</td>
                                            <td>{{user.last}}</td>
                                            <td>
                                                {% if user.isactive == True %}
                                                <span class="label label-success">
                                                    Active
                                                </span>
                                                {% else %}
                                                <span class="label label-danger">
                                                    Inactive
                                                </span>
                                                {% endif %}
                                            </td>
                                            <td class="text-center">
                                                <ul class="icons-list">
                                                    <li class="dropdown">
                                                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                                            <i class="icon-menu9"></i>
                                                        </a>
                            
                                                        <ul class="dropdown-menu dropdown-menu-right">
                                                            <li><a onclick="switchuserstatus('{{user.id}}, {{user.isactive}}')" ><i class="icon-user-block"></i> Switch user status</a></li>
                                                            <li><a onclick="loaduserbyid('{{user.id}}')"><i class="icon-users"></i> Edit user</a></li>
                                                        </ul>
                                                    </li>
                                                </ul>
                                            </td>
                                        </tr>
                                        {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                            <!-- /form validation -->
                        </div>
                    </div>
                    <!-- /main charts -->
                </div>
            </div>

            <!-- end user management tab -->

            <div class="content-wrapper" id="usergroup" style="display: none;">
                <div>
                    <!-- Page header -->
                    <div class="page-header page-header-default" style="margin-bottom: 0px;">
                        <div class="breadcrumb-line">
                            <ul class="breadcrumb">
                                <li>Group</li>
                            </ul>
                        </div>
                    </div>
                    <!-- /page header -->

                    <!-- Content area -->
                    <div class="content" style="padding: 15px;">
                        <!-- Main charts -->
                        <!-- Sales stats -->
                        <div class="panel panel-flat" style="display: none;">
                            <div class="panel-heading">
                                <h6 class="panel-title">Table Group</h6>
                                <button id="modalAddButtong" class="btn btn-primary btn-sm" value="SAVE" style="bottom: 15px; float: right; display:none;" data-toggle="modal" data-target="#modal_group"></button>
                            </div>

                            <hr style="margin-top: 0px;">

                            <div class="panel-body">
                                <table class="table table-responsive datatable-groups table-sm" id="usergroup" >
                                    <thead>
                                        <tr>
                                            <th>No.</th>
                                            <th>Name</th>
                                            <th class="text-center">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {% for group in dataGroup %}
                                        <tr>
                                            <td>{{forloop.counter}}</td>
                                            <td>{{group.name}}</td>
                                            <td class="text-center">
                                                <ul class="icons-list">
                                                    <li class="dropdown">
                                                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                                            <i class="icon-menu9"></i>
                                                        </a>
                            
                                                        <ul class="dropdown-menu dropdown-menu-right">
                                                            <li><a onclick="deletegroup('{{group.id}}', '{{group.name}}')" ><i class="icon-user-block"></i> Delete group</a></li>
                                                            <li><a onclick="showmodalgroup('{{group.id}}', '{{group.name}}')"><i class="icon-users"></i> Edit group</a></li>
                                                        </ul>
                                                    </li>
                                                </ul>
                                            </td>
                                        </tr>
                                        {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                            <!-- /form validation -->
                        </div>
                    </div>
                    <!-- /main charts -->
                </div>
            </div>
            
            <!-- /main content -->
        </div>
        <!-- /page content -->
    </div>
    <!-- /page container -->

    <div id="modal_theme_info" class="modal fade">
        <div class="modal-dialog md" style="margin-top: 100px;">
            <div class="modal-content">
                <div class="modal-header bg-info" style="background-color: #1a222f !important;">
                    <button type="button" class="close" data-dismiss="modal" onclick="destroyfade()">&times;</button>
                    <h6 class="modal-title modstit">Modal Tambah User</h6>
                </div>

                <div class="modal-body" style="max-height: 450px;overflow-y: auto;">
                        <input type="hidden" id="iduser">
                        
                        <div class="row">
                            <div class="form-group">
                                <label class="col-lg-3 control-label lbl-top" >Username</label>
                                <div class="col-lg-9">
                                    <input id="inUsername" type="text" class="form-control" value=""required>
                                </div>
                            </div>
                        </div>
    
                        <div class="row">
                            <div class="form-group">
                                <label class="col-lg-3 control-label lbl-top" >First Name</label>
                                <div class="col-lg-9">
                                    <input id="inNameF" type="text" class="form-control" value=""required>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="form-group">
                                <label class="col-lg-3 control-label lbl-top" >Last Name</label>
                                <div class="col-lg-9">
                                    <input id="inNameL" type="text" class="form-control" value=""required>
                                </div>
                            </div>
                        </div>
    
                        <div class="row">
                            <div class="form-group">
                                <label class="col-lg-3 control-label lbl-top" >Email</label>
                                <div class="col-lg-9">
                                    <input id="inEmail" type="text" class="form-control" value=""required>
                                </div>
                            </div>
                        </div>

                        <div class="row" style="margin-top: 20px;">
                            <div class="form-group">
                                <label class="col-lg-3 control-label">Staff</label>
                                <div class="col-lg-9">
                                    <label class="radio-inline">
                                        <input type="radio" class="styled" value="true" name="isStaff" checked="checked">
                                        Ya
                                    </label>
    
                                    <label class="radio-inline">
                                        <input type="radio" class="styled" value="false" name="isStaff">
                                        Tidak
                                    </label>
                                </div>
                            </div>
                        </div>
    
                        <div class="row">
                            <div class="form-group" style="margin-top: 10px !important;">
                                <label class="col-lg-3 control-label lbl-top" >Groups</label>
                                <div class="col-lg-9" >
                                    <select style="border-bottom: 1px solid rgb(83, 83, 83) !important;" id="select_group" data-placeholder="select group.." class="select-size-xs">
                                            <option></option>
                                    </select>
                                </div>
                            </div>
                        </div>
                   
                </div>
                <hr>
                <div class="modal-footer">
                    <button type="button" class="btn btn-link" data-dismiss="modal" onclick="destroyfade()">Close</button>
                    <button type="button" class="btn btn-info" id="saveuser">Save changes</button>
                </div>
            </div>
        </div>
    </div>

    <div id="modal_group" class="modal fade">
        <div class="modal-dialog md" style="margin-top: 200px;">
            <div class="modal-content">
                <div class="modal-header bg-info" style="background-color: #1a222f !important;">
                    <button type="button" class="close" data-dismiss="modal" onclick="destroyfade()">&times;</button>
                    <h6 class="modal-title modstitg">Modal Tambah Group</h6>
                </div>

                <div class="modal-body" style="max-height: 450px;overflow-y: auto;">
                        <input type="hidden" id="idgroup">

                        <div class="row">
                            <div class="form-group">
                                <label class="col-lg-3 control-label lbl-top" >Nama Group</label>
                                <div class="col-lg-9">
                                    <input id="inGroupName" type="text" class="form-control" value=""required>
                                </div>
                            </div>
                        </div>

                        <div class>

                        <div class="row" id="container_sparent">
                            <div class="form-group" style="margin-top: 10px !important;">
                                <label class="col-lg-3 control-label lbl-top" >Group Parent</label>
                                <div class="col-lg-9" >
                                    <select style="border-bottom: 1px solid rgb(83, 83, 83) !important;" id="select_group_parent" data-placeholder="select group.." class="select-size-xs">
                                            <option></option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                </div>
                <hr>
                <div class="modal-footer">
                    <button type="button" class="btn btn-link" data-dismiss="modal" onclick="destroyfade()">Close</button>
                    <button type="button" class="btn btn-info" id="savegroup">Save changes</button>
                </div>
            </div>
        </div>
    </div>


    <div class="page_loader"></div>

    <!-- Core JS files -->
    <script type="text/javascript" src="{% static 'js/plugins/loaders/pace.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/core/libraries/jquery.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/core/libraries/bootstrap.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/plugins/loaders/blockui.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/plugins/ui/nicescroll.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/plugins/ui/drilldown.js' %}"></script>
    <!-- /core JS files -->

    <script src="https://use.fontawesome.com/d232835e93.js"></script>

    <script src="https://unpkg.com/leaflet.markercluster@1.4.1/dist/leaflet.markercluster.js"></script>
    <!-- <script src="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol/dist/L.Control.Locate.min.js" charset="utf-8"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet.locatecontrol/dist/L.Control.Locate.min.js" charset="utf-8"></script> -->

    <script src="https://unpkg.com/esri-leaflet@2.5.1/dist/esri-leaflet.js"></script>
    <script src="https://unpkg.com/esri-leaflet-geocoder@2.3.3/dist/esri-leaflet-geocoder.js"></script>
    <script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw-src.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.6/handlebars.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.fullscreen/1.4.2/Control.FullScreen.min.js"></script>


    <!-- Theme JS files -->
    <script type="text/javascript" src="{% static 'js/plugins/visualization/d3/d3.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/plugins/visualization/d3/d3_tooltip.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/plugins/forms/styling/switchery.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/plugins/forms/styling/uniform.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/plugins/forms/selects/bootstrap_multiselect.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/plugins/ui/moment/moment.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/plugins/pickers/daterangepicker.js' %}"></script>

    
    <!-- <script type="text/javascript" src="{% static 'js/plugins/ui/ripple.min.js' %}"></script> -->
    <!-- /theme JS files -->
    {% include 'includes/scripts.html' %}
    <script src="{% static 'js/leaflet-bing-layer.js' %}"></script>
    <!-- <script src="https://unpkg.com/sweetalert/dists/sweetalert.min.js"></script> -->

    <script type="text/javascript" src="{% static 'js/core/libraries/jquery_ui/interactions.min.js' %}"></script>
	<script type="text/javascript" src="{% static 'js/plugins/forms/selects/select2.min.js' %}"></script>

	
	<script type="text/javascript" src="{% static 'js/pages/form_select2.js' %}"></script>
</body>

</html>

<script>
    // file.onchange = evt => {
    //     const [fil] = file.files
    //     if (fil) {
    //         blah.src = URL.createObjectURL(fil)
    //     }
    // }
    

    jQuery(document).ajaxSend(function(event, xhr, settings) {
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        function sameOrigin(url) {
            // url could be relative or scheme relative or absolute
            var host = document.location.host; // host + port
            var protocol = document.location.protocol;
            var sr_origin = '//' + host;
            var origin = protocol + sr_origin;
            // Allow absolute or scheme relative URLs to same origin
            return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                // or any other URL that isn't scheme relative or absolute i.e relative.
                !(/^(\/\/|http:|https:).*/.test(url));
        }

        function safeMethod(method) {
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    });

    function openInfo(evt, infName) {
        var i, tabcontent, tablinks;
        tabcontent = document.getElementsByClassName("content-wrapper");
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].style.display = "none";
        }
        tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" active", "");
        }
        document.getElementById(infName).style.display = "block";
        evt.currentTarget.className += " active";
    }

    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const page = urlParams.get('page')
    
    if(page == "group"){
        $("#usergroup").css("display", "block");
        $("#info-maps").css("display", "none");
    }else{
        $("#usergroup").css("display", "none");
        $("#info-maps").css("display", "block");
    }
    
    
    function destroyfade(){
        $(".modal-backdrop").css("display","none")
        $(".modal-backdrop").removeClass('show');
        $("body").css('padding-right','0px !important')
    }

    $('.datatable-show-all').DataTable({
        autoWidth: false,
        columnDefs: [
            { 
                orderable: false,
                width: '20px',
                targets: [ 0 ],
                
            },
            // {
            //     width: '100px',
            //     targets: [ 4 ]
            // },
            { 
                orderable: false,
                width: '20px',
                targets: [ 6 ],
                
            },
            { 
                orderable: false,
                width: '20px',
                targets: [ 7 ],
                
            },
        ],
        dom: '<"float-left"B>frtip',
        buttons: [
            {
                text: 'Tambah User',
                action: function ( e, dt, node, config ) {
                    $("#modalAddButton").click()
                    $("#inUsername").attr("disabled", false);
                    $("#inUsername").val(null);
                    $("#inNameF").val(null);
                    $("#inNameL").val(null);
                    $("#inEmail").val(null);
                    $("#iduser").val(null);
                    $(".modstit").html("Tambah User")
                    loadGroups(null)
                }
            }
        ],
        language: {
            search: '<span>Filter:</span> _INPUT_',
            searchPlaceholder: 'Type to filter...',
            lengthMenu: '<span>Show:</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
        
    });

    
    $('.datatable-groups').DataTable({
        autoWidth: false,
        columnDefs: [
            { 
                orderable: false,
                width: '100px',
                targets: [ 2 ]
            },
            {
                orderable: false,
                width: '100px',
                targets: [ 0 ]
            }
        ],
        dom: '<"float-left"B>frtip',
        buttons: [
            {
                text: 'Tambah Group',
                action: function ( e, dt, node, config ) {
                    $("#modalAddButtong").click();
                    $("#idgroup").val(null);
                    $(".modstitg").html("Tambah Group")
                    $("#inGroupName").val(null)
                    $("#container_sparent").css("display", "block")
                    loadGroups(null)
                }
            }
        ],
        language: {
            search: '<span>Filter:</span> _INPUT_',
            searchPlaceholder: 'Type to filter...',
            lengthMenu: '<span>Show:</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
        
    });

    $("#modalAddButton").click(function(){
        $("body").css("padding-right","0px !important")
    })

    $("#saveuser").on("click", function(){
        addUser()
    })

    function addUser(){
        var isObject = {};
        var ars  = ''
        var group = $("#select_group").val();
        var iduser = $("#iduser").val();
        console.log(group);
        if(iduser){
            isObject.id = iduser;
        }

        // for(i in group){
        //     if(i < group.length-1){
        //         ars += group[i]+"~";
        //     }else{
        //         ars += group[i];
        //     }
        // }
        // return false
        isObject['username']   = $("#inUsername").val();
        isObject['first_name'] = $("#inNameF").val();
        isObject['last_name']  = $("#inNameL").val();
        isObject['email']      = $("#inEmail").val();
        isObject.group         = group
        isObject.isStaff       = $('input[name="isStaff"]:checked').val();
        
    
        console.log(isObject);
        

        $.ajax({
            url: "{% url 'adduser' %}",
            data: isObject,
            dataType: 'json',
            type: 'post',
            success: function(data) {
                let response = data;

                if(response.code == 0){
                    $("#modal_theme_info").modal('toggle');
                    destroyfade();

                    swal({
                        title : response.info, 
                        text  : response.data, 
                        type  : "success",
                        icon  : "success",
                        confirmButtonColor: "#00BCD4"
                    }).then((isok) => {
                        location.reload();
                    })
                }else{
                    swal({
                        title : response.info, 
                        text  : response.data, 
                        type  : "alert",
                        icon  : "error",
                        confirmButtonColor: "#00BCD4"
                    })
                    
                }
            }
        });
    }

    $("#select_group").on("click", function(e){
        e.preventDefault()
    })

    function loadGroups(isSelect){
        var isObject = {}
        console.log(isSelect)
        isObject.func_name = "loadGroups";

        $.ajax({
            url: "{% url 'getallGroups' %}",
            data: isObject,
            dataType: 'json',
            type: 'post',
            success: function(data) {
                
                let response = data;
                console.log(response)
                if(response.code == 0){
                    var groups = response.data;
                    var html   = `<option value="null" selected disabled>-- Pilih Group --</option>`;
                    for(i in groups){
                        if(isSelect){
                            if(isSelect.length>=1){
                                for(j in isSelect){
                                    if(isSelect[j] == groups[i]){
                                        html += `<option value="`+groups[i]+`" selected>`+groups[i]+`</option>`;
                                        console.log(groups[i])
                                    }else{
                                        html += `<option value="`+groups[i]+`">`+groups[i]+`</option>`;
                                    }
                                }
                            }else{
                                html += `<option value="`+groups[i]+`">`+groups[i]+`</option>`;
                            }
                            
                            

                        }else{
                            html += `<option value="`+groups[i]+`">`+groups[i]+`</option>`;
                        }
                        
                    }

                    $("#select_group").html(html);
                    $("#select_group_parent").html(html);
                    console.log(html)
                }else{
                    $("#select_group").html("group tidak tersedia");
                    $("#select_group_parent").html("group tidak tersedia");
                }
                
            }
        });
    }
    

    function switchuserstatus(id, isactive){
        var isObject = {}
        var params = id.split(",");

        isObject.id     = params[0];
        isObject.stat   = params[1].replace(" ", "");

        console.log(params)
        if(isObject.stat == "True"){
            var title = "Nonaktifkan";
            var text  = "User tidak akan bisa login jika dinonaktifkan!";
        }else{
            var title = "Aktifkan";
            var text  = "User dapat kembali login jika diaktifkan!";
        }
        
        swal({
            title: title+" user?",
            text: text,
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Ya!",
            cancelButtonText: "Tidak!",
            closeOnConfirm: false,
            closeOnCancel: false
        }).then((isConfirm) =>{
            console.log(isConfirm)
            if (isConfirm.value) {
            
                $.ajax({
                    url: "{% url 'switchStatus' %}",
                    data: isObject,
                    dataType: 'json',
                    type: 'post',
                    success: function(data) {
                        
                        let response = data;

                        if(isObject.stat == "True"){
                            var inf = "dinonaktifkan"
                        }else{
                            var inf = "diaktifkan"
                        }
                        if(response.code == 0){
                            swal({
                            title : "sukses", 
                            text  : "User berhasil "+inf, 
                            type  : "success",
                            icon  : "success",
                            confirmButtonColor: "#00BCD4"
                        }).then((isok) => {
                            location.reload();
                        })
                        }else{
                            alert("no data in database")
                        }
                        
                    }
                });
            } else {
                swal("Dibatalkan", "User status tidak berubah", "error");
            }
        });
        
    }

    function loaduserbyid(id){
        var isObject = {};
        $(".modstit").html("Update User")
        $("#inUsername").attr("disabled", true)

        isObject.id = id;
        $("#iduser").val(id)

        $.ajax({
            url: "{% url 'loadUserbyId' %}",
            data: isObject,
            dataType: 'json',
            type: 'post',
            success: function(data) {
                
                let response = data;
               
                if(response.code == 0){
                    var user = response.data;
                    console.log(user)
                    $("#inUsername").val(user.username);
                    $("#inNameF").val(user.firstname);
                    $("#inNameL").val(user.lastname);
                    $("#inEmail").val(user.email);
                    if(user.is_staff){
                        $('input[name=isStaff][value=true]').attr('checked', true)
                    }else{
                        $('input[name=isStaff][value=false]').attr('checked', true)
                    }
                    loadGroups(user.group)
                    $("#modalAddButton").click()
                }else{
                    
                }
                
            }
        });
    }

    loaderPage(false);

    function loaderPage(stat) {
        if (stat == true) {
            $('.page_loader').show();
        } else {
            $('.page_loader').hide();
            $(".panel-flat").css("display", "block")
        }
    };

    $("#savegroup").on("click", function(){
        addGroup();
    })

    function addGroup(){
        var isObject = {}
        var idgroup  = $("#idgroup").val();

        isObject.parent = $("#select_group_parent").val()
        isObject.name   = $("#inGroupName").val();

        if(idgroup){
            isObject.id   = idgroup;
        }
        
        console.log(isObject)
        // return false
        $.ajax({
            url: "{% url 'addGroup' %}",
            data: isObject,
            dataType: 'json',
            type: 'post',
            success: function(data) {
                let response = data;

                if(response.code == 0){
                    $("#modal_group").modal('toggle');
                    destroyfade();

                    swal({
                        title : response.info, 
                        text  : response.data, 
                        type  : "success",
                        icon  : "success",
                        confirmButtonColor: "#00BCD4"
                    }).then((isok) => {
                        window.location.href = window.location.origin+"/usermanagement/?page=group"
                    })
                }else{
                    swal({
                        title : response.info, 
                        text  : response.data, 
                        type  : "alert",
                        icon  : "error",
                        confirmButtonColor: "#00BCD4"
                    })
                    
                }
            }
        });
    }

    function showmodalgroup(id, name){
        console.log(id);
        console.log(name);

        $("#idgroup").val(id);
        $("#inGroupName").val(name);
        $(".modstitg").html("Edit Group");
        // $("#modalAddButtong").click();
        
        var isObject = {}
        isObject.id = id
        $.ajax({
            url: "{% url 'getGroupById' %}",
            data: isObject,
            dataType: 'json',
            type: 'post',
            success: function(data) {
                let response = data;

                if(response.code == 0){
                    var datas = response.data

                    if(datas.length == 0){
                        $("#container_sparent").css("display", "none")
                    }else{
                        $("#container_sparent").css("display", "block")
                    }
                    
                    loadGroups(datas)
                    $("#modalAddButtong").click();

                    
                }else{
                    swal({
                        title : response.info, 
                        text  : response.data, 
                        type  : "alert",
                        icon  : "error",
                        confirmButtonColor: "#00BCD4"
                    })
                    
                }
            }
        });
        
    }

    function deletegroup(id, group){
        var isObject = {}
        var params   = id;

        isObject.id  = params;
        
        swal({
            title: "Hapus group?",
            text: "Group "+group+" akan dihapus",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Ya!",
            cancelButtonText: "Tidak!",
            closeOnConfirm: false,
            closeOnCancel: false
        }).then((isConfirm) =>{
            console.log(isConfirm)
            if (isConfirm.value) {
            
                $.ajax({
                    url: "{% url 'deleteGroup' %}",
                    data: isObject,
                    dataType: 'json',
                    type: 'post',
                    success: function(data) {
                        
                        let response = data;

                        if(response.code == 0){
                            swal({
                            title : "sukses", 
                            text  : "Group berhasil dihapus", 
                            type  : "success",
                            icon  : "success",
                            confirmButtonColor: "#00BCD4"
                        }).then((isok) => {
                            location.reload();
                        })
                        }else{
                            alert("no data in database")
                        }
                        
                    }
                });
            } else {
                swal("Dibatalkan", "User status tidak berubah", "error");
            }
        });
        
    }
</script>