<?php

namespace App\Components\Admin\Permission;

use Livewire\Component;
use Spatie\Permission\Models\Permission;

class PermissionEdit extends Component {
    public Permission $permission;
    public $selectedRoles = [];

    /**
     * Initialize the component with a specific permission.
     * We pluck the names of the currently assigned roles to populate the checkboxes.
     */
    public function mount(Permission $permission) {
        $this->permission = $permission;
        $this->selectedRoles = $this->permission->roles()->pluck('name')->toArray();
    }

    /**
     * This method is triggered every time the $selectedRoles array is updated
     * (i.e., when a checkbox is toggled).
     */
    public function updatedSelectedRoles() {
        // Spatie's syncRoles handles adding/removing relationships automatically.
        $this->permission->syncRoles($this->selectedRoles);
        $this->dispatch('toast', message: 'Roles updated', type: 'success');
    }

    public function render() {
        return view('components.admin.permission.permission-edit');
    }
}