<?php

namespace App\Http\Controllers\Auth;

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

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

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        // Authenticate the user
        $request->authenticate();
    
        // Get the authenticated user
        $user = Auth::user();
    
        // Check the user type and redirect accordingly before regenerating the session
        if ($user->user_type == 'admin') {
            $request->session()->regenerate();
            return redirect()->intended(route('dashboard'));
        }elseif ($user->user_type == 'employee') {
            $request->session()->regenerate();
            return redirect()->intended(route('employee.dashboard'));
        }elseif ($user->user_type == 'manager') {
            $request->session()->regenerate();
            return redirect()->intended(route('dashboard.manager'));
        }elseif ($user->user_type == 'client') {
            $request->session()->regenerate();
            return redirect()->intended(route('dashboard.client'));
        }

    }

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

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

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

        return redirect('/');
    }
}
