<?php

namespace App\Http\Controllers\Shop\Auth;

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

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/';

    public function __construct()
    {
        // $this->middleware('guest')->except('logout');
    }

    protected function guard()
    {
        return Auth::guard('customer');
    }

    public function showLoginForm()
    {
        $data['url'] = route('Shop.login.post');
        return view('Shop.auth.login', $data);
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email'   => 'required|email',
            'password' => 'required|min:8',
        ]);

        if (Auth::guard('customer')->attempt($credentials, $request->get('remember'))) {
            $request->session()->regenerate();
            return redirect()->intended(route('home'));
        }
        return back()->withInput($request->only('email', 'remember'));
    }

    public function logout(Request $request)
    {
        $sessionKey = $this->guard()->getName();
        $this->guard()->logout();
        $request->session()->forget($sessionKey);
        return redirect()->route('home');
    }

    public function username()
    {
        return 'email';
    }
}
