<?php
namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use DB;
use Auth;
use App\User;
use Validator;

class LoginController extends BaseController
{
	public $auth;
	
	public function index()
	{
		return view('ilogin');
	}
	public function loginauthentication(Request $req)
	{
		$validator = Validator::make($req->all(), [
            'username' => 'required',
            'password' => 'required'
        ]);
		$canLogin = false;
		//$username = $req->input('username');
		//$password = md5($req->input('password'));
		//$status='Active';
		$auth = user::where('usr_loginid',$req->input('username'))->first();
		 if($auth)
		 {
					Auth::login($auth);
					$password = Auth::user()->usr_password;
					
					if(md5($req->input('password')))
					{
						if (md5($req->input('password'))==$password)
						{
							$canLogin=true;
						}
					}					
					else
					{
						$data=['msg' => 'Invalid Password'];
						return $this->output_format($req,$data,404);
						$canLogin=false;
					}
		 }
		 	if($canLogin)
		 	{		
				$data=['home' => '/home'];
				return $this->output_format($req,$data,404);			
			}
			 else
			{
				$data=['msg' => 'Invalid Username or Password'];
               return $this->output_format($req,$data,404);			  			  						
			}		
	}
	
	public function output_format(Request $req,$data,$status) {
		 $format=$req->input('format');
		 if($format=='jsonp')
			return response()->json($data,$status)->setCallback($req->input('callback'));
		else
			return response()->json($data,$status);
    }
	
	public function logout()
	    {
	    	if(Auth::check())
	    	{
			   Auth::logout();
			   return redirect('/');
		    }
		    else
		    {
			  return redirect('/');
		    }
	    }
}