<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Validator;
use App\User;
class LoginController extends Controller
{

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


    public function Login(Request $request){
        $validator = Validator::make($request->all(), [
            'username' => 'required|exists:users,username',
            'password' => 'required',
        ], [
            'username.required' => 'Username diperlukan!',
            'username.exists' => 'Username tidak diketemukan',
            'password.required' => 'Password diperlukan'
        ]);

        if ($validator->fails()) {
            return redirect('/')
                        ->withErrors($validator)
                        ->withInput();
        } else {
             if (Auth::attempt(['username' => $request->username, 'password' => $request->password])) {
                if(Auth::user()->role == 'admin'){
                    return redirect()->intended('admin');
                }elseif(Auth::user()->role == 'k_supir'){
                    return redirect()->intended('k_supir');
                } else {
                    return redirect()->intended('klien');
                }
            } else {
                $validator->errors()->add('password', 'Password tidak benar');
                return redirect('/')
                            ->withErrors($validator)
                            ->withInput();
            }
        }
    }
}
