<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * Halaman pilih login (landing page login)
     */
    public function index()
    {
        return view('Auth.choose-login-admin');
    }

    /**
     * Menampilkan form login Admin
     */
    public function showAdminLoginForm()
    {
        return view('Auth.login'); // login admin
    }

    /**
     * Proses login Admin
     */
    public function adminLogin(Request $request)
    {
        $credentials = $request->validate([
            'email'    => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($credentials, $request->remember)) {
            $request->session()->regenerate();

            if (auth()->user()->role === 'admin') {
                return redirect()->route('admin.dashboard');
            }

            Auth::logout();
            return back()->withErrors(['email' => 'Akun ini bukan admin']); // Pesan yang Anda dapatkan
        }

        return back()->withErrors(['email' => 'Email atau password salah']);
    }

    /**
     * Menampilkan form login Pengunjung
     */
    public function showUserLoginForm()
    {
        return view('Auth.login-user'); // login pengunjung
    }

    /**
     * Proses login Pengunjung
     */
    public function userLogin(Request $request)
    {
        $credentials = $request->validate([
            'email'    => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($credentials, $request->remember)) {
            $request->session()->regenerate();

            return redirect()->route('user.dashboard'); // dashboard pengunjung
        }

        return back()->withErrors([
            'email' => 'Email atau password yang Anda masukkan salah.',
        ]);
    }

    /**
     * Logout untuk semua user
     */
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('home');
    }
}
