<?php

namespace App\Http\Controllers\Auth;

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

class LoginController extends Controller
{
    public function index()
    {
        if (auth()->check()) {
            return redirect()->intended();
        }
        return view('website.auth.login');
    }

    public function login(Request $request)
    {
        // Validasi data input
        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required|min:6',
        ]);

        // Jika validasi gagal
        if ($validator->fails()) {
            toast('Gagal, silahkan cek kembali!', 'error');
            return redirect()->back();
        }

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

        if ($user) {
            if ($user->status == 'tidak aktif') {
                toast('Gagal, akun anda belum aktif. kabarin admin pertama!', 'error');
                return redirect()->back();
            } else {
                if ($user) {
                    if (Hash::check($request->password, $user->password)) {
                        Auth::login($user);

                        $redirectRoute = match ($user->role) {
                            'admin' => route('dashboard.index'),
                            'user' => route('home.index'),
                            default => route('login.index'),
                        };

                        toast()->success('Login Berhasil', 'Anda telah login sebagai ' . $user->name);
                        return redirect($redirectRoute);
                    } else {
                        toast('Gagal, password anda salah!', 'error');
                        return redirect()->back();
                    }
                } else {
                    toast('Gagal, akun anda belum terdaftar!', 'error');
                    return redirect()->back();
                }
            }
        } else {
            toast('Gagal, akun anda belum terdaftar!', 'error');
            return redirect()->back();
        }
    }

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