<?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 index()
    {
        // tampilan login
        return view("auth.login");
    }

    public function login(Request $request)
    {
        $credentials = $this->validate($request, [
            "email" => "required|email:dns",
            "password" => "required|max:16"
        ]);

        if (!Auth::attempt($credentials)) {
            return redirect()->back()->withInput()->with("errorLogin", "Email atau Password salah");
        }

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

        // Ambil user yang sedang login
        $user = Auth::user();

        // Cek role_id dan redirect sesuai role
        if ($user->role_id === '9e3efb34-c5ef-416e-b31e-58ba13807301') {
            return redirect('/')->with("login", "Selamat Datang, {$user->name}!");
        } else {
            // Guru/admin
            return redirect()->route("dashboard")->with("login", "Selamat Datang, {$user->name}!");
        }
    }
}