<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class SoporteController extends Controller
{
    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/soporte';

    protected $guard = 'soporte';

    /**
     * SoporteController constructor.
     */
    public function __construct()
    {
        $this->middleware('soporte', ['except' => ['logout', 'getLogin', 'postLogin']]);
    }

    public function getLogin()
    {
        if (Auth::guard($this->guard)->check()) {
            return $this->dashboard();
        }
        return $this->showLoginForm();
    }

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        $view = "auth.authenticate";

        if (view()->exists($view)) {
            return view($view);
        }
        return view('soporte.acceso.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function postLogin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()
            ->route('soporte.login')
            ->with('errors', ['message' => 'Necesita completar los campos', 'type' => 'warning']);
        }

        $credentials = [
            'username' => $request->username,
            'password' => $request->password,
            'deleted_at' => null,
            'soporte' => 1
        ];

        if (Auth::guard($this->guard)->attempt($credentials, true)) {
            return redirect($this->redirectTo);
        } else {
            return redirect()
            ->route('soporte.login')
            ->with('errors', ['message' => 'Datos ingresados son incorrectos', 'type' => 'danger']);
        }
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function loginUsername()
    {
        return property_exists($this, 'username') ? $this->username : 'username';
    }

    /**
     * @return \Illuminate\Http\RedirectResponse
     */
    public function dashboard()
    {
        return redirect()->route('soporte.index');
    }

    /**
     * @return \Illuminate\Http\RedirectResponse
     */
    public function logout()
    {
        Auth::guard($this->guard)->logout();
        return redirect()->route('soporte.login');
    }
}
