<?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\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
    {
        $request->authenticate();
        $request->session()->regenerate();

        $user = auth()->user();

        if ($user->role->slug === 'admin' || $user->role->slug === 'owner') {
        return redirect()->intended(route('admin.dashboard'));
        }

        if ($user->role->slug === 'staff-produksi') {
        return redirect()->intended(route('staffproduksi.dashboard'));
        }

        if ($user->role->slug === 'staff-gudang') {
            return redirect()->intended(route('staffgudang.dashboard'));
        }

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


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

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

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

        return redirect('/');
    }

    protected function authenticated(Request $request, $user)
    {
        // Mengarahkan berdasarkan slug role
        if ($user->role->slug == 'admin' || $user->role->slug == 'owner') {
            return redirect()->route('admin.dashboard');
        } 
        
        if ($user->role->slug === 'staff-produksi') {
            return redirect()->intended(route('staffproduksi.dashboard'));
        }
        
        if ($user->role->slug == 'staff-distribusi') {
            return redirect()->route('distribusi.dashboard');
        }

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