<?php

namespace App\Filament\Resources\SiswaResource\Pages;

use App\Filament\Resources\SiswaResource;
use App\Models\User;
use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class EditSiswa extends EditRecord
{
    protected static string $resource = SiswaResource::class;

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

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

        $recipient = Auth::user();

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

        Notification::make()
            ->title('Perubahan Data Siswa')
            ->success()
            ->body("Data siswa {$nama} berhasil diperbarui")
            ->sendToDatabase($recipient);
    }

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

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $user = User::create([
            'name' => $data['nama'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'role' => 'guru',
        ]);

        $data['user_id'] = $user->id;

        unset($data['password']);

        return $data;
    }

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