<?php

namespace App\Http\Controllers;


use App\Rules\User\Google2FaSecretKeyVerificationRule;
use App\Services\Google2FaServices;
use Carbon\Carbon;
use Illuminate\Http\Request;

class GoogleFactorController extends Controller
{

    protected Google2FaServices $google2FaServices;
    public function __construct(Google2FaServices $google2FaServices)
    {
        $this->google2FaServices = $google2FaServices;
    }

    public function Google2FAUpdatePage(Request $request){

        $google2FaQR = $this->google2FaServices->generateQRImage(auth()->user()->email);
        $request->session()->flash('registration_data', $google2FaQR);

        // Pass the QR barcode image to our view
        return view('Dashboard.User.GoogleFactorUpdate' , ['QR_Image' => $google2FaQR['QR_Image'], 'secret'=>$google2FaQR['google2fa_secret']]);
    }

    public function verifyGoogle2Fa(Request $request){

        $request->merge(session('registration_data'));
        $this->validate($request, [
            'secret' => ['required', new Google2FaSecretKeyVerificationRule($this->google2FaServices, $request->google2fa_secret)]
        ],[
            'secret' => 'Your Secret Key is invalid please scan and enter the code again!'
        ]);

        auth()->user()->forceFill([
            'google2fa_secret' => $request->google2fa_secret,
            'googlef2_status' => 1,
            'google_date' => Carbon::now()->format('Y-m-d')
        ])->save();

        return redirect('/UserProfile')->with('success_message' , 'Your have successfully turned ON Two-Factor Authentication!');
        session()->put('GoogleUpdateFactor' , $request->google2fa_secret);
        return redirect('/GoogleSecretKey');

    }


}
