<?php

namespace App\Filament\Resources\SiswaResource\Pages;

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

class CreateSiswa extends CreateRecord
{
    protected static string $resource = SiswaResource::class;

    protected function getCreatedNotification(): ?Notification
    {
        return null;
    }
    
    protected function afterCreate(): void
    {
        $recipient = Auth::user();

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

        Notification::make()
            ->title('Siswa Berhasil Dibuat')
            ->success()
            ->body("Siswa {$this->record->nama} berhasil dibuat")
            ->sendToDatabase($recipient);
    }

    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');
    }
}
