<?php

namespace App\Http\Controllers;

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

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

    public function login(Request $request)
    {
        // Validasi input
        $credentials = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        // Coba untuk melakukan autentikasi menggunakan guard 'anggota'
        if (Auth::guard('anggota')->attempt($credentials)) {
            // Jika autentikasi berhasil
            $request->session()->regenerate();

            return redirect()->intended('/dashboard')->with('success', 'Login successful');
        }

        // Jika autentikasi gagal
        return back()->withErrors(['login_failed' => 'Login failed, please check your username and password.'])->withInput();
    }

    public function logout(Request $request)
    {
        Auth::guard('anggota')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/login')->with('success', 'Logout successful');
    }
}
