<?php

namespace App\Filament\Resources\RoleResource\Pages;

use App\Filament\Resources\RoleResource;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;

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

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        // Collect all permission IDs from all sections
        $allPermissionIds = [];
        foreach ($data as $key => $value) {
            if (str_starts_with($key, 'permissions_') && is_array($value)) {
                $allPermissionIds = array_merge($allPermissionIds, $value);
            }
        }

        // Warning if no permissions selected
        if (empty($allPermissionIds)) {
            Notification::make()
                ->title('تحذير: لم يتم تحديد أي صلاحيات')
                ->warning()
                ->body('يُنصح بتحديد صلاحيات على الأقل للدور')
                ->persistent()
                ->send();
        }

        // Set the permissions relationship
        $data['permissions'] = $allPermissionIds;

        // Remove the temporary permission section keys
        foreach ($data as $key => $value) {
            if (str_starts_with($key, 'permissions_')) {
                unset($data[$key]);
            }
        }

        return $data;
    }

    protected function afterCreate(): void
    {
        $permissionsCount = $this->record->permissions()->count();
        
        Notification::make()
            ->title('تم إنشاء الدور بنجاح')
            ->success()
            ->body("تم تعيين {$permissionsCount} صلاحية للدور")
            ->send();
    }
}





