<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use PragmaRX\Google2FA\Google2FA;
use Illuminate\Support\Facades\Auth;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\Image\SvgImageBackEnd;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;

class TwoFactorController extends Controller
{
    public function showSetupForm()
    {
        $user = Auth::user();
        $google2fa = new Google2FA();
        
        $secret = $google2fa->generateSecretKey();
        
        // Temporarily store secret in session
        session(['2fa_secret_pending' => $secret]);
        
        // Generate QR Code manually using BaconQrCode
        $renderer = new ImageRenderer(
            new RendererStyle(200),
            new SvgImageBackEnd()
        );
        $writer = new Writer($renderer);
        
        // otpauth://totp/LABEL?secret=SECRET&issuer=ISSUER
        $companyName = config('app.name', 'Laravel');
        $otpUrl = $google2fa->getQRCodeUrl(
            $companyName,
            $user->email,
            $secret
        );
        
        $qrCodeSvg = $writer->writeString($otpUrl);

        return view('admin.auth.2fa-setup', compact('secret', 'qrCodeSvg'));
    }

    public function confirm(Request $request)
    {
        $request->validate(['code' => 'required']);
        
        $google2fa = new Google2FA();
        $secret = session('2fa_secret_pending');
        
        if (!$secret) {
            return redirect()->route('admin.2fa.setup')->withErrors(['error' => 'Session expired. Please try again.']);
        }
        
        $valid = $google2fa->verifyKey($secret, $request->code);
        
        if ($valid) {
            $user = Auth::user();
            $user->google2fa_secret = $secret;
            $user->two_factor_confirmed_at = now();
            $user->save();
            
            session()->forget('2fa_secret_pending');
            session(['2fa_verified' => true]);
            
            return redirect()->route('dashboard')->with('success', '2FA enabled successfully.');
        }
        
        return back()->withErrors(['code' => 'Invalid authentication code.']);
    }

    public function showVerifyForm()
    {
        return view('admin.auth.2fa-verify');
    }

    public function verify(Request $request)
    {
        $request->validate(['code' => 'required']);
        
        $user = Auth::user();
        $google2fa = new Google2FA();
        
        if ($google2fa->verifyKey($user->google2fa_secret, $request->code)) {
            session(['2fa_verified' => true]);
            return redirect()->intended(route('dashboard'));
        }
        
        return back()->withErrors(['code' => 'Invalid code.']);
    }
}
