<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use App\Models\User;
use Illuminate\Console\View\Components\Alert;
use Illuminate\Support\Facades\Redis;

class LoginController extends Controller
{
    // public function __construct()
    // {
    //     $this->middleware('guest')->except('logout');
    // }
    
    public function index()
    {
        if (Auth::check()) {
            return $this->redirectToDashboard();
        }
        return view('login');
    }

    public function login(Request $request)
    {
        // Validate the request
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string|min:8',
        ], [
            'email.email' => 'Format email tidak valid.',
            'password.min' => 'Password harus minimal 8 karakter.',
        ]);

        $user = User::where('email', $request->email)->first();

        if (!$user) {
            return redirect()->route('login')->with('error', 'Email tidak terdaftar.');
        }

        $credentials = $request->only('email', 'password');

        // Attempt to authenticate the user
        if (Auth::attempt($credentials)) {
            return $this->redirectToDashboard();
        }

        // Jika gagal, ubah pesan error
        return redirect()->back()->withErrors([
            'email' => 'Email atau password Anda salah!',
        ]);
    }

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

    private function redirectToDashboard()
    {
        $user = Auth::user();

        //Mapping roles ke routes
        $roleRoutes = [
            'admin' => 'mahasiswa.dashboard',
            'laman' => 'mahasiswa.dashboard',
        ];

        foreach ($roleRoutes as $role => $route) {
            if ($user->role == $role) {
                return redirect()->route($route);
            }
        }

        Auth::logout();
        return redirect()->route('login')->with('error', 'Role tidak dikenal.');
    }
}