<?php

namespace App\Http\Controllers\Backend\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Exception;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use App\Helpers\AuditTrailHelper;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo;
    
    /**
     * show login form for admin guard
     *
     * @return void
     */
    public function showLoginForm()
    {
        return view('backend.auth.login');
    }


    protected function redirectTo()
    {
        // Check the current guard and redirect accordingly
        if (Auth::guard('admin')->check()) {
            // Redirect admins to their dashboard
            return '/';
        }

        if (Auth::guard('web')->check()) {
            // Redirect regular users to their home or default page
            return '/';
        }

        // Default redirection if no condition matches
        return '/login';
    }

    /**
     * login admin
     *
     * @param Request $request
     * @return void
     */
    public function login(Request $request)
    {
        // Validate Login Data
        $request->validate([
            'email' => 'required|max:50',
            'password' => 'required',
        ]);

        // Determine the intended redirect URL
        $redirectTo = session()->pull('url.intended', $this->redirectTo());
        session()->put('redirect_url', $redirectTo);

        // Attempt to login
        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
            session()->flash('success', 'Successfully Logged in!');
            Session::put('current_guard', 'admin');

            AuditTrailHelper::AuthAttempt('Login', 'User (' . $request->email . ') Logged in to the System');
            return redirect($redirectTo);
        } else if (Auth::guard('admin')->attempt(['username' => $request->email, 'password' => $request->password], $request->remember)) {
            session()->flash('success', 'Successfully Logged in!');
            Session::put('current_guard', 'admin');

            AuditTrailHelper::AuthAttempt('Login', 'User (' . $request->email . ') Logged in to the System');
            return redirect($redirectTo);
        } else if (Auth::guard('web')->attempt(['username' => $request->email, 'password' => $request->password], $request->remember)) {
            session()->flash('success', 'Successfully Logged in!');
            Session::put('current_guard', 'web');

            AuditTrailHelper::AuthAttempt('Login', 'User (' . $request->email . ') Logged in to the System');
            return redirect($redirectTo);
        } else if (Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
            session()->flash('success', 'Successfully Logged in!');
            Session::put('current_guard', 'web');

            AuditTrailHelper::AuthAttempt('Login', 'User (' . $request->email . ') Logged in to the System');
            return redirect($redirectTo);
        } else {
            // Log activity
            AuditTrailHelper::AuthAttempt('Login', 'Failed login attempt for User (' . $request->email . ')');

            // Login failed
            session()->flash('error', 'Invalid email or password.');
            return back();
        }
    }   

    /**
     * logout admin guard
     *
     * @return void
     */
    public function logout()
    {
        $user = Auth::guard('admin')->user();

        if (!$user) {
            Auth::guard('admin')->logout();
            return redirect()->route('admin.login');
        }

        // Log activity
        AuditTrailHelper::AuthAttempt('Logout', 'User (' . $user->username . ') Logged out from the System');

        try {
            // Logout from admin guard
            Auth::guard('admin')->logout();
        } catch (Exception $e) {
            // Fallback to web guard if admin logout fails
            Auth::guard('web')->logout();
        }

        // Redirect to admin login
        return redirect()->route('admin.login');
    }
}
