<?php

use App\Models\User;
use Illuminate\Validation\Rules\Password;
use Livewire\Features\SupportRedirects\Redirector;
use Illuminate\Support\Facades\{Auth, Hash};
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Title;
use Livewire\Component;
use Mary\Traits\Toast;

return new #[Title('Profil')]
class extends Component {
    use Toast;

    public User $user;
    public string $firstname = '';
    public string $name = '';
    public string $email = '';
    public bool $newsletter = false;
    public string $password = '';
    public string $password_confirmation = '';
    public bool $rgpd = false;

    public function mount(): void
    {
        $this->user = Auth::user();
        $this->firstname = $this->user->firstname ?? '';
        $this->name = $this->user->name ?? '';
        $this->email = $this->user->email ?? '';
        $this->newsletter = (bool) ($this->user->newsletter ?? false);
    }

    public function generatePassword(): void
    {
        $generated = Str::password(14);
        $this->password = $generated;
        $this->password_confirmation = $generated;

        $this->info(__('Nouveau mot de passe généré.'), position: 'toast-bottom');
    }

    public function save(): void
    {
        $data = $this->validate([
            'firstname'  => ['required', 'string', 'max:255'],
            'name'       => ['required', 'string', 'max:255'],
            'email'      => ['required', 'email', Rule::unique('users')->ignore($this->user->id)],
            'newsletter' => ['boolean'],
            'rgpd'       => ['accepted'],
            'password' => [
                'nullable',
                '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 !
            ],
        ], [
            'rgpd.accepted' => __('Vous devez accepter la politique de confidentialité pour enregistrer.')
        ]);

        if (empty($data['password'])) {
            unset($data['password']);
        } else {
            $data['password'] = Hash::make($data['password']);
        }

        unset($data['rgpd']);

        $this->user->update($data);

        $this->success(__('Profil mis à jour avec succès !'), redirectTo: route('home'));
    }

    public function cancel(): Redirector
    {
        return redirect()->route('home');
    }

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