<?php

namespace App\Livewire\Auth;

use App\Mail\ResetPasswordMail;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Livewire\Component;

class ForgotPassword extends Component
{
    public string $email = '';
    public bool   $sent  = false;
    public string $error = '';

    public function send(): void
    {
        $this->validate([
            'email' => 'required|email',
        ]);

        $user = User::where('email', $this->email)->first();

        if (!$user) {
            // Gleiche Meldung aus Security-Gründen
            $this->sent = true;
            return;
        }

        $token = Str::random(64);

        DB::table('password_reset_tokens')->updateOrInsert(
            ['email' => $this->email],
            ['token' => Hash::make($token), 'created_at' => now()]
        );

        Mail::mailer('system')->to($this->email)->send(new ResetPasswordMail($user, $token));

        $this->sent = true;
    }

    public function render()
    {
        return view('livewire.auth.forgot-password')
            ->layout('layouts.blank');
    }
}
