<?php namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;	
use App\User;
use Validator;
use Session;
use Mail;
use League\OAuth2\Client\Provider\LinkedIn;
use Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Profile;
use App\Services\CustomLoad;
use App\BusinessYears;

class UserController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| User Controller
	|--------------------------------------------------------------------------
	|
	| This controller renders your application's users functionality
	| like signup, login, forgot password.
	|
	*/

	/**
	 * The Guard implementation.
	 *
	 * @var Guard
	 */
	protected $auth;

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

	/**
	 * Show the application login page to the user.
	 *
	 * @return Login page
	 */
	/**
		 * Show the application login to the user.
		 *
		 * @return Response
		 */
		public function getLogin()
		{
/*			$user = User::where('username','=','jagadeesh')->get();
			$users = $user[0];
			echo "<pre>";
			print_r($users);
			exit;
			$this->auth->login($users);
*/			return view('login');
		}

		public function newSignup(Request $request)
		{
			$input = $request->all();
			$data['name'] = $input['fullname'];
			$data['email'] = $input['newemail'];
			$data['password'] = $input['newpassword'];
			//print_r($data); exit;
			//return Redirect::to('user/signup')->with('newdata',$data);
			
			return view('signup')->with(['validation_errors'=>'','social_data'=>$data,'business_years'=>$business_years]);
			
		}
		
		public function postLogin(Request $request)
		{
			//$post_data = Input::post();
			$input = $request->all();
			$this->validate($request, [
			'username' => 'required', 'password' => 'required',
			]);

			$credentials = $request->only('username', 'password');
                        $user_data=User::where('username','=',$credentials['username'])->where('user_type', '=', 'user')->where('deleted', '=', '0')->get();
                       if($user_data->count()>0)
                       {
			$result = User::where('username','=',$credentials['username'])->where('user_type','!=','admin')->get()->first();
			if(count($result)){
			if ($this->auth->attempt($credentials, $request->has('remember')))
			   {

				if($this->auth->user()->profile_completed==0)	
					return redirect()->intended($this->redirectPath());
				else
				     session()->regenerate();
                                     Session::put('user_type', $result->user_type);
                                     
                                     CustomLoad::AuthProfiles($result->id);
                                     
                                     
                                    return redirect('dashboard');

			   }
                         }
			}

		return redirect($this->loginPath())
					->withInput($request->only('username', 'remember'))
					->withErrors([
						'username' => $this->getFailedLoginMessage(),
					]);
	
		}

                 
                public function postadminlogin(Request $request)
                {
                        //$post_data = Input::post();
			$input = $request->all();
			$this->validate($request, [
			'username' => 'required', 'password' => 'required',
			]);

			$credentials = $request->only('username', 'password');
                       
			$result = User::where('username','=',$credentials['username'])->first();
                        /*echo "<pre>";
                        print_r($result);
                        exit;*/
                        if(isset($result->id))
                        {
                            if($result->user_type=='admin' && $this->auth->attempt($credentials, $request->has('remember')))
                            {
                                       session()->regenerate();
                                       Session::put('user_type', $result->user_type);

                                                return redirect('admin/dashboard');


                            }
                        }

		        return redirect('administrator')
					->withInput($request->only('username', 'remember'))
					->withErrors([
						'username' => $this->getFailedLoginMessage(),
					]);;
                }

		/**
		 * Get the post register / login redirect path.
		 *
		 * @return string
		 */
		public function redirectPath()
		{
			if (property_exists($this, 'redirectPath'))
			{
				return $this->redirectPath;
			}
	
			return property_exists($this, 'redirectTo') ? $this->redirectTo : '/profile/step1';
		}
	
		/**
		 * Get the path to the login route.
		 *
		 * @return string
		 */
		public function loginPath()
		{
			return property_exists($this, 'loginPath') ? $this->loginPath : '/user/login';
		}

		/**
		 * Get the failed login message.
		 *
		 * @return string
		 */
		protected function getFailedLoginMessage()
		{
			return 'These credentials do not match our records.';
		}
		
		public function getSignup()
		{
			$data = Session::get('data');
			echo "<pre>";
			print_r($data);
			exit;
		}

	/**
	 * Show the application signup page to the user.
	 *
	 * @return Signup page
	 */
	public function signup(Request $request)
	{
				$social_data = Session::get('social_data');
                $business_years = BusinessYears::getAllYears();	
                $data['gender']="";$data['years_in_business']="";
		
		if(isset($social_data->id)):
			$user = User::where('fb_id','=',$social_data->id)->get();
			if(isset($user[0])):
				$this->auth->login($user[0]);						
				return Redirect::to($this->redirectPath());
			else:
				  
			 function randomuser($len = 8)
				{
				   $user = '';
				   $lchar = 0;
				   $char = 0;
				   for($i = 0; $i < $len; $i++)
				   {
				       while($char == $lchar)
				       {
				           $char = rand(48, 109);
				           if($char > 57) $char += 7;
				           if($char > 90) $char += 6;
				       }
				       $user .= chr($char);
				       $lchar = $char;
				   }
				   return $user;
				}	 
             function randomPassword() {
				    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
				    $pass = array(); //remember to declare $pass as an array
				    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
				    for ($i = 0; $i < 8; $i++) {
				        $n = rand(0, $alphaLength);
				        $pass[] = $alphabet[$n];
				    }
				    return implode($pass); //turn the array into a string
				}
				$pass=randomPassword();
				$username=randomuser(10);
				$social=$social_data->user;
			
				 $result = User::create([
                                    'name'                   => $social['name'],
	                                'username'               => $username,
	                                'email'                  => $social['email'],
	                                'password'               => bcrypt($pass),
	                                'gender'                 => $social['gender'],
	                                'fb_id'                  => $social['id'],
	                                'selected_profile'       => "T",
                                ]);
                    if($result){
                    	Mail::send('emails.welcome', ['name' => $social['name']], function($message)
					        use($social){
					            $message->to($social['email'], $social['name'])->subject('Welcome!');       		
					        });
                    	Mail::send('emails.confirmation', ['name' => $social['name'],'username' => $username,'password' => $pass], function($message)
					        use($social){
					            $message->to($social['email'], $social['name'])->subject('Welcome!');       		
					        });
                    	$this->auth->login($result);
                    	return redirect($this->redirectPath());
                      }
			endif;
		endif;
		
		if(isset($social_data->name))
			$social_data->name = $social_data->name;
		else if(isset($social_data->firstName))
			$social_data->name = $social_data->firstName." ".$social_data->lastName;

		if(isset($social_data->emailAddress))
			$social_data->email = $social_data->emailAddress;
		else if(isset($social_data->email))
			$social_data->email = $social_data->email;
		
		
		$input_new = $request->all();
		//$social_data = new stdClass();
		if(isset($input_new))
		{
			if(isset($input_new['fullname']))
				$social_data['name'] = $input_new['fullname'];
			
			if(isset($input_new['newemail']))
				$social_data['email'] = $input_new['newemail']; 
			if(isset($input_new['newpassword']))
				$social_data['password'] = $input_new['newpassword']; 
		}
		
        $validation_errors = "";
       
       
        $name = $request->input('signup');
        if($name=='signup')
        {//echo $request->input('selected_profile');
                $data = array(
                                'name'                   => $request->input('name'),
                                'username'               => $request->input('username'),
                                'email'                  => $request->input('email'),
                                'password'               => $request->input('password'),
                                'password_confirmation'  => $request->input('password_confirmation'),
                                'gender'                 => $request->input('gender'),
                                'dob'                    => $request->input('dob'),
                                'linked_id'              => $request->input('linked_id'),
                                'fb_id'                  => $request->input('fb_id'),
                                'fb_access_token'        => $request->input('fb_access_token'),
                                'city'                   => $request->input('city'),
                                'years_in_business'      => $request->input('years_in_business'),
                                'selected_profile'       => $request->input('selected_profile'),
                               );
                if($request->input('selected_profile')=='T')
                {
                $messages = [
                                'name'      => 'required|max:255',
                                'username'  =>'required|max:255|unique:users',
                                'email'     => 'required|email|max:255|unique:users',
                                'password'  => 'required|confirmed|min:6',
                                'gender'    => 'required',
                                'dob'       => 'required',
                            ];
                }
                 if($request->input('selected_profile')=='O')
                {
                $messages = [
                                'name'      => 'required|max:255',
                                'username'  =>'required|max:255|unique:users',
                                'email'     => 'required|email|max:255|unique:users',
                                'password'  => 'required|confirmed|min:6',
                                'years_in_business' => 'required',
                               // 'gender'    => 'required',
                                //'dob'       => 'required',
                            ];
                }
                $validation = Validator::make($data, $messages);
                if($validation->fails())
                {

                    $validation_errors = $validation->errors()->all() ;  
                }else{
		    if(!empty($data['dob'])):
                      $date = explode("/",$data['dob']);
                      $data['dob'] =  $date[2]."-".$date[0]."-".$date[1];  
                    else:
                      $data['dob'] ="";
                    endif;
                    $result = User::create([
                                    'name'            => $data['name'],
                                    'username'        => $data['username'],
                                    'email'           => $data['email'],
                                    'password'        => bcrypt($data['password']),
                                    'gender'          => $data['gender'],
                                    'dob'             => $data['dob'],
				    'linked_id'       => $data['linked_id'],
                                    'fb_id'           => $data['fb_id'],
                                    'fb_access_token' => $data['fb_access_token'],
                                    'city'            => $data['city'],
                                    'years_in_business'=> $data['years_in_business'],
                                    'selected_profile'=> $data['selected_profile'],
                                ]);
                    if($result){
                    	Mail::send('emails.welcome', ['name' => $data['name']], function($message)
					        use($data){
					            $message->to($data['email'], $data['name'])->subject('Welcome!');       		
					        });
                    	$this->auth->login($result);
                    	return redirect($this->redirectPath());
                        //return redirect('user/login');
                    }
                }
		  }
        return view('signup')->with(['validation_errors'=>$validation_errors,'social_data'=>$social_data,'business_years'=>$business_years]);

	}
	
	public function linkedin(Request $request)
	{
		// User denial @ last moment from Ln page
		if($request->input('error'))
		{
			return Redirect::to('user/signup')->with('error_description',$request->input('error_description'));
			exit;
		}

		$provider = new Linkedin(Config::get('social.linkedin'));
		if (!$request->input('code')) {
			// If we don't have an authorization code, get one
			$provider->authorize();
		} else {
			try {
				// Try to get an access token (using the authorization code grant)
				$t = $provider->getAccessToken('authorization_code', array('code' => $request->input('code')));
				try {
					// We got an access token, let's now get the user's details
					$userDetails = $provider->getUserDetails($t);
	//                $resource = '/v1/people/~:(firstName,lastName,emailAddress,pictureUrl,positions,educations,threeCurrentPositions,threePastPositions,dateOfBirth,location)';
					$resource = '/v1/people/~:(id,firstName,lastName,emailAddress,dateOfBirth)';
					$params = array('oauth2_access_token' => $t->accessToken, 'format' => 'json');
					$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
					$context = stream_context_create(array('http' => array('method' => 'GET')));
					$response = file_get_contents($url, false, $context);
					$data = json_decode($response);
					$data->linked_id = $data->id;
					
					$user = User::where('linked_id','=',$data->id)->get();
					if(isset($user[0])):
						$this->auth->login($user[0]);						
						return Redirect::to($this->redirectPath());
					else:
						function randomuser($len = 8)
						{
						   $user = '';
						   $lchar = 0;
						   $char = 0;
						   for($i = 0; $i < $len; $i++)
						   {
						       while($char == $lchar)
						       {
						           $char = rand(48, 109);
						           if($char > 57) $char += 7;
						           if($char > 90) $char += 6;
						       }
						       $user .= chr($char);
						       $lchar = $char;
						   }
						   return $user;
						}	 
		             function randomPassword() {
						    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
						    $pass = array(); //remember to declare $pass as an array
						    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
						    for ($i = 0; $i < 8; $i++) {
						        $n = rand(0, $alphaLength);
						        $pass[] = $alphabet[$n];
						    }
						    return implode($pass); //turn the array into a string
						}
						$pass=randomPassword();
						$username=randomuser(10);

						$result = User::create([
		                                    'name'                   => $data->firstName,
			                                'username'               => $username,
			                                'email'                  => $data->emailAddress,
			                                'password'               => bcrypt($pass),
			                                'linked_id'              => $data->id,
			                                'selected_profile'       => "T",
		                                ]);
	                    if($result){
	                    	Mail::send('emails.welcome', ['name' => $data->firstName], function($message)
						        use($data){
						            $message->to($data->emailAddress, $data->firstName)->subject('Welcome!');       		
						        });
	                    	Mail::send('emails.confirmation', ['name' => $data->firstName,'username' => $username,'password' => $pass], function($message)
						        use($data){
						            $message->to($data->emailAddress, $data->firstName)->subject('Welcome!');       		
						        });
	                    	$this->auth->login($result);
	                    	return redirect($this->redirectPath());
	                      }
					endif;
				} catch (Exception $e) {
					return 'Unable to get user details';
				}
	
			} catch (Exception $e) {
				return 'Unable to get access token';
			}
		}
	}

	/**
	 * Log the user out of the application.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function getLogout()
	{     
            $value = Session::get('user_type');
           
            if($value == 'admin')
               { 
                Session::flush();
		$this->auth->logout();
                return redirect('administrator');
		
               }
	       else
               {   
                   Session::flush();
                   $this->auth->logout();
                    return redirect('user/login');
               }

		
	}
    public function maile()
    {
        
        Mail::send('emails.welcome', ['key' => 'value'], function($message)
        {
            $message->to('keshav@dotcomweavers.com', 'John Smith')->subject('Welcome!');
        });
    }
	
	public function check_username(Request $request)	
	{
		$input = $request->all();
		$result = User::where('username','=',$input['username'])->get();
		if(isset($result[0]))
			$return = "false";
		else
			$return = "true";

		echo json_encode(array('valid' => $return,));
	}

	public function check_email(Request $request)	
	{
		$input = $request->all();
		$result = User::where('email','=',$input['email'])->get();
		if(isset($result[0]))
			$return = "false";
		else
			$return = "true";

		echo json_encode(array('valid' => $return,));
	}
           public function forgotpwd()	
	{
	    $validation_errors="";	
            return view('forgotpwd')->with(['validation_errors'=>$validation_errors]);;
	}
        public function forgotmail(Request $request)
        {
        $validation_errors = "";

        $name = $request->input('forgot');
        if($name=='forgot')
        {
           
                $data = array('email' => $request->input('email'));
                $validation = Validator::make($data, ['email' => 'required|email|max:255']);
                if($validation->fails())
                {
                    $validation_errors = $validation->errors()->all() ;  
                  
                }else{
		    $result=User::where('email', '=',$request->input('email'))->where('user_type', '=', 'user')->get();
                
                    if(count($result)==1){
                        $paswd=str_random(6);
                        User::where('email', '=', $request->input('email'))->where('user_type', '=', 'user')->update(array('password' => bcrypt($paswd)));
                        
                    	Mail::send('emails.forgotpwd', ['password' => $paswd,'name' => $result[0]->name,'username' => $result[0]->username ], function($message)
					        use($data){
					            $message->to($data['email'])->subject('Temporary Password!');       		
					        });
                                                
                          return Redirect::back()->with('succ_msg',"Mail Sent Successfully");                       
                    
                            }
                           else
                            {
                          return Redirect::back()->with('error_msg',"Email address doesn't exists in our records,Please signup to create an account.");    
                            }
                }
		 
            
        }
        return view('forgotpwd')->with(['validation_errors'=>$validation_errors]);

	
        
        }

}
