<?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-responsive/css/responsive.bootstrap4.min.css">
    <link rel="stylesheet" href="<?php echo base_url(); ?>vendor/datatables-buttons/css/buttons.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="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 class="table-responsive m-t-40">
            <table id="mTable" class="table table-bordered table-striped table-hover" style="width:100%">
                <thead>
                    <tr>
                        <th>ลำดับ</th>
                        <th>บริษัท</th>
                        <th>สาขา</th>
                        <th>รายละเอียด</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="fas fa-edit"></i></th>
                        <?php } ?>
                        <?php if ($this->app->is_can($permission, "delete")) { ?>
                            <th class="IsNotSort text-center"><i class="fas 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/branch/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">
                            <div class="form-group">
                                <label class="control-label">บริษัท<span class="text-danger">*</span></label>
                                <div class="controls">
                                    <select name="company_id" class="form-control" required>
                                        <option value=""></option>
                                        <?php
                                        $sql = "SELECT * FROM company WHERE record_status ='N' AND is_active ='1' ";
                                        if ($this->session->userdata("user_profile")->id !== '1') {
                                            $sql .= "AND id = '" . $this->session->userdata("user_profile")->company_id . "' ";
                                        }
                                        $sql .= "ORDER BY sort ASC";
                                        foreach ($this->db->query($sql)->result() as $item) {
                                            echo "<option value='" . $item->id . "'>" . $item->company_name . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">สาขา<span class="text-danger">*</span></label>
                                <div class="controls">
                                    <input type="text" class="form-control" name="branch_name" required autocomplete="off">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">รายละเอียด</label>
                                <div class="controls">
                                    <textarea name="branch_description" class="form-control" rows="3" placeholder=""></textarea>
                                </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/branch/edit'); ?>">
                <input type="hidden" name="id">
                <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">บริษัท<span class="text-danger">*</span></label>
                                <div class="controls">
                                    <select name="company_id" class="form-control" required>
                                        <option value=""></option>
                                        <?php
                                        $sql = "SELECT * FROM company WHERE record_status ='N' AND is_active ='1' ";
                                        if ($this->session->userdata("user_profile")->id !== '1') {
                                            $sql .= "AND id = '" . $this->session->userdata("user_profile")->company_id . "' ";
                                        }
                                        $sql .= "ORDER BY sort ASC";
                                        foreach ($this->db->query($sql)->result() as $item) {
                                            echo "<option value='" . $item->id . "'>" . $item->company_name . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">สาขา<span class="text-danger">*</span></label>
                                <div class="controls">
                                    <input type="text" class="form-control" name="branch_name" required autocomplete="off">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label">รายละเอียด</label>
                                <div class="controls">
                                    <textarea name="branch_description" class="form-control" rows="3" placeholder=""></textarea>
                                </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>
    <!-- SweetAlert2 -->
    <script src="<?php echo base_url(); ?>vendor/sweetalert2/sweetalert2.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; ?>';
        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/branch/ajax_list'); ?>",
                "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": "company_name"
                    },
                    {
                        "data": "branch_name"
                    },
                    {
                        "data": "branch_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/branch/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/branch/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.branch_name.trim() + '=>' + data.branch_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/branch/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/branch/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/branch/ajax_data'); ?>", {
                            id: $(this).data('id')
                        },
                        function(data) {
                            $form.find('[name="id"]').val(data['id']);
                            $form.find('[name="company_id"]').val(data['company_id']).trigger('change');
                            $form.find('[name="branch_name"]').val(data['branch_name']);
                            $form.find('[name="branch_description"]').html(data['branch_description']);
                        }, "json");
                });
            <?php } ?>

        });

        $('#addForm').validate({
            rules: {
                branch_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: {
                branch: {
                    required: true,
                },
                branch_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 */ ?>