<?php

namespace App\Http\Controllers\Finance;

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

class AuthController extends Controller
{
    public function showLoginForm()
    {
        if (Auth::guard('finance')->check()) {
            return redirect()->route('finance.dashboard');
        }

        return view('finance.auth.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        if (Auth::guard('finance')->attempt($credentials, $request->filled('remember'))) {
            $request->session()->regenerate();

            $user = Auth::guard('finance')->user();

            // Check if user is active
            if (!$user->is_active) {
                Auth::guard('finance')->logout();
                return back()->withErrors([
                    'username' => 'Hesabiniz pasif durumda. Lutfen yonetici ile iletisime gecin.',
                ])->onlyInput('username');
            }

            $twofaEnabled = (string) setting('finance_2fa_enabled', 'enabled') !== 'disabled';
            if ($twofaEnabled) {
                if ($user->twofa_enabled) {
                    $request->session()->put('finance_2fa_user', $user->id);
                    $request->session()->put('finance_2fa_remember', $request->filled('remember'));
                    Auth::guard('finance')->logout();
                    return redirect()->route('finance.2fa.challenge');
                }

                $request->session()->put('finance_2fa_enroll_user', $user->id);
                $request->session()->put('finance_2fa_remember', $request->filled('remember'));
                Auth::guard('finance')->logout();
                return redirect()->route('finance.2fa.enroll');
            }

            // Update last login
            $user->update(['last_login_at' => now()]);

            // Log activity
            ActivityLog::log(
                'login',
                'auth',
                'Finance user login: ' . $user->username
            );

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

        return back()->withErrors([
            'username' => 'Kullanici adi veya sifre hatali.',
        ])->onlyInput('username');
    }

    public function logout(Request $request)
    {
        $user = Auth::guard('finance')->user();

        // Log activity
        ActivityLog::log(
            'logout',
            'auth',
            'Finance user logout: ' . $user->username
        );

        Auth::guard('finance')->logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

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