// Service : Login
$mainframe = JFactory::getApplication();
$option = JRequest::getVar('option','com_webservice','','string');
$post = JRequest::get ('post'); 

 global $HTTP_RAW_POST_DATA;
 
 $post = json_decode($HTTP_RAW_POST_DATA, true);
 
$uri = JURI::getInstance();
$url= $uri->root();
$options = array();
$options['remember'] = 'false';
$options['return'] = '';
//$post["isSocial"] = 'NO';
$isSocial = $post["isSocial"];
//$post["email"] = 'android.dev@gmail.com';$post["password"] = '123456';
/*$post["isSocial"] = 'NO';
$post['socialId']=0;
$post["username"] = $post["email"];
$post["email"]="meghabparmar@yahoo.co.in";
$post["password"] = "123456";
$post['devicetoken'] = "Simulator";
$post['deviceaccess'] = "1";*/
//$post['pushnotification']=1;
//$post['favoritenotification']=1;
 
$post["username"] = $post["email"];

//$post['devicetoken']='5356a2a1c4079b05036b2a354441218dba8382bfb91518159da1afb4cbeadb91';


	if($isSocial=='NO'){
		
		 
		$username = $post["username"] ;
		$password  =$post["password"];
		if($username=="" && $password=="") {
		$arr = array('success' => 0, 'message' => "Please enter Username and Password" );	
		echo json_encode($arr);exit;
		}
		
		
		
		$credentials = array();
		$credentials['username'] = $username; 
		$credentials['password'] = $password;
		$user=JFactory::getUser($credentials['username']);
		
		 
		
		$sql="SELECT u.id,u.name,u.email,au.gender,au.dob FROM #__users as u LEFT JOIN #__jetour_appusers as au ON au.user_id=u.id WHERE u.username='".$credentials["username"]."'"; 
		$db->setQuery($sql);
		$result1 = $db->loadObject();
		
		$update='UPDATE #__jetour_appusers SET deviceaccess="'.$post['deviceaccess'].'" WHERE  user_id="'.$result1->id.'"';
		$db->setQuery($update);
		$db->Query();
		
		
		
		if($result1){ 
		
			$sql="SELECT id FROM #__jetour_appalldevices WHERE devicetoken ='".$post['devicetoken']."' AND deviceaccess=".$post['deviceaccess'] ;	
			$db->setQuery($sql);
			$devicefound = $db->loadResult();
			
			if($devicefound){
				$update='UPDATE #__jetour_appalldevices SET user_id="'.$result1->id.'",deviceaccess="'.$post['deviceaccess'].'" WHERE  devicetoken="'.$post['devicetoken'].'"';
				$db->setQuery($update);
				$db->Query();
				
			}else{
				$deinsert='INSERT INTO #__jetour_appalldevices (`user_id`,`deviceaccess`,`devicetoken`) VALUES ("'.$result1->id.'","'.$post['deviceaccess'].'","'.$post['devicetoken'].'")';
				$db->setQuery($deinsert);
				$db->Query();
			
			}
		
		
		$error = $mainframe->login($credentials,$options);
		
			$sqlfav="SELECT COUNT(f.package_id) as totalfavorite FROM #__jetour_favoritepackage as f LEFT JOIN  #__jetour_package as p ON p.id=f.package_id WHERE f.user_id=".$result1->id." AND ( `start_date` <= DATE(NOW()) AND `end_date` >= DATE(NOW()) )";
			$db->setQuery($sqlfav);
			$totalfavorites = $db->LoadResult();
		
		$profile = array();
		 $profile['userId']   = $result1->id;
		 $profile['name']   = $result1->name;
		 $profile['username']  = $credentials["username"];
		 $profile['email']  = $result1->email;
		 $profile['gender']  = $result1->gender;
		 $profile['dob']  = $result1->dob;
		 $profile['favoritecount']  =$totalfavorites;
		 //$profile['notification_status']  = $result1->pushnotification;
		 
		if($error==1){ 
						$arr = array('success' => 1, 'username' => $credentials["username"], 'profile' => $profile);
						echo json_encode($arr);exit;
					
					}else{
		
						$arr = array('success' => 0, 'message' => "Auth Failed" );	
						echo json_encode($arr);exit;
					}
		}else{
				$arr = array('success' => 0, 'message' => "Auth Failed" );	
				echo json_encode($arr);exit;
		
		}
	}else{
	
	//$socialId = $post['socialId'];
	
		if($post["email"]=="" || $post["email"]=="(null)") {
		$arr = array('success' => 0, 'message' => "Please Provide Your Username" );	
		echo json_encode($arr);exit;
		}
	
	
	
	   		$email    =  $post["email"];
			$db = JFactory::getDbo();
			$app = JFactory::getApplication();
			$sql="SELECT * FROM #__users WHERE email='".$email."'";
			$db->setQuery($sql);
			$userinfo= $db->LoadObject();
			 
	
		if(count($userinfo)){
			
			$user=@$userinfo->username;
			$passw=@$userinfo->password;
	
			/*$update='UPDATE #__users SET devicetoken="'.$post['devicetoken'].'",deviceaccess="'.$post['deviceaccess'].'" WHERE  username="'.$user.'"';
			$db->setQuery($update);
			$db->query();*/
			
			$update='UPDATE #__jetour_appusers SET deviceaccess="'.$post['deviceaccess'].'" WHERE  user_id="'.$userinfo->id.'"';
			$db->setQuery($update);
			$db->Query();
			
			
			
			$sql="SELECT id FROM #__jetour_appalldevices WHERE devicetoken ='".$post['devicetoken']."' AND deviceaccess=".$post['deviceaccess'] ;	
			$db->setQuery($sql);
			$devicefound = $db->loadResult();
			
			if($devicefound){
				$update='UPDATE #__jetour_appalldevices SET user_id="'.$userinfo->id.'",deviceaccess="'.$post['deviceaccess'].'" WHERE  devicetoken="'.$post['devicetoken'].'"';
				$db->setQuery($update);
				$db->Query();
				
			}else{
				$deinsert='INSERT INTO #__jetour_appalldevices (`user_id`,`deviceaccess`,`devicetoken`) VALUES ("'.$userinfo->id.'","'.$post['deviceaccess'].'","'.$post['devicetoken'].'")';
				$db->setQuery($deinsert);
				$db->Query();
			
			}
			
			
			$db = JFactory::getDBO();
			$query = 'SELECT `id`, `username`, `password`' . ' FROM `#__users`' . ' WHERE username="' .$user . '" AND password="' . $passw.'" ';
			$db->setQuery( $query );
			$result = $db->loadObject();
			
			
			
			if($result) {
			  JPluginHelper::importPlugin('user');
			  
			  $options = array();
			  $options['action'] = 'core.login.site';
			  
			  $response->username = $result->username;
			  $result = $app->triggerEvent('onUserLogin', array((array)$response, $options));
			 }
			
			
			
			$sql="SELECT u.id,u.name,u.username,u.email,au.gender,au.dob FROM #__users as u LEFT JOIN #__jetour_appusers as au ON au.user_id=u.id WHERE u.username='".$user."' ";
			$db->setQuery($sql);
			$result1 = $db->LoadObject();
			if($result1){ 
			
			$sqlfav="SELECT COUNT(f.package_id) as totalfavorite FROM #__jetour_favoritepackage as f LEFT JOIN  #__jetour_package as p ON p.id=f.package_id WHERE f.user_id=".$result1->id." AND ( `start_date` <= DATE(NOW()) AND `end_date` >= DATE(NOW()) )";
			$db->setQuery($sqlfav);
			$totalfavorites = $db->LoadResult();
			
			
			 $profile = array();
			 $profile['userId']   = $result1->id;
			 $profile['name']   = $result1->name;
			 $profile['username']  = $result1->username;
			 $profile['email']  = $result1->email;
			 $profile['gender']  = $result1->gender;
			 $profile['dob']  = $result1->dob;
			 $profile['favoritecount']  =$totalfavorites;
	 		//$profile['notification_status']  = $result1->pushnotification;
			
							$arr = array('success' => 1, 'username' => $user, 'profile' => $profile);
							echo json_encode($arr);exit;
						
			}
			
			}else{
			
			/*$post['name']='Rahul Patel';
			$post["username"]='rahulpatel0305@gmail.com';
		
			$post["email"]='rahulpatel0305@gmail.com';
			//$post["dob"]='30-6-1990';
			//$post["phno"]='75589345325';
			//$post["gender"]='1';
			//$post["country"]='99';
			$post["devicetoken"]='APA91bFcP2ajjdqzVe6VxKx0hGmvz7ECQGVWu-YfhInH_Pfm48TfdsGPtcT4F0nsIxr_gvZj-ygd_re4dm_tiyefg8rj6X4eafJDTk5IjiuoiP5v-z54nbd6eAn45Ew7vsC8-JNw8gJk';
			$post["deviceaccess"]='1';*/
			
			if($post["email"]=="" || $post["email"]=="(null)") {
			$arr = array('success' => 0, 'message' => "Please Provide Your Username" );	
			echo json_encode($arr);exit;
			}
			
			
			$pass=explode('@',$post["email"]);
			$password=$pass[0];
			$password=md5($password);
			
	
						$mainframe = JFactory::getApplication();
						$user 		= clone(JFactory::getUser());
						//$pathway 	=$mainframe->getPathway();
						$config		=JFactory::getConfig();
						$authorize	=JFactory::getACL();
						$document   =JFactory::getDocument();					
						$usersConfig = JComponentHelper::getParams( 'com_users');
						$newUsertype = 'Registered';
						
						/*if ($newUsertype) 
						{
							$newUsertype = 'Registered';
						}*/
						if($post['name']==" " || $post['name']=="")
						$post['name'] = $pass[0];
					
						$user->set('id', 0);
						$user->set('name', $post['name']);
						$user->set('username', $post["username"]);
						$user->set('password', $password);
						$user->set('usertype', $newUsertype);
						$user->set('email', $post["email"]);
						/*if(@$post["dob"])
						$user->set('dob', $post["dob"]);
						if(@$post["gender"])
						$user->set('gender', $post["gender"]);*/
						
						
						$date =JFactory::getDate();
						$jdate = new JDate;
						$user->set('registerDate', $jdate->toSql());
			
					
						$user->set('block', '0');
					
						if (!$user->save())
						{
							
						}
						if($user->id!=739 && $user->id!=742){
		 				$delete = 'DELETE FROM #__user_usergroup_map WHERE user_id='.$user->id.' AND group_id=8';
						$db->setQuery($delete);
						$db->query();	
						}
						
					$sql = 'Select id from #__usergroups where title="Registered" OR title="Application user"';
					$db->setQuery($sql);
					$res = $db->LoadObjectList();
							
				for($i=0;$i<count($res);$i++)
				{			
					$sql_temp="insert into #__user_usergroup_map (user_id,group_id) values('".$user->id."','".$res[$i]->id."')";
					$db->setQuery($sql_temp);
					$db->Query();
				}	
					
					
						$insert_appuser='INSERT INTO #__jetour_appusers (`user_id`,`deviceaccess`,`dob`,`gender`,`pushnotification`,`favoritenotification`) VALUES ("'.$user->id.'","'.$post["deviceaccess"].'","'.@$post["dob"].'","'.@$post["gender"].'","1","1")';
						$db->setQuery($insert_appuser);
						$db->Query();
					 
					 
					 	$sql="SELECT id FROM #__jetour_appalldevices WHERE devicetoken ='".$post['devicetoken']."' AND deviceaccess=".$post['deviceaccess'] ;	
						$db->setQuery($sql);
						$devicefound = $db->loadResult();
						
						if($devicefound){
							$update='UPDATE #__jetour_appalldevices SET user_id="'.$user->id.'",deviceaccess="'.$post['deviceaccess'].'" WHERE  devicetoken="'.$post['devicetoken'].'"';
							$db->setQuery($update);
							$db->Query();
							
						}else{
							$deinsert='INSERT INTO #__jetour_appalldevices (`user_id`,`deviceaccess`,`devicetoken`) VALUES ("'.$user->id.'","'.$post['deviceaccess'].'","'.$post['devicetoken'].'")';
							$db->setQuery($deinsert);
							$db->Query();
						
						}
					 
						
						$sql="SELECT u.id,u.name,u.username,u.email,au.gender,au.dob FROM #__users as u LEFT JOIN #__jetour_appusers as au ON au.user_id=u.id WHERE u.id=".$user->id;
						//$sql="SELECT * FROM #__users WHERE id=".$user->id;
						$db->setQuery($sql);
						$userdata1 = $db->LoadObject();
						$profile = array();
						$profile['userId']   = $userdata1->id;
						$profile['name']   = $userdata1->name;
						$profile['username']  = $userdata1->username;
						$profile['email']  = $userdata1->email;
						$profile['gender']  =$userdata1->gender;
						$profile['dob']  =$userdata1->dob;
						$profile['favoritecount']  =0;
						
						//$profile['notification_status']  = $userdata1->pushnotification;
			
						if($userdata1)
						{
							$arr = array('success' => 1, 'username' => $userdata1->username, 'profile' => $profile);
							echo json_encode($arr);exit;
						}
				
						else
						{
				
							$arr = array('success' => 0, 'user' => 'Error in Registering User');
							echo json_encode($arr);exit;
						}
	
		}
	
	
	 
	
}