<?php

namespace App\Livewire\Permissions;

use App\Models\Permission;
use App\Models\Role;
use App\Services\PermissionService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class RolePermissionIndex extends Component
{
    use AuthorizesRequests;

    public ?int $selectedRoleId = null;
    public array $rolePermissions = [];

    public function selectRole(int $roleId, PermissionService $permissionService): void
    {
        $this->authorize('viewAny', Permission::class);
        $role = Role::with('permissions')->findOrFail($roleId);

        $this->selectedRoleId = $role->id;
        $this->rolePermissions = $role->permissions->pluck('id')->toArray();
    }

    public function savePermissions(PermissionService $permissionService): void
    {
        $this->authorize('update', Permission::class);

        if ($this->selectedRoleId) {
            $role = Role::findOrFail($this->selectedRoleId);

            // Super Admin cannot be restricted
            if ($role->name === 'super_admin') {
                session()->flash('toast', ['type' => 'info', 'message' => 'Super Admin selalu memiliki akses penuh ke seluruh sistem.']);
                return;
            }

            $permissionService->updateRolePermissions($this->selectedRoleId, $this->rolePermissions);
            session()->flash('toast', ['type' => 'success', 'message' => "Matriks hak akses permission untuk '{$role->label}' berhasil diperbarui."]);
        }
    }

    public function render(PermissionService $permissionService)
    {
        $this->authorize('viewAny', Permission::class);

        $roles = $permissionService->getRolesWithPermissions();
        $permissionsByModule = $permissionService->getPermissionsGroupedByModule();

        if ($this->selectedRoleId === null && $roles->isNotEmpty()) {
            $firstRole = $roles->firstWhere('name', 'admin_tu') ?? $roles->first();
            $this->selectedRoleId = $firstRole->id;
            $this->rolePermissions = $firstRole->permissions->pluck('id')->toArray();
        }

        return view('livewire.permissions.role-permission-index', [
            'roles' => $roles,
            'permissionsByModule' => $permissionsByModule,
        ])->layout('components.layouts.app');
    }
}
