<?php

namespace App\Http\Livewire\Pages\Auth;

use Livewire\Component;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Validation\Rules\Password as PasswordRule;

class ResetPassword extends Component
{
    public $token;
    public $email;
    public $password;

    public function mount()
    {
        $this->token = request()->token;
        $this->email = request()->email;
    }

    public function rules()
    {
        return [
            'token' => ['required', 'string'],
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string', 'min:6', 'max:64', PasswordRule::min(6)->numbers()],
        ];
    }

    public function updated($property)
    {
        $this->validateOnly($property);
    }

    public function reset_password()
    {
        $status = Password::reset(
            ['email' => $this->email, 'password' => $this->password, 'token' => $this->token],
            function ($user) {

                $user->forceFill([
                    'password' => Hash::make($this->password)
                ])->setRememberToken(Str::random(60));

                $user->save();

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

        if ($status === Password::PASSWORD_RESET) {
            return redirect()->route('login')->with(['message' => 'Password changed successfully. Login now']);
        } else {
            back()->with(['email' => [__($status)]]);
        }
    }

    public function render()
    {
        return view('livewire.pages.auth.reset-password');
    }
}
