<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Rules\ReCAPTCHA;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{
  
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home 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::HOME;
    protected $redirectTo = '/admin/dashboard';

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

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

    protected function validateLogin(Request $request)
    {
        // dd($request->all());
        $rules = [
            $this->username() => 'required|email',
            'password'        => 'required|string|min:6',
            'recaptcha' => ['required', new ReCAPTCHA],
        ];
        
        $this->validate($request, $rules);
    }

    protected function authenticated(Request $request, $user)
    {
        // Se a senha está expirada
        if (!$user->password_expires_at || $user->password_expires_at->isPast()) {

            // Desloga imediatamente
            auth()->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()
                ->route('login')
                ->withErrors([
                    'email' => 'Sua senha expirou. Por favor, redefina sua senha para continuar.'
                ]);
        }

        return redirect()->intended($this->redirectPath());
    }

    public function logout(Request $request) {
        
        Auth::logout();
        Session::flush();
        header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
        header("Pragma: no-cache"); // HTTP 1.0.
        header("Expires: 0"); // Proxies.
        session()->flash('alert-success', 'Success logged out');
        return redirect('admin/login');
       
    }

    // Quantas tentativas são permitidas
    protected function maxAttempts()
    {
        return 4; // padrão
    }

    // Por quantos minutos o usuário fica bloqueado
    protected function decayMinutes()
    {
        return 20;
    }
}
