<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }

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

        if (Auth::attempt($credentials)) {

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

            if (Auth::user()->role == 'administrator') {
                return redirect()->route('administrator.dashboard');
            }

            if (Auth::user()->role == 'atasan') {
                return redirect()->route('dashboard.index');
            }

            if (Auth::user()->role == 'anak_asuh') {
                return redirect()->route('hasilPenilaian.index');
            }

            Auth::logout();

            return back()->withErrors([
                'nrp' => 'Role tidak dikenali.',
            ]);
        }

        return back()->withErrors([
            'nrp' => 'NRP atau password salah.',
        ])->onlyInput('nrp');
    }

    public function logout(Request $request)
    {
        Auth::logout();

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

        return redirect('/');
    }
}
