<?php

namespace Modules\TwoFA\Http\Controllers;

use App\Repositories\UserRepositoryInterface;
use App\User;
use Brian2694\Toastr\Facades\Toastr;
use Exception;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Modules\FrontendManage\Entities\LoginPage;
use Modules\RolePermission\Entities\Role;
use Modules\TwoFA\Entities\UserOtpCode;
use PragmaRX\Google2FALaravel\Support\Authenticator;

class TwoFAController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */

    public function __construct(UserRepositoryInterface $userRepository)
    {
        $this->userRepository = $userRepository;
    }


    public function settings()
    {
        try {
            $roles =implode(', ',Role::where('id', '!=',3)->pluck('name')->toArray());
            return view('twofa::settings',compact('roles'));
        } catch (Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());

        }
    }

    public function settingsUpdate(Request $request)
    {
        try {

            UpdateGeneralSetting('enable_two_fa', isset($request->enable_two_fa) ? 1 : 0);
            UpdateGeneralSetting('enable_student_two_fa', isset($request->enable_student_two_fa) ? 1 : 0);
            UpdateGeneralSetting('force_two_fa', isset($request->force_two_fa) ? 1 : 0);
            UpdateGeneralSetting('default_two_fa', isset($request->default_two_fa) ? (int)$request->default_two_fa : 0);

            Toastr::success(trans('common.Operation successful'), trans('common.Success'));
            return redirect()->back();
        } catch (Exception $e) {
            GettingError($e->getMessage(), url()->current(), request()->ip(), request()->userAgent());
        }
    }


    public function index()
    {
        try {
            $page = LoginPage::getData();
            return view(theme('auth.two_step_verification'), compact('page'));

        } catch (Exception $e) {
            Log::info($e->getMessage());
        }
    }

    public function resendVerificationCode()
    {

        $email = session()->get('email');

        UserOtpCode::where('email', $email)->delete();

        $verification_code = $this->userRepository->storeVerificationCode($email);

        if ($verification_code) {
            $user = User::where('email', $email)->first();
            $data = [
                'otp_code' => $verification_code->otp_code,
                'email' => $verification_code->email,
                'expired_time' => $verification_code->expired_time
            ];
            if ($user->two_step_verification == 1) {
                send_email($user, 'Two_Factor_Authentication', $data);
            } else {
                send_sms_notification($user, 'Two_Factor_Authentication', $data);
            }
        }

        Toastr::success(trans('frontend.Your verification code sends successfully'), trans('common.Success'));
        return back();

    }

    public function verify(Request $request)
    {
        $user = Auth::user();
        $authenticator = new Authenticator($request);
        $status = $authenticator->verifyGoogle2FA($user->google2fa_secret, $request->get('one_time_password', 'None'));
        if (!$status) {
            Toastr::error(trans('frontend.One Time password is not correct'), trans('common.Failed'));
            return redirect()->back();
        }
        $authenticator->login();
        return redirect()->back();
    }

    public function regenerate(Request $request)
    {
        $user = auth()->user();
        $google2fa = app('pragmarx.google2fa');

        $registration_data['google2fa_secret'] = $google2fa->generateSecretKey();
        User::where('email', $user->email)->update(['google2fa_secret' => $registration_data['google2fa_secret']]);
        $authenticator = new Authenticator($request);

        $authenticator->login();
        return redirect()->back();
    }
}
