<?php

namespace App\Http\Controllers;

use App\User;
use Auth;
use Validator;
use Illuminate\Http\Request;

class AuthController extends Controller {

    protected $redirectTo = '/titulo/listar';
    protected $redirectFails = 'login';

    public function authenticate(Request $request) {
        $validator = Validator::make(
                        [
                    "email" => $request->input("email"),
                    "password" => $request->input("password")
                        ], [
                    "email" => "required",
                    "password" => "required"
                        ]
        );

        if ($validator->fails()) {
            return redirect($this->redirectFails)->withInput()->withErrors($validator);
        }

        $email = $request->input("email");
        $password = $request->input("password");

        $array = ['.', '-', '/'];
        if (e_cpf(trim($email)) || e_cnpj(trim($email))) {
            $email = str_replace($array, "", trim($email));
        }

		$user = User::where('cnpj_cpf', '=', $email)->first();
        if (count($user) == 0) {
			$user = User::where('email', '=', $email)->first();
			if (count($user) == 0) {
					return redirect($this->redirectFails)->with('mensagem', "Usuário não encontrado.");
			}
		}
		
        //tenta logar pelo email
        if (Auth::attempt(['email' => $email, 'password' => $password], $request->has('remember'))) {
            return redirect()->intended($this->redirectTo);
        }
        //tenta logar pelo cnpj
        if (Auth::attempt(['cnpj_cpf' => $email, 'password' => $password], $request->has('remember'))) {
            return redirect()->intended($this->redirectTo);
        }

		//"As informações de login não foram encontradas."
        return redirect($this->redirectFails)->with('mensagem', "Senha Inválida");
    }

}
