<?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;
use App\Logins;
use App\User;
use App\Http\Controllers\ConfigController;

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
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }


    public function credentials(Request $request)
    {
        return [
            'email' => $request->email,
            'password' => $request->password,
            'status' => 'a',
        ];
    }


    protected function authenticated(Request $request)
    {

        switch (Auth::user()->role_id) {
            case '1':
                $login = new Logins();
                $login->ip = $request->getClientIp();
                $login->login_type = 'WEB';
                $login->user_id = Auth::user()->id;
                $login->login_date = date('d-m-Y h:i:s A');
                $login->save();

                break;

            case '2':
                $login = new Logins();
                $login->ip = $request->getClientIp();
                $login->login_type = 'WEB';
                $login->user_id = Auth::user()->id;
                $login->login_date = date('d-m-Y h:i:s A');
                $login->save();
                break;  

            case '3':
                $login = new Logins();
                $login->ip = $request->getClientIp();
                $login->login_type = 'API';
                $login->user_id = Auth::user()->id;
                $login->login_date = date('d-m-Y h:i:s A');
                $login->save();
                break;         
        }


        //Check password expiry
        if(ConfigController::check_password_expiry(Auth::user()->id))
        {
            $password = User::find(Auth::user()->id);
            $password->reset = 'on';
            $password->save();
        }


        $users = User::find(Auth::user()->id);
        $users->pac_status = 'n';
        if(Auth::user()->role_id == '4')
        {
            $users->branch_id = '';
        }
        
        $users->save();

        \Auth::logoutOtherDevices(request('password'));
    }
}
