<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    /**
     * Menampilkan form login.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('auth.login');
    }

    /**
     * Memproses permintaan login.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        // Validasi data input
        $request->validate([
            'username' => 'required|string', // Perubahan di sini
            'password' => 'required',
        ]);

        // Menggunakan kolom 'username' untuk otentikasi
        $credentials = $request->only('username', 'password'); // Perubahan di sini

        // Coba melakukan otentikasi
        if (Auth::attempt($credentials)) {
            // Cek status user setelah login berhasil
            $user = Auth::user();
            if ($user->status === 'active') {
                // Regenerate session untuk keamanan
                $request->session()->regenerate();

                // Update last_login
                $user->last_login = now();
                $user->save();

                // Redirect ke halaman dashboard
                return redirect()->intended('/dashboard'); 
            }

            // Jika status tidak 'active', logout user
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return back()->withErrors([
                'username' => 'Akun Anda tidak aktif. Silakan hubungi administrator.', // Perubahan di sini
            ])->withInput($request->only('username'));
        }

        // Jika otentikasi gagal
        return back()->withErrors([
            'username' => 'Username atau password salah.', // Perubahan di sini
        ])->withInput($request->only('username'));
    }

    /**
     * Log out user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        Auth::logout();

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

        return redirect('/');
    }
}
