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

namespace App\Http\Livewire\Auth;

use Livewire\Component;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use App\Events\ForgotPassword as ForgotEvents;

class ForgotPassword extends Component
{
    public $email;

    public $setLoading = false;

    protected $rules = [
        'email' => ['required', 'email', 'exists:users'],
    ];

    public function forgetUser()
    {
        // VALIDASI
        $this->validate();

        // RESET VALIDASI
        $this->resetErrorBag();
        $this->resetValidation();

        // CHECK IF VALID EMAIL
        if(!filter_var($this->email, FILTER_VALIDATE_EMAIL)) {
            $this->addError('email', __('validation.email'));
            return null;
        }

        // GET USER
        $user = DB::table('users')->where('email', $this->email)->first();

        // GENERATE TOKEN
        $token = Str::random(64);

        // INSERT PASSWORD RESET
        DB::table('password_reset_tokens')->insert([
            'email' => sanitize($this->email),
            'token' => $token,
            'created_at' => getTodayDate(),
        ]);

        $data = array(
            'email' => $this->email,
            'token' => $token,
            'name'  => $user->email,
        );

        // SEND EMAIL
        event(new ForgotEvents((object) $data));

        // NOTIFICATION
        $this->dispatchBrowserEvent('alert:success', [
            'message' => __('passwords.sent'),
        ]);

        // RESET PROPERTY
        $this->reset('email');
    }

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