<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Mail\ResetPasswordMail;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;

class PasswordResetLinkController extends Controller
{
    /**
     * Display the password reset link request view.
     */
    public function create(): View
    {
        return view('auth.forgot-password');
    }

    /**
     * Handle an incoming password reset link request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */

    public function store(Request $request)
    {
        $customMessages = [
            'email.required' => 'Email tidak boleh kosong',
            'email.email' => 'Email tidak valid',
            'email.exists' => 'Email tidak terdaftar',
        ];

        $validator = Validator::make($request->all(), [
            'email' => ['required', 'email', 'exists:users,email'],
        ], $customMessages);

        if ($validator->fails()) {
            toast($validator->messages()->all()[0], 'error')->position('top')->autoclose(3000);
            return redirect()->back()->withInput();
        }

        DB::table('password_reset_tokens')->updateOrInsert(
            ['email' => $request->email],
            [
                'token' => Hash::make($request->_token),
                'created_at' => now(),
            ]
        );

        $resetLink = route('auth.create_new_password_form', ['token' => $request->_token, 'email' => $request->email]);
        Mail::to($request->email)->send(new ResetPasswordMail($resetLink));


        alert()->success('Berhasil', 'Silahkan cek email anda untuk mereset password');
        return redirect()->back();
    }

    public function createNewPasswordForm(Request $request)
    {
        return view('auth.reset-password-form', ['token' => $request->token, 'email' => $request->email]);
    }

    public function storeNewPasswordForm(Request $request)
    {
        $data = DB::table('password_reset_tokens')->where('email', $request->email)->first();

        if ($data == null || !Hash::check($request->token, $data->token)) {
            toast('Link reset password tidak valid atau kedaluwarsa', 'error')->position('top')->autoclose(3000);
            return redirect()->back();
        }

        DB::beginTransaction();
        $user = User::where('email', $request->email)->first();
        $user->password = Hash::make($request->new_password);
        try {
            $user->save();
            DB::table('password_reset_tokens')->where('email', $request->email)->delete();
            DB::commit();
            alert()->success('Berhasil', 'Password berhasil direset, silahkan login');
            return redirect()->route('auth.login');
        } catch (\Throwable $th) {
            DB::rollBack();
            toast('Terjadi kesalahan', 'error')->position('top')->autoclose(3000);
            return redirect()->back();
        }
    }
}
