<?php

namespace App\Http\Controllers\Store;

use Illuminate\Http\RedirectResponse;
//Check the request is valid
use App\Http\Requests\Admin\LoginRequest;
use App\Http\Controllers\Controller;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Auth;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Session;
use Illuminate\View\View;


class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controllers
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your Web screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    // use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::STORE;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('guest')->except('logout');
    }

    /**
     * Show the application dashboard.
     * @return View
     */
    public function index()
    {
        return view('store.login');
    }

    /**
     * Function for Web login to the cms
     * @param LoginRequest $request
     * @return RedirectResponse|Redirector
     */
    public function authenticate(LoginRequest $request) :RedirectResponse
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials, $request->remember)) {
            /**
             * Check if the dashboard is disabled
             * for other administrators, other than the super admin
             */

            if (!in_array(Auth::user()->role, ['store_admin', 'store_user'])  ){
                    Auth::logout();
                    return redirect('store/login')->with('error', __('dashboard.failed'));
            }

            // Authentication passed...
            return redirect('/store');
        }

        return redirect('/store/login')->withInput()->with('error', __('auth.failed'));
    }


    /**
     * Web logout
     * @return RedirectResponse|Redirector
     */
    public function logout() :RedirectResponse
    {
        Session::flush();
        Auth::logout();
        return redirect('/store/login');
    }
}
