<?php

use Livewire\Component;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

new class extends Component {
    public $email = '';

    protected function rules()
    {
        return [
            'email' => ['required', 'email', 'max:255', Rule::unique(User::class)],
        ];
    }

    public function updated($property)
    {
        $this->validateOnly($property);
    }

    public function submit()
    {
        $this->validate();

        $user = User::create([
            'email' => $this->email,
        ]);

        try {
            event(new Registered($user));
        } catch (\Exception $e) {
            // Handle failure
            $user->delete(); // optional: remove the user since email failed
            // Log detailed error for debugging
            \Log::error('Failed to send verification email', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString(),
            ]);
            $this->dispatch('showToast', 'Failed to send verification email. Please try again.', type: 'error');
            return;
        }

        Auth::login($user);
        session()->regenerate();
        //✅         Redirect to email verification notice page
        return redirect()->route('verification.notice');
    }
};
?>

<x-slot:title>
    {{ config('app.name') }} || Account Registration
</x-slot:title>

<div class="space-y-5">
    <x-auth-header :title="__('Create an account')" :description="__('Enter your email below to get a verification link')" />

    <form wire:submit.prevent="submit" class="space-y-4">

        <!-- Email Address -->
        <div wire:transition>
            <x-input wire:model="email" label="Email Address" placeholder="example@email.com" />
        </div>

        <x-button type="submit" class="bg-sky-600 text-white w-full">
            Register
        </x-button>
    </form>
</div>
