<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    // Menampilkan Halaman Login
    public function showLogin()
    {
        return view('login');
    }

    // Proses Login
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'username' => 'required',
            'password' => 'required',
        ]);

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

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

            // CEK ROLE
            if (Auth::user()->role == 'admin') {

                return redirect('/admin');
            }

            // Default mahasiswa
            return redirect('/');
        }

        return back()->withErrors([
            'username' => 'Username atau password salah.'
        ]);
    }

    // Menampilkan Halaman Register
    public function showRegister()
    {
        return view('register');
    }

    // Proses Register
    public function register(Request $request)
    {
        $request->validate([
            'username' => 'required|unique:users|min:4',
            'password' => 'required|confirmed|min:6',
        ]);

        User::create([
            'username' => $request->username,

            'password' => Hash::make($request->password),

            // Default role mahasiswa
            'role' => 'mahasiswa',
        ]);

        return redirect()
            ->route('login')
            ->with('success', 'Akun berhasil dibuat! Silahkan login.');
    }

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

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

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

        return redirect('/');
    }
}