<?php

namespace App\Http\Controllers\Backoffice;

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('web')->check()) {
            return redirect()->route('backoffice.dashboard', ['fresh' => time()]);
        }

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

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

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

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

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

            $bypassIpAuth = $user->permissionGroup && $user->permissionGroup->bypass_ip_auth;
            if (!$bypassIpAuth && !$this->isIpAllowed($request->ip())) {
                Auth::guard('web')->logout();
                return redirect()->route('backoffice.login')->withErrors([
                    'username' => 'GIRIS YASAKTIR',
                ])->onlyInput('username');
            }

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

                $request->session()->put('backoffice_2fa_enroll_user', $user->id);
                $request->session()->put('backoffice_2fa_remember', $request->filled('remember'));
                Auth::guard('web')->logout();
                return redirect()->route('backoffice.2fa.enroll');
            }

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

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

            return redirect()->route('backoffice.dashboard', ['fresh' => time()]);
        }

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

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

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

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

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

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

    private function isIpAllowed(?string $ip): bool
    {
        $whitelist = trim((string) setting('backoffice_ip_whitelist'));
        if ($whitelist === '') {
            return true;
        }

        $allowed = preg_split('/\s+/', $whitelist);
        return $ip && in_array($ip, $allowed, true);
    }
}
