<?php

namespace App\Http\Controllers\Shop\Auth;

use App\Http\Controllers\Controller;
use App\Repositories\Core\User\ShopCart;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/';

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

    public function showLoginForm()
    {
        return view('Shop.auth.login');
    }

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

        if ($this->guard()->attempt($credentials, $request->get('remember'))) {
            ShopCart::migrateGuestCartToUser();
            $request->session()->regenerate();
            if (back()->getTargetUrl() === route('Shop.Orders.store')) {
                $route = 'Shop.Orders.order';
            } else {
                $route = 'home';
            }
    
            return redirect()->intended(route($route));
        }

        return back()->withErrors([
            'msg' => 'Identifiant ou mot de passe incorrect',
        ])->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';
    }

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