<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
    {
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        if (!session()->has('cdata')) {
            return back()->withErrors(['captcha' => 'Captcha verification failed.'])->withInput();
        }
    
        $functionData = session('cdata');
        $captchaResponse = $request->input($functionData['ctoken']);
        $isVerified = verify_ccaptcha($functionData, $captchaResponse);
    
        if (!$isVerified) {
            throw ValidationException::withMessages([
                'captcha' => 'The captcha verification failed. Please try again.',
            ]);
        }
        
        $allowed_mails = get_setting('allowed_mails');
        
        if (is_string($allowed_mails)) {
            $allowed_mails = trim($allowed_mails, '[]"');
            $allowed_mails = explode(',', $allowed_mails);
        } else {
            $allowed_mails = [];
        }
        
        $email_domain = substr(strrchr($request->email, "@"), 1);
        
        if (!empty($allowed_mails) && !in_array($email_domain, $allowed_mails)) {
            throw ValidationException::withMessages([
                'error' => 'The email domain is not allowed.',
            ]);
        }

        $request->authenticate();
        $request->session()->regenerate();
        
        if (!empty(Auth::user()->two_factor_secret)) {
            if (!$request->filled('otp')) {
                Auth::logout();
                return redirect('/login')->withErrors(['error' => 'Enter OTP for 2FA verification.']);
            }
    
            $google2fa = app('pragmarx.google2fa');
            $isValid = $google2fa->verifyKey(Auth::user()->two_factor_secret, $request->otp);
    
            if (!$isValid) {
                Auth::logout();
                return redirect('/login')->withErrors(['error' => 'Invalid OTP code.']);
            }
        }

        $ip = $request->ip();
        if(get_setting('maintenance_status') == 'on') {
            if(Auth::user()->role != 'Superadmin') {
                Auth::logout();
                return redirect('/login')->withErrors(['error' => 'Website is under Maintenance, only Admins can login.']);
            }
        }
        if (Auth::user()->banned == 1) {
            Auth::logout();
            return redirect('/login')->withErrors(['error' => 'Access denied: Account Banned.']);
        }
        Auth::user()->update([
            'last_login_ip' => $request->ip(),
        ]);
        create_notification('Login Successful', "Logged in successfully from IP: $ip", 'system');
        return redirect()->intended(route('dashboard', absolute: false));
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

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

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

        return redirect('/');
    }
}
