<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\FinanceUser;
use App\Services\TotpService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TwoFactorController extends Controller
{
    public function showSetup(TotpService $totp)
    {
        $user = Auth::guard('finance')->user();
        if (!$user) {
            return redirect()->route('finance.login');
        }

        if (!$user->twofa_secret) {
            $user->twofa_secret = $totp->generateSecret();
            $user->save();
        }

        $issuer = setting('site_name', 'PayGaranti');
        $account = $user->username ?: $user->email ?: ('user-' . $user->id);
        $otpAuthUrl = $totp->getOtpAuthUri($issuer, $account, $user->twofa_secret);

        return view('finance.auth.twofa', [
            'user' => $user,
            'issuer' => $issuer,
            'account' => $account,
            'otpAuthUrl' => $otpAuthUrl,
        ]);
    }

    public function showEnroll(Request $request, TotpService $totp)
    {
        $userId = $request->session()->get('finance_2fa_enroll_user');
        if (!$userId) {
            return redirect()->route('finance.login');
        }

        $user = FinanceUser::find($userId);
        if (!$user) {
            $request->session()->forget(['finance_2fa_enroll_user', 'finance_2fa_remember']);
            return redirect()->route('finance.login');
        }

        if (!$user->twofa_secret) {
            $user->twofa_secret = $totp->generateSecret();
            $user->save();
        }

        $issuer = setting('site_name', 'PayGaranti');
        $account = $user->username ?: $user->email ?: ('user-' . $user->id);
        $otpAuthUrl = $totp->getOtpAuthUri($issuer, $account, $user->twofa_secret);

        return view('finance.auth.twofa-enroll', [
            'user' => $user,
            'issuer' => $issuer,
            'account' => $account,
            'otpAuthUrl' => $otpAuthUrl,
        ]);
    }

    public function enable(Request $request, TotpService $totp)
    {
        $user = Auth::guard('finance')->user();
        if (!$user) {
            return redirect()->route('finance.login');
        }

        $data = $request->validate([
            'code' => 'required|string',
        ]);

        if (!$user->twofa_secret || !$totp->verifyCode($user->twofa_secret, $data['code'])) {
            return back()->withErrors(['code' => 'Invalid code.'])->withInput();
        }

        $user->update([
            'twofa_enabled' => true,
            'twofa_confirmed_at' => now(),
        ]);

        ActivityLog::log(
            'twofa_enable',
            'auth',
            'Finance user enabled 2FA: ' . $user->username
        );

        return back()->with('status', 'Two factor enabled.');
    }

    public function verifyEnroll(Request $request, TotpService $totp)
    {
        $data = $request->validate([
            'code' => 'required|string',
        ]);

        $userId = $request->session()->get('finance_2fa_enroll_user');
        $remember = (bool) $request->session()->get('finance_2fa_remember', false);

        $user = FinanceUser::find($userId);
        if (!$user || !$user->twofa_secret) {
            $request->session()->forget(['finance_2fa_enroll_user', 'finance_2fa_remember']);
            return redirect()->route('finance.login');
        }

        if (!$totp->verifyCode($user->twofa_secret, $data['code'])) {
            return back()->withErrors(['code' => 'Invalid code.'])->withInput();
        }

        $user->update([
            'twofa_enabled' => true,
            'twofa_confirmed_at' => now(),
        ]);

        ActivityLog::log(
            'twofa_enable',
            'auth',
            'Finance user enabled 2FA: ' . $user->username
        );

        Auth::guard('finance')->login($user, $remember);
        $request->session()->forget(['finance_2fa_enroll_user', 'finance_2fa_remember']);
        $request->session()->regenerate();

        $user->update(['last_login_at' => now()]);

        ActivityLog::log(
            'login',
            'auth',
            'Finance user login (2FA): ' . $user->username
        );

        return redirect()->intended(route('finance.dashboard'));
    }

    public function disable(Request $request, TotpService $totp)
    {
        $user = Auth::guard('finance')->user();
        if (!$user) {
            return redirect()->route('finance.login');
        }

        $data = $request->validate([
            'code' => 'required|string',
        ]);

        if (!$user->twofa_secret || !$totp->verifyCode($user->twofa_secret, $data['code'])) {
            return back()->withErrors(['code' => 'Invalid code.'])->withInput();
        }

        $user->update([
            'twofa_enabled' => false,
            'twofa_secret' => null,
            'twofa_confirmed_at' => null,
        ]);

        ActivityLog::log(
            'twofa_disable',
            'auth',
            'Finance user disabled 2FA: ' . $user->username
        );

        return back()->with('status', 'Two factor disabled.');
    }

    public function showChallenge(Request $request)
    {
        if (Auth::guard('finance')->check()) {
            return redirect()->route('finance.dashboard');
        }

        if (!$request->session()->has('finance_2fa_user')) {
            return redirect()->route('finance.login');
        }

        return view('finance.auth.twofa-challenge');
    }

    public function verifyChallenge(Request $request, TotpService $totp)
    {
        $data = $request->validate([
            'code' => 'required|string',
        ]);

        $userId = $request->session()->get('finance_2fa_user');
        $remember = (bool) $request->session()->get('finance_2fa_remember', false);

        $user = FinanceUser::find($userId);
        if (!$user || !$user->twofa_enabled || !$user->twofa_secret) {
            $request->session()->forget(['finance_2fa_user', 'finance_2fa_remember']);
            return redirect()->route('finance.login');
        }

        if (!$totp->verifyCode($user->twofa_secret, $data['code'])) {
            return back()->withErrors(['code' => 'Invalid code.'])->withInput();
        }

        Auth::guard('finance')->login($user, $remember);
        $request->session()->forget(['finance_2fa_user', 'finance_2fa_remember']);
        $request->session()->regenerate();

        $user->update(['last_login_at' => now()]);

        ActivityLog::log(
            'login',
            'auth',
            'Finance user login (2FA): ' . $user->username
        );

        return redirect()->intended(route('finance.dashboard'));
    }
}
