<?php

namespace App\Filament\Admin\Resources\Users\Pages;

use App\Filament\Admin\Resources\Users\UserResource;
use App\Models\Association;
use Filament\Actions\DeleteAction;
use Filament\Actions\ForceDeleteAction;
use Filament\Actions\RestoreAction;
use Filament\Actions\ViewAction;
use Filament\Facades\Filament;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\Facades\Log;

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

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

    protected function handleRecordUpdate(\Illuminate\Database\Eloquent\Model $record, array $data): \Illuminate\Database\Eloquent\Model
    {
        $associationId = $data['association_id'] ?? null;
        $roles = $data['roles'] ?? [];
        unset($data['association_id'], $data['roles']);

        $record->update($data);

        $tenant = Filament::getTenant();
        if ($tenant) {
            // Handle association assignment
            if ($associationId) {
                $association = Association::find($associationId);
                if ($association && $association->org_id === $tenant->id) {
                    $record->setAssociationInOrg($tenant, $association);
                }
            } else {
                // Remove association if none selected
                $record->setAssociationInOrg($tenant, null);
            }

            // Handle role assignment with organization scope
            Log::info('Roles are: '.implode(',', $roles));

            $record->syncRoles($roles);
        }

        return $record;
    }
}
