<?php

namespace App\Livewire\Auth;

use App\Models\User;
use App\Enum\UserRole;
use Livewire\Component;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Mail\TwoFactorAuthenticationCode;

class TwoFactorAuth extends Component
{
    public $verification_code, $id;

    public function mount($id)
    {
        $this->id = $id;
    }

    public function verify()
    {
        $this->validate([
            'verification_code' => ['required', 'numeric', 'digits:6'],
        ]);

        try {
            $user = User::where('role', UserRole::USER->value)->where('uuid', $this->id)->firstOrFail();

            if ($user->email_code_expires_at < now()) {
                session()->flash('error', 'Verification code has expired. Please request a new one.');
                return;
            }

            if ($user->email_code != $this->verification_code) {
                session()->flash('error', 'Invalid verification code. Please try again.');
                return;
            }

            DB::beginTransaction();

            $user->update([
                'email_verified_at' => now(),
                'email_code' => null,
                'email_code_expires_at' => null,
            ]);

            DB::commit();

            Auth::login($user);

            return redirect()->intended(route('user.dashboard'))->with('success', 'Logged in successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            session()->flash('error', config('app.messages.error'));
            return;
        }
    }

    public function resend()
    {
        try {
            $user = User::where('role', UserRole::USER->value)->where('uuid', $this->id)->firstOrFail();

            DB::beginTransaction();

            $user->update([
                'email_code' => getRandomNumber(6),
                'email_code_expires_at' => now()->addMinutes(10),
            ]);

            DB::commit();

            Mail::to($user->email)->queue(new TwoFactorAuthenticationCode($user));

            session()->flash('success', 'Verification code has been sent to your email. Please check your inbox.');
            return;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            session()->flash('error', config('app.messages.error'));
            return;
        }
    }

    public function render()
    {
        return view('livewire.auth.two-factor-auth');
    }
}
