<?php

namespace App\Filament\Resources\UserResource\Pages;

use App\Filament\Resources\UserResource;
use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

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

    protected function getSavedNotification(): ?Notification
    {
        return null;
    }

    protected function afterSave(): void
    {
        $user = $this->record;
        $data = $this->data;

        if ($user->isGuru() && isset($data['nip'])) {
            $user->guru()->updateOrCreate(
                ['user_id' => $user->id],
                ['nip' => $data['nip']]
            );
        }
        elseif ($user->isSiswa()) {
            $user->siswa()->updateOrCreate(
                ['user_id' => $user->id],
                [
                    'nis' => $data['nis'],
                    'kelas_id' => $data['kelas_id'],
                ]
            );
        }

        $recipient = Auth::user();

        if (!$recipient) {
            Log::error('No authenticated user available for notification');
            return;
        }

        Notification::make()
            ->title('Perubahan Data Pengguna')
            ->success()
            ->body("Data pengguna {$user->name} berhasil diperbarui")
            ->sendToDatabase($recipient);
    }

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

    protected function mutateFormDataBeforeFill(array $data): array
    {
        $user = $this->record;
        
        if ($user->isGuru() && $user->guru) {
            $data['nip'] = $user->guru->nip;
        }
        
        if ($user->isSiswa() && $user->siswa) {
            $data['nis'] = $user->siswa->nis;
            $data['kelas_id'] = $user->siswa->kelas_id;
        }

        return $data;
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }
}
