<?php

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Livewire\Attributes\Title;
use Livewire\Component;
use App\Mail\UserRegistered;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rules\Password;
use Illuminate\Support\Str;

return new #[Title('Inscription')]
class extends Component {

    public string $firstname = '';
    public string $name = '';
    public string $email = '';
    public string $password = '';
    public string $password_confirmation = '';
    public bool   $newsletter = false;
    public ?string $generatedPassword = null;
    public ?string $gender = null;

    /**
     * Enregistre un nouvel utilisateur dans la base de données.
     */
    public function register()
    {
        if ($this->gender) {
            abort(403);
        }

        $data = $this->validate([
            'firstname'  => 'required|string|max:255',
            'name'       => 'required|string|max:255',
            'newsletter' => 'nullable|boolean',
            'email'      => 'required|string|email|unique:users',
            'password' => [
                'required',
                'confirmed',
                Password::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
            ],
            'password_confirmation' => 'required',
        ]);

        $data['password'] = Hash::make($data['password']);
        $user = User::create($data);
        auth()->login($user);
        request()->session()->regenerate();

        Mail::to($user)->send(new UserRegistered());

        session()->flash('registered', __('Votre compte a été créé avec succès. Un e-mail de confirmation vous a été envoyé.'));

        return redirect('/');
    }

    /**
     * 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;
    }


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