<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * Redirect setelah login berdasarkan role.
     */
    protected function authenticated(Request $request, $user)
    {
        if ($user->role === 'admin') {
            return redirect()->route('dashboard.admin');
        } elseif ($user->role === 'user') {
            return redirect()->route('dashboard.user');
        } elseif ($user->role === 'customer') {
            return redirect()->route('dashboard.customer');
        }

        return redirect('/home'); // Default jika role tidak dikenali
    }

    /**
     * Logout dan redirect ke halaman login.
     */
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/login')->with('success', 'Anda telah logout.');
    }

    /**
     * Hanya pengguna yang belum login yang dapat mengakses halaman login.
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}
