<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
 
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 = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */

    protected function login(Request $request) {

        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if(Auth::attempt($credentials)){
           $user = Auth::user(); 
           $user_role=Auth::user()->role;
           
            $jsondata = [];
            $jsondata = $user;
            switch($user_role){

                case 1;
                return response()->json(['success'=> true, 
                'message'=> 'Login Successfully', 
                'data'=>$jsondata]);
                   // return redirect('/superadmin');
                    break;
                case 2;
                return response()->json(['success'=> true, 
                'message'=> 'Login Successfully', 
                'data'=>$jsondata]);
                   //return redirect('/admin');
                    break;    
                case 3;
                return response()->json(['success'=> true, 
                'message'=> 'Login Successfully', 
                'data'=>$jsondata]);
                  // return redirect('/manager');
                    break;  
                case 5;
                return response()->json(['success'=> true, 
                'message'=> 'Login Successfully', 
                'data'=>$jsondata]);
                 // return redirect('/patient');
                    break; 
                default;
                    Auth::logout();
                    return response()->json(['success'=> true, 
                    'message'=> 'Something went wrong']);
                //  return redirect('/login')->with('error', ' Something went wrong');    
            }

        } else {
           return redirect('/login');
           return response()->json(['success'=> true, 
           'message'=> 'Login credential is wrong, please try again']);
        }
    }

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
        // $this->middleware('auth')->only('logout');
    }
}