<?php

namespace App\Livewire\Admin;

use Livewire\Component;

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RoleForm extends Component
{
    protected $listeners = ['openCreateRoleModal','openEditRoleModal', 'deleteRole'];

    public $showCreateModal=false;
    public ?int $roleId = null;
    public $name = '';
    public $permissions = []; // 所有權限清單
    public $selectedPermissions = []; // 表單中選到的權限

   

    public function mount()
    {
        $this->permissions = Permission::all();
    }

    public function openCreateRoleModal()
    {
        $this->resetFields();
        $this->showCreateModal = true;
    }

    public function openEditRoleModal($id)
    {
        $role = Role::findOrFail($id);
        $this->roleId = $role->id;
        $this->name = $role->name;
        $this->selectedPermissions = $role->permissions()->pluck('id')->toArray();
        $this->showCreateModal = true;
    }
    
    public function save()
    {
        $this->validate([
            'name' => 'required|string|max:255',
            'selectedPermissions' => 'array',
        ]);
        
        if ($this->roleId) {
            $role = Role::findOrFail($this->roleId);
            $role->update(['name' => $this->name]);
            $role->syncPermissions($this->selectedPermissions);
            session()->flash('message', '角色已更新');
        } else {
            $role = Role::create(['name' => $this->name]);
            $role->syncPermissions($this->selectedPermissions);
            session()->flash('message', '角色已新增');
        }

        $this->resetFields();
        $this->showCreateModal = false;
        $this->dispatch('pg:eventRefresh-role-table');
    }

    public function deleteRole($id)
    {
        Role::findOrFail($id)->delete();
        session()->flash('message', '角色已刪除');
    }

    public function resetFields()
    {
        $this->name = '';
        $this->selectedPermissions = [];
        $this->roleId = null;
    }

    public function render()
    {
        return view('livewire.admin.role-form');
    }
}
