<?php

namespace App\Http\Controllers\Auth;

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

class LoginController extends Controller
{
    public function showLoginForm()
    {
        // Jika sudah login, redirect ke dashboard sesuai role
        if (Auth::check()) {
            return $this->redirectByRole();
        }
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();
            return $this->redirectByRole();
        }

        return back()->withErrors([
            'email' => 'Email atau password salah',
        ]);
    }

    protected function redirectByRole()
    {
        $user = Auth::user();
        
        // Tolong perhatika setiaprole yang ada apakah sungguh ada di database
        // dan apakah sudah sesuai dengan route yang ada
        // Jika ada role yang tidak sesuai, logout user
        // dan redirect ke halaman login dengan pesan error
        switch ($user->role) {
            case 'admin':
                return redirect()->route('home');
            case 'karyawan':
                return redirect()->route('dashboard.karyawan');
            case 'mahasiswa':
                return redirect()->route('dashboard.mahasiswa');
            default:
                Auth::logout();
                return redirect('/login')->with('error', 'Role tidak valid');
        }
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/login');
    }
}