<script setup>
import { onUpdated, ref } from 'vue';
import { api } from '@Services/Api';
import { apiTo } from '../Module';

import Header     from '@Holos/Modal/Elements/Header.vue';
import EditModal  from '@Holos/Modal/Show.vue';
import Checkbox   from '@Holos/Form/Checkbox.vue';
import PrimaryButton from '@Holos/Button/Primary.vue';

/** Eventos */
const emit = defineEmits([
    'close', 
]);

/** Propiedades */
const permissionTypes = ref([]);
const permissions     = ref([]);
const model           = ref(null);

/** Referencias */
const modalRef = ref(null);

/** Métodos */
function close() {
    modalRef.value.close();
    emit('close');
}

function update() {
    api.put(apiTo('permissions', { role: model.value.id }), {
        data: {
            permissions: permissions.value
        },
        onSuccess: () => {
            Notify.success(Lang('register.edit.onSuccess'))
            
            close();
        }
    });
}

function getPermissions() {
    api.get(route('permission-types.all-with-permissions'), {
        onSuccess: (r) => permissionTypes.value = r.models
    });

    api.get(apiTo('permissions', { role: model.value.id }), {
        onSuccess: (r) => {
            if(r.permissions) {
                permissions.value = r.permissions.map(p => p.id);
            }
        }
    });
}

/** Exposiciones */
defineExpose({
    open: (data) => {
        model.value = data;
        getPermissions();
        modalRef.value.open();
    }
});
</script>
<template>
    <EditModal
        ref="modalRef"
        @close="close"
    >
        <div v-if="model"> 
            <Header
                :title="model.description"
            />
            <div class="p-4">
                <div class="grid gap-4 grid-cols-2">
                    <div v-for="permissionType in permissionTypes">
                        <p class="font-bold">{{ permissionType.name}}</p>
                        <ul class="space-y-0.5 list-none">
                            <li v-for="permission in permissionType.permissions">
                                <Checkbox
                                    v-model="permissions"
                                    :title="permission.description"
                                    :value="permission.id"
                                />
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <template #buttons>
            <PrimaryButton
                @click="update"
            >
                {{ $t('update') }}
            </PrimaryButton>
        </template>
    </EditModal>
</template>