<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function index(): View|RedirectResponse
    {
        if (Auth::check()) {
            return redirect()->route('dashboard.overview');
        }

        return view('pages.auth.login', [
            'pageTitle' => 'Masuk Akun',
            'metaDesc' => 'Masuk akun untuk mengakses admin panel',
        ]);
    }

    public function auth(LoginRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();
        $identifier = filter_var($validatedData['login'], FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        if (Auth::attempt([
            $identifier => $validatedData['login'],
            'password' => $validatedData['password'],
        ])) {
            $user = Auth::user();
            if ($user->is_active) {
                notify()->success("Selamat datang, {$user->biography->full_name}!", 'Berhasil');

                return redirect()->route('dashboard.overview');
            }

            Auth::logout();
            notify()->info('Akun Anda saat ini tidak aktif. Silakan hubungi administrator untuk informasi lebih lanjut', 'Informasi');

            return redirect()->route('auth.login');
        }

        notify()->warning('Pastikan email / nama pengguna dan kata sandi yang Anda masukkan benar', 'Gagal');

        return redirect()->route('auth.login');
    }

    public function logout(): RedirectResponse
    {
        Auth::logout();

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

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

        return redirect('auth/login');
    }
}
