<?php

namespace App\Filament\Resources\RoleResource\Pages;

use App\Filament\Resources\RoleResource;
use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;

class EditRole extends EditRecord
{
    protected static string $resource = RoleResource::class;

    protected function getHeaderActions(): array
    {
        return [
            DeleteAction::make(),
        ];
    }

    protected function mutateFormDataBeforeFill(array $data): array
    {
        $record = $this->getRecord();
        $record->load('permissions');
        
        $categories = [
            'users' => 'users',
            'clients' => 'clients',
            'technicians' => 'technicians',
            'services' => 'services',
            'categories' => 'categories',
            'orders' => 'orders',
            'packages' => 'packages',
            'subscriptions' => 'subscriptions',
            'point_transactions' => 'point_transactions',
            'ratings' => 'ratings',
            'additional_facilities' => 'additional_facilities',
            'property_types' => 'property_types',
            'roles' => 'roles',
            'permissions' => 'permissions',
            'reports' => 'reports',
            'settings' => 'settings',
            'notifications' => 'notifications',
        ];

        foreach ($categories as $key => $prefix) {
            $permissionIds = $record->permissions()
                ->where(function ($query) use ($prefix) {
                    $query->where('name', 'like', '%_' . $prefix . '%')
                        ->orWhere('name', 'like', $prefix . '_%');
                })
                ->pluck('id')
                ->toArray();
            
            $data['permissions_' . $key] = $permissionIds;
        }

        return $data;
    }

    protected function mutateFormDataBeforeSave(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 afterSave(): void
    {
        $permissionsCount = $this->record->permissions()->count();
        
        Notification::make()
            ->title('تم تحديث الدور بنجاح')
            ->success()
            ->body("تم تعيين {$permissionsCount} صلاحية للدور")
            ->send();
    }
}





