<?php

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

return new class extends Component
{
    public $name = '';
    public $selectedPermissions = [];
    public $editingRoleId = null;

    public function render()
    {
        return $this->view()->layout('layouts::auth');
    }

    public function with()
    {
        return [
            'roles' => Role::with('permissions')->get(),
            'permissions' => Permission::all()->groupBy(function($item) {
                if (str_contains($item->name, ' ')) {
                    return explode(' ', $item->name)[1];
                }
                return 'Other';
            }),
        ];
    }

    public function save()
    {
        $this->validate([
            'name' => 'required|string|unique:roles,name,' . $this->editingRoleId,
            'selectedPermissions' => 'array'
        ]);

        if ($this->editingRoleId) {
            $role = Role::findById($this->editingRoleId);
            $role->update(['name' => $this->name]);
            $role->syncPermissions($this->selectedPermissions);
            session()->flash('message', 'Role updated successfully.');
        } else {
            $role = Role::create(['name' => $this->name]);
            $role->syncPermissions($this->selectedPermissions);
            session()->flash('message', 'Role created successfully.');
        }

        $this->reset(['name', 'selectedPermissions', 'editingRoleId']);
    }

    public function editRole($id)
    {
        $role = Role::findById($id);
        $this->editingRoleId = $id;
        $this->name = $role->name;
        $this->selectedPermissions = $role->permissions->pluck('name')->toArray();
    }

    public function deleteRole($id)
    {
        $role = Role::findById($id);
        if ($role->name === 'superadmin') {
            session()->flash('error', 'Superadmin role cannot be deleted.');
            return;
        }
        $role->delete();
        session()->flash('message', 'Role deleted successfully.');
    }

    public function cancelEdit()
    {
        $this->reset(['name', 'selectedPermissions', 'editingRoleId']);
    }

    protected function view($data = [])
    {
        return app('view')->file('D:\02-my freelance\00-DR_Padhi\DR_PADHI\storage\framework/views/livewire/views/762733b7.blade.php', $data);
    }

    public function styleModuleSrc()
    {
        return 'D:\02-my freelance\00-DR_Padhi\DR_PADHI\storage\framework/views/livewire/styles/762733b7.css';
    }
};
