<?php $__env->startSection('content'); ?>
    <?php
        $actionsFormat = [];

        foreach ($actions as $val) {
            $actionsFormat[$val->parent_menu][] = (object) [
                'id' => $val->id,
                'name' => $val->name,
            ];
        }

    ?>
    <?php if (isset($component)) { $__componentOriginald411d1792bd6cc877d687758b753742c = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginald411d1792bd6cc877d687758b753742c = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.primary-button','data' => ['dataBsToggle' => 'modal','dataBsTarget' => '#modalTambahRole','class' => 'mb-4']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('primary-button'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(Illuminate\View\AnonymousComponent::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['data-bs-toggle' => 'modal','data-bs-target' => '#modalTambahRole','class' => 'mb-4']); ?>Tambah Role <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginald411d1792bd6cc877d687758b753742c)): ?>
<?php $attributes = $__attributesOriginald411d1792bd6cc877d687758b753742c; ?>
<?php unset($__attributesOriginald411d1792bd6cc877d687758b753742c); ?>
<?php endif; ?>
<?php if (isset($__componentOriginald411d1792bd6cc877d687758b753742c)): ?>
<?php $component = $__componentOriginald411d1792bd6cc877d687758b753742c; ?>
<?php unset($__componentOriginald411d1792bd6cc877d687758b753742c); ?>
<?php endif; ?>
    <nav>
        <div class="nav nav-tabs" id="nav-tab" role="tablist">
            <button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button"
                role="tab" aria-controls="nav-home" aria-selected="true">Role Aktif</button>
            <button class="nav-link" id="nav-profile-tab" data-bs-toggle="tab" data-bs-target="#nav-profile" type="button"
                role="tab" aria-controls="nav-profile" aria-selected="false">Role Hapus</button>

        </div>
    </nav>
    <div class="tab-content" id="nav-tabContent">
        <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
            <div class="card">
                <div class="card-body">
                    <table id="activeTable" class="table table-striped data-table">
                        <thead>
                            <tr>
                                <th id="no">No</th>
                                <th>Role</th>
                                <th>All Location</th>
                                <th>Is Operator</th>
                                <th width="105px">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
            <div class="card">
                <div class="card-body">
                    <table id="trashTable" class="table table-striped data-table">
                        <thead>
                            <tr>
                                <th id="no">No</th>
                                <th>Role</th>
                                <th>All Location</th>
                                <th>Is Operator</th>
                                <th width="105px">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>


    <?php echo $__env->make('master-data.role.modal.add', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    <?php echo $__env->make('master-data.role.modal.edit', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<?php $__env->stopSection(); ?>
<?php $__env->startPush('extraJS'); ?>
    <script type="text/javascript">
        $(document).ready(function () {
            $(function () {
                var table = $('#activeTable').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: "<?php echo e(route('roles.index')); ?>",
                        data: function (d) {
                            d.option = "active";
                        },
                    },
                    columnDefs: [{
                        width: "50px",
                        targets: 0
                    } // 0 adalah index kolom 'id'
                    ],
                    columns: [{
                        data: 'DT_RowIndex',
                        name: 'DT_RowIndex',
                        className: 'text-center',
                        orderable: false,
                        searchable: false
                    },
                    {
                        data: 'role',
                        name: 'role'
                    },
                    {
                        data: 'all_site',
                        name: 'all_site'
                    },
                    {
                        data: 'is_Operator',
                        name: 'is_Operator'
                    },
                    {
                        data: 'action',
                        name: 'action',
                        orderable: false,
                        searchable: false
                    },
                    ]
                });
                var table2 = $('#trashTable').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: "<?php echo e(route('roles.index')); ?>",
                        data: function (d) {
                            d.option = "trash"
                        },
                    },
                    columnDefs: [{
                        width: "50px",
                        targets: 0
                    } // 0 adalah index kolom 'id'
                    ],
                    columns: [{
                        data: 'DT_RowIndex',
                        name: 'DT_RowIndex',
                        className: 'text-center',
                        orderable: false,
                        searchable: false
                    },
                    {
                        data: 'role',
                        name: 'role'
                    },
                    {
                        data: 'all_site',
                        name: 'all_site'
                    },
                    {
                        data: 'is_Operator',
                        name: 'is_Operator'
                    },
                    {
                        data: 'action',
                        name: 'action',
                        orderable: false,
                        searchable: false
                    },
                    ]
                });

            });

            // tambah
            $('#formTambahRole').on('submit', function (e) {
                e.preventDefault();

                const form = $(this);
                const name = $('#role').val().trim();
                let actions = $('[name="actions[]"]');
                if (!name) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Validasi Gagal',
                        text: 'Nama role wajib diisi.'
                    });
                    return;
                }

                $.ajax({
                    url: '<?php echo e(route('roles.store')); ?>',
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: form.serialize(),
                    success: function (response) {
                        $('#modalTambahRole').modal('hide');
                        form.trigger("reset");

                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: response.message,
                            timer: 2000,
                            showConfirmButton: false
                        });

                        $('.data-table').DataTable().ajax.reload();


                        $('#modalTambahRole [name="read-all"]').prop('checked', false).trigger(
                            'change');
                        $('#modalTambahRole [name="update-all"]').prop('checked', false)
                            .trigger('change');
                        $('#modalTambahRole [name="create-all"]').prop('checked', false)
                            .trigger('change');
                        $('#modalTambahRole [name="delete-all"]').prop('checked', false)
                            .trigger('change');
                        $('#modalTambahRole [name="reads[]"]').prop('checked', false).trigger(
                            'change');
                        $('#modalTambahRole [name="updates[]"]').prop('checked', false).trigger(
                            'change');
                        $('#modalTambahRole [name="creates[]"]').prop('checked', false).trigger(
                            'change');
                        $('#modalTambahRole [name="deletes[]"]').prop('checked', false).trigger(
                            'change');
                    },
                    error: function (xhr) {
                        let message = xhr.responseJSON?.message || 'Terjadi kesalahan';
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal Menyimpan',
                            text: message
                        });
                    }
                });
            });

            // edit
            $(document).on('click', '.edit', function () {
                let id = $(this).data('id');
                let role = $(this).data('role');
                let all_site = $(this).data('all-site');
                let is_Operator = $(this).data('is-Operator');
                let actions = $(this).data('actions');

                $('#edit-id').val(id);
                $('#edit-role').val(role);
                $('#modalEditRole').modal('show');
                if (all_site == 1) {
                    $('#edit-all-site').prop('checked', true);
                } else {
                    $('#edit-all-site').prop('checked', false);
                }
                if (is_Operator == 1) {
                    $('#is-operator').prop('checked', true);
                } else {
                    $('#is-operator').prop('checked', false);
                }

                $('#modalEditRole [name="read-all"]').prop('checked', false).trigger('change');
                $('#modalEditRole [name="update-all"]').prop('checked', false).trigger('change');
                $('#modalEditRole [name="create-all"]').prop('checked', false).trigger('change');
                $('#modalEditRole [name="delete-all"]').prop('checked', false).trigger('change');
                $('#modalEditRole [name="reads[]"]').prop('checked', false).trigger('change');
                $('#modalEditRole [name="updates[]"]').prop('checked', false).trigger('change');
                $('#modalEditRole [name="creates[]"]').prop('checked', false).trigger('change');
                $('#modalEditRole [name="deletes[]"]').prop('checked', false).trigger('change');
                let url = "<?php echo e(route('roles.akses', ':id')); ?>".replace(':id', id);

                $.ajax({
                    url: url,
                    method: "GET",
                    success: (data) => {
                        data.access.forEach(d => {
                            $(`#modalEditRole [name="reads[]"][value="${d.action_id}"]`)
                                .prop('checked', d.read == true || d.read == 1 || d
                                    .read === "1").trigger('change');
                            $(`#modalEditRole [name="updates[]"][value="${d.action_id}"]`)
                                .prop('checked', d.update == true || d.update == 1 || d
                                    .update === "1").trigger('change');
                            $(`#modalEditRole [name="creates[]"][value="${d.action_id}"]`)
                                .prop('checked', d.create == true || d.create == 1 || d
                                    .create === "1").trigger('change');
                            $(`#modalEditRole [name="deletes[]"][value="${d.action_id}"]`)
                                .prop('checked', d.delete == true || d.delete == 1 || d
                                    .delete === "1").trigger('change');
                        });

                    }
                })
                // Loop dan centang yang sesuai

            });

            // Handle form submit edit
            $('#formEditRole').on('submit', function (e) {
                e.preventDefault();
                const form = $(this);

                let id = $('#edit-id').val();
                let role = $('#edit-role').val().trim();
                let actions = $('[name="actions[]"]');

                if (!role) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Validasi Gagal',
                        text: 'Nama role wajib diisi.'
                    });
                    return;
                }

                $.ajax({
                    url: `<?php echo e(route('roles.update', ":id")); ?>`.replace(":id", id),
                    type: 'PUT',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: form.serialize(),
                    success: function (response) {
                        $('#modalEditRole').modal('hide');

                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: response.message,
                            timer: 2000,
                            showConfirmButton: false
                        });

                        $('.data-table').DataTable().ajax.reload();
                    },
                    error: function (xhr) {
                        let message = xhr.responseJSON?.message ||
                            'Terjadi kesalahan saat update.';
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal Update',
                            text: message
                        });
                    }
                });
            });
            // delete
            $(document).on("click", ".delete", function () {
                var id = $(this).data("id");
                var option = $(this).data("option");

                Swal.fire({
                    title: 'Apakah kamu yakin?',
                    text: option == "restore" ? "Data akan dipulihkan" : (option == "delete" ?
                        "Data akan dihapus sementara" : "Data akan dihapus secara permanen!"),
                    icon: 'warning',
                    showCancelButton: true,
                    cancelButtonColor: '#3085d6',
                    confirmButtonColor: option == "restore" ? "#ffae1f" : '#d33',
                    confirmButtonText: option == "restore" ? "Ya, pulihkan" : 'Ya, hapus!',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: `<?php echo e(route('roles.destroy', ":id")); ?>`.replace(":id", id) + "?option=" + option,
                            type: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            },
                            success: function (res) {
                                Swal.fire(option == "restore" ? "Dipulihkan" :
                                    'Terhapus!', res.message, 'success');
                                $('.data-table').DataTable().ajax.reload();
                            },
                            error: function (xhr) {
                                Swal.fire('Gagal!', 'Data gagal dihapus.', 'error');
                            }
                        });
                    }
                });
            });




            // HANDLE checkbox ALL

            $(document).on("click", "[name='read-all']", function () {
                const status = $(this).is(":checked");
                $(this).closest(".modal").find("[name='reads[]']").prop("checked", status);
                $(this).closest(".modal").find("[name='read-all-menu']").prop("checked", status);
            });

            $(document).on("click", "[name='create-all']", function () {
                const status = $(this).is(":checked");
                $(this).closest(".modal").find("[name='creates[]']").prop("checked", status);
                $(this).closest(".modal").find("[name='create-all-menu']").prop("checked", status);

            });

            $(document).on("click", "[name='update-all']", function () {
                const status = $(this).is(":checked");
                $(this).closest(".modal").find("[name='updates[]']").prop("checked", status);
                $(this).closest(".modal").find("[name='update-all-menu']").prop("checked", status);

            });

            $(document).on("click", "[name='delete-all']", function () {
                const status = $(this).is(":checked");
                $(this).closest(".modal").find("[name='deletes[]']").prop("checked", status);
                $(this).closest(".modal").find("[name='delete-all-menu']").prop("checked", status);

            });



            // menu
            $(document).on("click", ".parent-menu [name='read-all-menu']", function () {
                const status = $(this).is(":checked");
                const parentMenuName = $(this).parent().parent().parent().data("menu");
                $(this).closest(".modal").find("[data-menu='" + parentMenuName + "']" + " [name='reads[]']")
                    .prop("checked", status).trigger("change");
            });

            $(document).on("click", ".parent-menu [name='create-all-menu']", function () {
                const status = $(this).is(":checked");
                const parentMenuName = $(this).parent().parent().parent().data("menu");
                $(this).closest(".modal").find("[data-menu='" + parentMenuName + "']" +
                    " [name='creates[]']").prop("checked", status).trigger("change");
            });

            $(document).on("click", ".parent-menu [name='update-all-menu']", function () {
                const status = $(this).is(":checked");
                const parentMenuName = $(this).parent().parent().parent().data("menu");
                $(this).closest(".modal").find("[data-menu='" + parentMenuName + "']" +
                    " [name='updates[]']").prop("checked", status).trigger("change");
            });

            $(document).on("click", ".parent-menu [name='delete-all-menu']", function () {
                const status = $(this).is(":checked");
                const parentMenuName = $(this).parent().parent().parent().data("menu");
                $(this).closest(".modal").find("[data-menu='" + parentMenuName + "']" +
                    " [name='deletes[]']").prop("checked", status).trigger("change");
            });



            // ==========================
            // Tambahan: kalau semua child dicentang → parent ikut
            // ==========================
            $(document).on("change", "[name='reads[]']", function () {
                const $modal = $(this).closest(".modal");
                const parentMenu = $(this).parent().parent().data("menu"); // tambahkan: ambil parentMenu
                const allChecked = $modal.find("[name='reads[]']").length === $modal.find(
                    "[name='reads[]']:checked").length;
                const allCheckedMenu = $modal.find("[data-menu='" + parentMenu + "'] [name='reads[]']")
                    .length === $modal.find("[data-menu='" + parentMenu + "'] [name='reads[]']:checked")
                        .length;
                $modal.find("[name='read-all']").prop("checked", allChecked).trigger("change");
                $modal.find("[data-menu='" + parentMenu + "'] [name='read-all-menu']").prop("checked",
                    allCheckedMenu).trigger("change");
            });

            $(document).on("change", "[name='creates[]']", function () {
                const $modal = $(this).closest(".modal");
                const allChecked = $modal.find("[name='creates[]']").length === $modal.find(
                    "[name='creates[]']:checked").length;
                const parentMenu = $(this).parent().parent().data("menu");
                const allCheckedMenu = $modal.find("[data-menu='" + parentMenu + "'] [name='creates[]']")
                    .length === $modal.find("[data-menu='" + parentMenu + "'] [name='creates[]']:checked")
                        .length;

                $modal.find("[name='create-all']").prop("checked", allChecked).trigger("change");
                $modal.find("[data-menu='" + parentMenu + "'] [name='create-all-menu']").prop("checked",
                    allCheckedMenu).trigger("change");
            });

            $(document).on("change", "[name='updates[]']", function () {
                const $modal = $(this).closest(".modal");
                const allChecked = $modal.find("[name='updates[]']").length === $modal.find(
                    "[name='updates[]']:checked").length;
                const parentMenu = $(this).parent().parent().data("menu");
                const allCheckedMenu = $modal.find("[data-menu='" + parentMenu + "'] [name='updates[]']")
                    .length === $modal.find("[data-menu='" + parentMenu + "'] [name='updates[]']:checked")
                        .length;

                $modal.find("[name='update-all']").prop("checked", allChecked).trigger("change");
                $modal.find("[data-menu='" + parentMenu + "'] [name='update-all-menu']").prop("checked",
                    allCheckedMenu).trigger("change");
            });

            $(document).on("change", "[name='deletes[]']", function () {
                const $modal = $(this).closest(".modal");
                const parentMenu = $(this).parent().parent().data("menu");
                const allCheckedMenu = $modal.find("[data-menu='" + parentMenu + "'] [name='deletes[]']")
                    .length === $modal.find("[data-menu='" + parentMenu + "'] [name='deletes[]']:checked")
                        .length;
                const allChecked = $modal.find("[name='deletes[]']").length === $modal.find(
                    "[name='deletes[]']:checked").length; // perbaiki: hilangkan spasi ekstra

                $modal.find("[name='delete-all']").prop("checked", allChecked).trigger("change");
                $modal.find("[data-menu='" + parentMenu + "'] [name='delete-all-menu']").prop("checked",
                    allCheckedMenu).trigger("change");
            });

        })
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('template.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/pmme2286/public_html/docu/vendor1/resources/views/master-data/role/index.blade.php ENDPATH**/ ?>