<?php

namespace App\Filament\Association\Resources\MemberResource\Pages;

use App\Filament\Association\Resources\MemberResource;
use App\Models\ProfileField;
use App\Models\MemberProfileValue;
use Filament\Actions;
use Filament\Facades\Filament;
use Filament\Resources\Pages\EditRecord;

class EditMember extends EditRecord
{
    protected static string $resource = MemberResource::class;

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

    protected function mutateFormDataBeforeFill(array $data): array
    {
        $user = $this->record;
        $tenant = \Filament\Facades\Filament::getTenant();

        // Load pivot data
        $pivot = $user->associations()->where('associations.id', $tenant->id)->first()?->pivot;
        if ($pivot) {
            $data['membership_number'] = $pivot->membership_number;
            $data['status'] = $pivot->status;
        }

        $values = \App\Models\MemberProfileValue::where('user_id', $user->id)
            ->where('association_id', $tenant->id)
            ->get();

        foreach ($values as $value) {
            $data['profile_fields'][$value->profile_field_id] = $value->value_json ?? $value->value;
        }

        return $data;
    }

    protected function afterSave(): void
    {
        $user = $this->record;
        $tenant = \Filament\Facades\Filament::getTenant();

        // Save pivot data
        $user->associations()->updateExistingPivot($tenant->id, [
            'membership_number' => $this->data['membership_number'] ?? null,
            'status' => $this->data['status'] ?? 'pending',
        ]);

        $data = $this->data['profile_fields'] ?? [];
        foreach ($data as $fieldId => $value) {
            $field = \App\Models\ProfileField::find($fieldId);
            if (!$field) continue;

            if ($value === null || $value === '') {
                \App\Models\MemberProfileValue::where([
                    'association_id' => $tenant->id,
                    'user_id' => $user->id,
                    'profile_field_id' => $fieldId,
                ])->delete();
                continue;
            }

            \App\Models\MemberProfileValue::updateOrCreate(
                [
                    'association_id' => $tenant->id,
                    'user_id' => $user->id,
                    'profile_field_id' => $fieldId,
                ],
                [
                    'value' => is_array($value) ? null : (string) $value,
                    'value_json' => is_array($value) ? $value : null,
                ]
            );
        }
    }
}
