<?php

namespace App\Filament\Resources\UserResource\Pages;

use App\Filament\Resources\UserResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;

class EditUser extends EditRecord
{
    protected static string $resource = UserResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\DeleteAction::make()
                ->label('删除')
                ->modalHeading('删除用户')
                ->modalDescription('确定要删除此用户吗？此操作无法撤销。')
                ->modalSubmitActionLabel('确认删除')
                ->modalCancelActionLabel('取消'),
        ];
    }

    protected function getSavedNotificationTitle(): ?string
    {
        return '用户更新成功';
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // 从 all_permissions 字段获取权限列表
        if (isset($data['all_permissions'])) {
            $permissions = $data['all_permissions'];
            unset($data['all_permissions']);
            
            // 保存权限到记录中，稍后在 afterSave 中同步
            $this->permissions = $permissions;
        }
        
        // 移除所有 permissions_* 字段
        foreach ($data as $key => $value) {
            if (str_starts_with($key, 'permissions_')) {
                unset($data[$key]);
            }
        }
        
        return $data;
    }

    protected function afterSave(): void
    {
        // 同步权限
        if (isset($this->permissions)) {
            $this->record->syncPermissions($this->permissions);
        }
    }
}
