<?php
/*=========================================================================================
    App Name  : Manajement Administrasi Peradilan
    File Name : ResetPassword
    --------------------------------------------------------------------------------------
    Author    : Fuad Auliya Rohman
    Email     : fuad.dev16@gmail.com
==========================================================================================*/

namespace App\Http\Livewire\Auth;

use Illuminate\Http\Request;
use Livewire\Component;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class ResetPassword extends Component
{
    public $token;
    public $email;
    public $password;
    public $password_confirmation;
    public $setLoading = false;

    protected $rules = [
        'email' => ['required', 'string', 'email', 'max:255', 'exists:user'],
        'password' => ['required', 'confirmed', 'min:8',],
        'password_confirmation' => ['required'],
    ];

    public function resetUser()
    {
        $this->validate();

        // GET TOKEN FROM DB
        $checkToken = DB::table('password_resets')->where([
            'email' => $this->email,
            'token' => $this->token,
        ])->first();

        // CHECK TOKEN
        if(!$checkToken) {
            $this->dispatchBrowserEvent('alert:failed', [
                'message' => __('passwords.token'),
            ]);
            return null;
        }

        // CHECK IF TOKEN EXPIRED
        if(getTodayDate() > addMinuteToDate($checkToken->created_at, config('auth.passwords.users.expire'))) {
            $this->dispatchBrowserEvent('alert:failed', [
                'message' => __('passwords.timeup'),
            ]);
            return null;
        }

        // UPDATE NEW PASSWORD
        DB::table('user')->where('email', $this->email)->update(['password' => Hash::make($this->password), 'diupdate_tanggal' => getTodayDate(),]);

        DB::table('password_resets')->where('email', $this->email)->delete();

        return redirect('login')->with('success', __('messages.registration_success'));
    }

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

    public function render()
    {
        return view('livewire.auth.reset-password')->extends('layouts.auth')->section('content')->layoutData(['title' => __('lang.reset_password'),]);
    }
}
