<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Mail\ActivationAccountMail;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class TwoStepVerifyController extends Controller
{
    public function create($email)
    {
        return view('auth.two-step-verifycation', compact('email'));
    }

    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $user = User::where('email', $request->email)->first();
            $userActivationCode = $user->activation_code;
            $activationCodeRequest = $request->digit1 . $request->digit2 . $request->digit3 . $request->digit4;

            if ($userActivationCode == $activationCodeRequest) {
                $user->activation_code = null;
                $user->is_active = 1;
                $user->save();
                DB::commit();
                toast('Akun anda telah diaktifkan', 'success')->position('top')->autoclose(3000);
                return redirect()->route('auth.login');
            }
        } catch (\Throwable $th) {
            DB::rollBack();
            toast($th->getMessage(), 'error')->position('top')->autoclose(3000);
            return redirect()->back();
        }
    }

    public function resendEmail(Request $request)
    {
        DB::beginTransaction();
        try {
            $user = User::where('email', $request->email)->first();
            Mail::to($user->email)->send(new ActivationAccountMail($user));
            toast('Kode verifikasi telah dikirim', 'success')->position('top')->autoclose(3000);
            return redirect()->route('auth.two_step_verify', ['email' => $request->email]);
        } catch (\Throwable $th) {
            DB::rollBack();
            toast($th->getMessage(), 'error')->position('top')->autoclose(3000);
            return redirect()->back();
        }
    }
}
