<?php

use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Facades\{Hash, Password, Session};
use Illuminate\Support\Str;
use Livewire\Attributes\{Locked, Title};
use Livewire\Component;
use Illuminate\Validation\Rules\Password as PasswordRule;

return new
#[Title('Réinitialisation du mot de passe')]
class extends Component {
    #[Locked]
    public string $token = '';

    public string $email                 = '';
    public string $password              = '';
    public string $password_confirmation = '';
    public ?string $generatedPassword    = null;

    public function mount(string $token): void
    {
        $this->token = $token;
        $this->email = request()->input('email', '');
    }

    /**
     * Génère un mot de passe aléatoire et le remplit dans les champs de mot de passe.
     */
    public function generatePassword(): void
    {
        $this->generatedPassword = Str::password(14);
        $this->password = $this->generatedPassword;
        $this->password_confirmation = $this->generatedPassword;
    }

    public function resetPassword(): void
    {
        $this->validate([
            'token'    => ['required'],
            'email'    => ['required', 'string', 'email'],
            'password' => [
                'required',
                'confirmed',
                PasswordRule::min(8)
                    ->mixedCase()   // Majuscules & Minuscules
                    ->numbers()     // Chiffres
                    ->symbols()     // Caractères spéciaux
                    ->uncompromised(), // Vérifie via "Have I Been Pwned" si le mot de passe a fuité sur le web
            ],
        ]);

        $status = Password::reset(
            $this->only('email', 'password', 'password_confirmation', 'token'),
            function ($user) {
                $user->forceFill([
                    'password'       => Hash::make($this->password),
                    'remember_token' => Str::random(60),
                ])->save();

                event(new PasswordReset($user));
            }
        );

        if (Password::PASSWORD_RESET != $status) {
            $this->addError('email', __($status));
            return;
        }

        Session::flash('status', __($status));

        $this->redirectRoute('login', navigate: true);
    }

    protected function view($data = [])
    {
        return app('view')->file('E:\laragon\www\shop2\storage\framework\views/livewire/views/02cabea3.blade.php', $data);
    }
}; 