<?php

namespace App\Filament\Resources\Roles\Pages;

use App\Filament\Resources\Roles\RoleResource;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Models\Permission;

class CreateRole extends CreateRecord
{
    protected static string $resource = RoleResource::class;

    public function canCreateAnother(): bool
    {
        return false;
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }

    protected function handleRecordCreation(array $data): Model
    {
        // Extract permissions from the form data
        $permissions = collect([
            $data['users_permissions'] ?? [],
        ])->flatten()->toArray();

        // Create the role record
        $record = new ($this->getModel())([
            'name' => $data['name'],
            'guard_name' => $data['guard_name']
        ]);

        if ($parentRecord = $this->getParentRecord()) {
            $record = $this->associateRecordWithParent($record, $parentRecord);
        } else {
            $record->save();
        }

        // Assign permissions after the role is saved
        $permissions = Permission::query()->whereIn('name', $permissions)->get();
        $record->syncPermissions($permissions);

        return $record;
    }
}
