<?php

namespace App\Livewire\Forms;

use App\Models\User;
use Closure;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Livewire\Form;

final class UserProfileForm extends Form
{
    public string $nombre = '';

    public string $email = '';

    public string $currentPassword = '';

    public string $newPassword = '';

    public string $passwordConfirm = '';

    public ?User $user;

    public function rules() {

        $new_password = $this->newPassword;
        $password_confirm = $this->passwordConfirm;
        $user = $this->user;

        return [
            'nombre' => ['required'],
            'email' => ['required', Rule::unique('users', 'email')->ignore(id: $user->uuid, idColumn: 'uuid'), 'email'],
            'currentPassword' => [
                'nullable',
                function (string $attribute, mixed $value, Closure $fail) use ($user, $new_password) {
                    /* Por seguridad no me traigo la contraseña en el componente de livewire asi que tengo que consultarla */
                    if (! Hash::check($new_password, User::where('uuid', $user->uuid)->value('password'))) {
                        $fail('La contraseña proporcionada no concuerda con la contraseña actual');
                    }
                },
            ],
            'newPassword' => [
                'nullable',
                function (string $attribute, mixed $value, Closure $fail) use ($new_password, $password_confirm) {
                    if ($new_password != $password_confirm) {
                        $fail('La contraseña nueva y la de confirmación no coinciden');
                    }
                },
            ],

        ];

    }

    public function messages() {

        return [
            'nombre.required' => "El campo es obligatorio.",
            'email.required' => "El campo es obligatorio.",
            'email.unique' => "Ya existe un usuario registrado con ese correo eletrónico.",
            'email.email' => "Correo proporcionado contiene un formato inválido."
        ];

    }

    public function save(User $user)
    {
        $this->user = $user;
        $new_password = $this->newPassword;

        $this->validate();

        if ($new_password) {
            $user->forceFill([
                'name' => $this->nombre,
                'email' => $this->email,
                'password' => Hash::make($new_password),
            ]);
        } else {
            $user->fill([
                'name' => $this->nombre,
                'email' => $this->email,
            ]);
        }

        $user->save();
    }
}
