<?php /* var_dump($permission); */ ?>
<?php (empty($permission) ? redirect(base_url("error404")) : ""); ?>
<?php if (!empty($this->app->is_can($permission, "view"))) { /* Can View */ ?>
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/sweetalert2-theme-bootstrap-4/bootstrap-4.min.css">
    <!-- Toastr -->
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/toastr/toastr.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/datatables-bs4/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/datatables-rowreorder/css/rowReorder.bootstrap4.min.css">
    <!-- Bootstrap-Switch  & Plugins -->
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/bootstrap-switch/css/bootstrap3/bootstrap-switch.min.css">
    <style>
        .btn-xs {
            height: 22px;
            padding: 2px 5px;
            font-size: 12px;
            line-height: 1.5;
            /* If Placeholder of the input is moved up, rem/modify this. */
            border-radius: 3px;
        }

        .table td,
        .table th {

            font-size: 13px;
        }

        th.dt-center,
        td.dt-center {
            width: 5px;
            text-align: center;
        }

        th.dt-active,
        td.dt-active {
            width: 15px;
            text-align: center;
        }
    </style>

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

    <div class="col-12 pt-3">
        <div class="row">
            <div class="col-6">
                <div class="text-left">
                    <a class="btn btn-xs mb-2" href="<?php echo base_url(); ?>sys/module">
                        <h5><i class="fa fa-backward"></i> <?php echo $this->app->decrypt_segment($this->uri->segment(4)); ?></h5>
                    </a>
                </div>
            </div>
            <div class="col-6">
                <div class="text-right">
                    <?php if ($this->app->is_can($permission, "add")) { ?>
                        <a id="addBtn" class="btn btn-primary btn-xs mb-2" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#addModal" href="javascript:void(0);"><span><i class="fa fa-plus"></i></span></a>
                    <?php } ?>
                </div>
            </div>
        </div>
        <div class="table-responsive m-t-40">
            <table id="mTable" class="table table-bordered table-striped table-hover" style="width:100%">
                <thead>
                    <tr>
                        <th>NO.</th>
                        <th>MODULE</th>
                        <th class="IsActive IsNotSort text-center">ICON</th>
                        <th>NAME</th>
                        <th>DESCRIPTION</th>
                        <th class="IsActive IsNotSort text-center"><i class="fa fa-eye"></i></th>
                        <?php if ($this->app->is_can($permission, "edit")) { ?>
                            <th class="IsNotSort text-center"><i class="fa fa-edit"></i></th>
                        <?php } ?>
                        <?php if ($this->app->is_can($permission, "delete")) { ?>
                            <th class="IsNotSort text-center"><i class="fa fa-trash-alt"></i></th>
                        <?php } ?>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

    <?php if ($this->app->is_can($permission, "add")) { ?>
        <div class="modal fade" id="addModal" tabindex="-1" role="dialog">
            <form id="addForm" method="post" action="<?php echo base_url('sys/module/add'); ?>">
                <input type="hidden" name="sort">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">เพิ่ม</h4>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        </div>
                        <div class="modal-body">
                            <input type="hidden" name="parent_module" value="<?php echo $this->app->decrypt_segment($this->uri->segment(4)); ?>">
                            <div class="form-group">
                                <label class="control-label">MODULE<span class="text-danger">*</span></label>
                                <div class="controls">
                                    <input type="text" class="form-control" name="module" required autocomplete="off">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">ICON</label>
                                <div class="controls">
                                    <select name="module_icon" class="form-control select2-add">
                                        <option value=""></option>
                                        <?php $this->load->view("layout/icon_font-awesome");
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">NAME<span class="text-danger">*</span></label>
                                <div class="controls">
                                    <input type="text" class="form-control" name="module_name" required autocomplete="off">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">DESCRIPTION</label>
                                <div class="controls">
                                    <textarea name="module_description" class="form-control" rows="3" placeholder=""></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">Roles</label>
                                <div class="controls">
                                    <div class="d-inline mr-2">
                                        <input type="checkbox" id="addRoleView" checked disabled>
                                        <label for="addRoleView">
                                            ดู
                                        </label>
                                    </div>
                                    <div class="d-inline mr-2">
                                        <input type="checkbox" id="addRoleAdd" name="add" value="1">
                                        <label for="addRoleAdd">
                                            เพิ่ม
                                        </label>
                                    </div>
                                    <div class="d-inline mr-2">
                                        <input type="checkbox" id="addRoleEdit" name="edit" value="1">
                                        <label for="addRoleEdit">
                                            แก้ไข
                                        </label>
                                    </div>
                                    <div class="d-inline mr-2">
                                        <input type="checkbox" id="addRoleDelete" name="delete" value="1">
                                        <label for="addRoleDelete">
                                            ลบ
                                        </label>
                                    </div>
                                    <div class="d-inline mr-2">
                                        <input type="checkbox" id="addRoleApprove" name="approve" value="1">
                                        <label for="addRoleApprove">
                                            อนุมัติ
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="reset" class="btn btn-xs btn-default" data-dismiss="modal">ยกเลิก</button>
                            <button type="submit" class="btn btn-xs btn-primary">บันทึก</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <!-- /.modal -->
    <?php } ?>

    <?php if ($this->app->is_can($permission, "edit")) { ?>
        <div class="modal fade" id="editModal" tabindex="-1" role="dialog">
            <form id="editForm" method="post" action="<?php echo base_url('sys/module/edit'); ?>" novalidate>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">แก้ไข</h4>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        </div>
                        <div class="modal-body">
                            <div class="form-group">
                                <label class="control-label">MODULE<span class="text-danger">*</span></label>
                                <div class="controls">
                                    <input type="text" class="form-control" name="module" readonly autocomplete="off">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">ICON</label>
                                <div class="controls">
                                    <select name="module_icon" class="form-control select2-edit">
                                        <option value=""></option>
                                        <?php $this->load->view("layout/icon_font-awesome");
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">NAME<span class="text-danger">*</span></label>
                                <div class="controls">
                                    <input type="text" class="form-control" name="module_name" required autocomplete="off">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">DESCRIPTION</label>
                                <div class="controls">
                                    <textarea name="module_description" class="form-control" rows="3" placeholder=""></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">Roles</label>
                                <div class="controls">
                                    <div class="d-inline mr-2">
                                        <input type="checkbox" id="editRoleView" checked disabled>
                                        <label for="editRoleView">
                                            ดู
                                        </label>
                                    </div>
                                    <div class="d-inline mr-2">
                                        <input type="checkbox" id="editRoleAdd" name="add" value="1">
                                        <label for="editRoleAdd">
                                            เพิ่ม
                                        </label>
                                    </div>
                                    <div class="d-inline mr-2">
                                        <input type="checkbox" id="editRoleEdit" name="edit" value="1">
                                        <label for="editRoleEdit">
                                            แก้ไข
                                        </label>
                                    </div>
                                    <div class="d-inline mr-2">
                                        <input type="checkbox" id="editRoleDelete" name="delete" value="1">
                                        <label for="editRoleDelete">
                                            ลบ
                                        </label>
                                    </div>
                                    <div class="d-inline mr-2">
                                        <input type="checkbox" id="editRoleApprove" name="approve" value="1">
                                        <label for="editRoleApprove">
                                            อนุมัติ
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="reset" class="btn btn-xs btn-default" data-dismiss="modal">ยกเลิก</button>
                            <button type="submit" class="btn btn-xs btn-primary">บันทึก</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <!-- /.modal -->
    <?php } ?>

    <!-- jQuery -->
    <script src="<?php echo base_url(); ?>vendor/jquery/jquery.min.js"></script>
    <!-- jQuery UI 1.11.4 -->
    <script src="<?php echo base_url(); ?>vendor/jquery-ui/jquery-ui.min.js"></script>
    <!-- Select2 -->
    <script src="<?php echo base_url(); ?>vendor/select2/js/select2.full.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="<?php echo base_url(); ?>vendor/sweetalert2/sweetalert2.min.js"></script>
    <!-- Toastr -->
    <script src="<?php echo base_url(); ?>vendor/toastr/toastr.min.js"></script>
    <!-- DataTables  & Plugins -->
    <script src="<?php echo base_url(); ?>vendor/datatables/jquery.dataTables.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-responsive/js/dataTables.responsive.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-buttons/js/dataTables.buttons.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-rowreorder/js/dataTables.rowReorder.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/datatables-rowreorder/js/rowReorder.bootstrap4.min.js"></script>
    <!-- Bootstrap-Switch  & Plugins -->
    <script src="<?php echo base_url(); ?>vendor/bootstrap-switch/js/bootstrap-switch.min.js"></script>
    <!-- jquery-validation -->
    <script src="<?php echo base_url(); ?>vendor/jquery-validation/jquery.validate.min.js"></script>
    <script src="<?php echo base_url(); ?>vendor/jquery-validation/additional-methods.min.js"></script>

    <script type="text/javascript">
        var timestamp = '<?php echo $timestamp; ?>';

        $('.select2-add').select2({
            dropdownParent: $('#addModal'),
            width: "100%"
        });

        $('.select2-edit').select2({
            dropdownParent: $('#editModal'),
            width: "100%"
        });

        var mTable;
        ! function(window, document, $) {
            "use strict";

            mTable = $('#mTable').DataTable({
                "colReorder": {
                    "realtime": true
                },
                "rowReorder": {
                    selector: 'td:nth-child(1)'
                },
                "orderable": false,
                "autoWidth": false,
                "pageLength": 10,
                "processing": true,
                "stateSave": true,
                stateSaveCallback: function(settings, data) {
                    localStorage.setItem('DataTables_' + settings.sInstance, JSON.stringify(data))
                },
                stateLoadCallback: function(settings) {
                    return JSON.parse(localStorage.getItem('DataTables_' + settings.sInstance))
                },
                "language": {
                    "url": "<?php echo base_url() ?>vendor/datatables/th.json",
                    "headers": {
                        "Access-Control-Allow-Origin": "*"
                    },
                    searchPlaceholder: "<?php echo strip_tags(@$var->txt_search); ?>",
                },
                "ajax": "<?php echo base_url('sys/module/ajax_list/' . $this->uri->segment(4)); ?>",
                "deferRender": true,
                "aLengthMenu": [
                    [10, 25, 50, 100],
                    [10, 25, 50, 100]
                ],
                "columns": [{
                        "data": {
                            "id": "id",
                            "is_active": "is_active"
                        },
                        render: function(data, type, row, meta) {
                            return '<div class="text-center">' + (meta.row + 1) + '</div>';
                        }
                    },
                    {
                        "data": "module"
                    },
                    {
                        "data": "module_icon"
                    },
                    {
                        "data": "module_name"
                    },
                    {
                        "data": "module_description"
                    },
                    {
                        "data": {
                            "id": "id",
                            "is_active": "is_active",
                            "created_by": "created_by"
                        },
                        render: function(data, type) {
                            if (data.created_by == 'system') {
                                return '<input data-id="' + data.id + '" data-active="' + data.is_active + '" type="checkbox" class="switch" <?php echo ($this->app->is_can($permission, "edit") ? '' : 'disabled'); ?> ' + (data.is_active == 1 ? 'checked' : '') + ' data-size="mini" data-on-color="success" data-off-color="warning" data-on-text="Yes" data-off-text="No"  disabled />';
                            } else {
                                return '<input data-id="' + data.id + '" data-active="' + data.is_active + '" type="checkbox" class="switch" <?php echo ($this->app->is_can($permission, "edit") ? '' : 'disabled'); ?> ' + (data.is_active == 1 ? 'checked' : '') + ' data-size="mini" data-on-color="success" data-off-color="warning" data-on-text="Yes" data-off-text="No"/>';
                            }
                        }
                    },
                    <?php if ($this->app->is_can($permission, "edit")) { ?> {
                            "data": {
                                "id": "id"
                            },
                            render: function(data, type) {
                                return '<button type="button" class="btn btn-info btn-xs" id="editBtn" data-id="' + data.id + '" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#editModal"><i class="fas fa-pencil-alt"></i></button>';
                            }
                        },
                    <?php } ?>
                    <?php if ($this->app->is_can($permission, "delete")) { ?> {
                            "data": {
                                "id": "id",
                                "created_by": "created_by"
                            },
                            render: function(data, type) {
                                if (data.created_by == 'system') {
                                    return '<button type="button" class="btn btn-default btn-xs" title="Delete" disabled><i class="fas fa-trash-alt"></i></button>';
                                } else {
                                    return '<button type="button" class="btn btn-danger btn-xs confirmDelete" data-href="<?php echo base_url('sys/module/delete/'); ?>' + data.id + '"><i class="fas fa-trash-alt"></i></button>';
                                }
                            }
                        },
                    <?php } ?>
                ],
                "columnDefs": [{
                        orderable: true,
                        className: 'reorder',
                        targets: 0
                    }, {
                        targets: '_all'
                    },
                    {
                        "width": "5px",
                        "targets": 0
                    },
                    {
                        "className": "dt-active",
                        "targets": "IsActive"
                    },
                    {
                        "orderable": false,
                        "className": "dt-center",
                        "targets": "IsNotSort"
                    }
                ],
                "fnDrawCallback": function() {
                    $(".switch[type='checkbox']").bootstrapSwitch();
                    $('.switch[type="checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) {
                        $(location).attr('href', '<?php echo base_url() ?>sys/module/change_active/' + $(this).data('id') + '.' + $(this).data('active'));
                    });
                },
                "createdRow": function(row, data, rowIndex) {
                    // Per-cell function to do whatever needed with cells
                    $.each($('td', row), function(colIndex) {
                        // console.log(data)
                        $(this).attr('title', data.module_name.trim() + '=>' + data.module_description);
                    });
                }
            });

            /* Event การเรียงลำดับข้อมูลในตารางหลัก */
            mTable.on('row-reorder', function(e, diff, edit) {
                for (var i = 0, ien = diff.length; i < ien; i++) {
                    var rowData = mTable.row(diff[i].node).data();
                    $.post('<?php echo base_url('sys/module/sort'); ?>', {
                        newPos: diff[i].newPosition + 1,
                        id: rowData.id
                    }, function(data) {});
                }
                reloadTable();
            });

            function reloadTable() {
                mTable.ajax.reload();
            }

            setInterval(function() {
                $.post('<?php echo base_url('sys/module/timestamp'); ?>',
                    function(data) {
                        if (timestamp != data) {
                            timestamp = data;
                            reloadTable();
                        }
                    });

            }, 12340);

        }(window, document, jQuery);
        $(document).ready(function() {
            <?php if ($this->app->is_can($permission, "add")) { ?>
                $('#addBtn').click(function() {
                    $('#addForm').trigger("reset");
                    var $form = $('#addForm');
                    $form.find('.is-invalid,.is-valid').css('border-color', '').removeClass('is-invalid').removeClass('is-valid');
                    $form.find('.error.invalid-feedback').html('');
                });
            <?php } ?>

            <?php if ($this->app->is_can($permission, "edit")) { ?>
                $('#mTable tbody').on('click', 'tr td #editBtn', function() {
                    var $form = $('#editForm');
                    $form.find('.is-invalid,.is-valid').css('border-color', '').removeClass('is-invalid').removeClass('is-valid');
                    $form.find('.error.invalid-feedback').html('');
                    $.post("<?php echo base_url('sys/module/ajax_data'); ?>", {
                            id: $(this).data('id')
                        },
                        function(data) {
                            $form.find('[name="module"]').val(data['module']);
                            $form.find('[name="module_icon"]').val(data['module_icon']).trigger('change');
                            $form.find('[name="module_name"]').val(data['module_name']);
                            $form.find('[name="module_description"]').html(data['module_description']);

                            if (data['add'] == 1) {
                                $form.find('[name="add"]').attr("checked", data['add']);
                            }
                            if (data['edit'] == 1) {
                                $form.find('[name="edit"]').attr("checked", data['edit']);
                            }
                            if (data['delete'] == 1) {
                                $form.find('[name="delete"]').attr("checked", data['delete']);
                            }
                            if (data['approve'] == 1) {
                                $form.find('[name="approve"]').attr("checked", data['approve']);
                            }
                        }, "json");
                });
            <?php } ?>

        });

        $('#addForm').validate({
            rules: {
                module: {
                    required: true,
                    remote: "<?php echo base_url('sys/module/ajax_exist'); ?>"
                },
                moudle_name: {
                    required: true
                },
            },
            messages: {},
            errorElement: 'span',
            errorPlacement: function(error, element) {
                error.addClass('invalid-feedback');
                element.closest('.form-group').append(error);
            },
            highlight: function(element, errorClass, validClass) {
                $(element).addClass('is-invalid');
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).removeClass('is-invalid');
            }
        });

        $('#editForm').validate({
            rules: {
                module: {
                    required: true,
                },
                moudle_name: {
                    required: true
                },
            },
            messages: {},
            errorElement: 'span',
            errorPlacement: function(error, element) {
                error.addClass('invalid-feedback');
                element.closest('.form-group').append(error);
            },
            highlight: function(element, errorClass, validClass) {
                $(element).addClass('is-invalid');
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).removeClass('is-invalid');
            }
        });

        /* Conform delete data in table */
        $('#mTable tbody').on('click', '.confirmDelete', function() {
            Swal.fire({
                title: 'คุณต้องการลบรายการนี้หรือไม่?',
                width: 300,
                showDenyButton: false,
                showCancelButton: true,
                confirmButtonText: 'ตกลง',
                confirmButtonColor: '#dc3545',
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    location.href = $(this).data('href');
                }
            })
        });
    </script>
<?php
} /* Can View */ ?>