$mainframe = JFactory::getApplication();
$option = JRequest::getVar('option','com_webservice','','string');
$post = JRequest::get ('post');  
$uri =& JURI::getInstance();
$url= $uri->root();
$options = array();
$options['remember'] = 'false';
$options['return'] = '';
$post["isSocial"] = 'YES';
$isSocial = $post["isSocial"];
$post['socialId']=0;
$post["email"]="ravi@gmail.com";
/*$post['dob']="1990/06/30";
$post['phno']="84949484";
$post['gender']=1;*/
//$post['devicetoken']='5356a2a1c4079b05036b2a354441218dba8382bfb91518159da1afb4cbeadb91';

if($isSocial=='NO'){

//$post["username"] = 'paresh';
//$post["password"] = '123456';
//$post['email']='paresh@harmistechnology.com';
$username = $post["username"] ;
$password  =$post["password"];

$update='UPDATE #__users SET devicetoken="'.$post['devicetoken'].'",deviceaccess="'.$post['deviceaccess'].'" WHERE  username="'.$username.'"';
$db->setQuery($update);
$db->query();


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.*,c.country_id FROM #__users AS u  LEFT JOIN #__naderapp_country AS c ON u.country=c.country_id  WHERE u.username='".$credentials["username"]."' ";
$db->setQuery($sql);
$result1 = $db->LoadObject();

/*$update="UPDATE #__users SET devicetoken='".$post['devicetoken']."' WHERE username='".$credentials["username"]."'";
$db->setQuery($update);
$db->query();*/

if($result1){ 
$error = $mainframe->login($credentials,$options);

$profile = array();
 $profile['userId']   = $result1->id;
 $profile['name']   = $result1->name;
 $profile['username']  = $credentials["username"];
 $profile['email']  = $result1->email;
 $profile['gender']  = $result1->gender;
 
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($socialId==0)
{
   $email    =  $post["email"];
		$db = JFactory::getDbo();
		$app = JFactory::getApplication();
		$sql="SELECT * FROM #__users WHERE email='".$email."'";
		$db->setQuery($sql);
		$userinfo= $db->LoadObject();

if($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();
		
		$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 * FROM #__users WHERE username='".$user."' ";
		$db->setQuery($sql);
		$result1 = $db->LoadObject();
		if($result1){ 
		
		$profile = array();
		 $profile['userId']   = $result1->id;
		 $profile['name']   = $result1->name;
		 $profile['username']  = $user;
		 $profile['email']  = $email;
           $profile['gender']  = $result1->gender; ;
		
						$arr = array('success' => 1, 'username' => $user, 'profile' => $profile);
						echo json_encode($arr);exit;
					
		}
		
		}else{
		
		$post['name']='ravi';
		$post["username"]='ravi';
		$pass='123456';
		$post["email"]='ravi@gmail.com';
		$post["dob"]='30-6-1990';
		/*$post["phno"]='75589345325';
		$post["gender"]='1';
		$post["country"]='99';
		$post["devicetoken"]='84ijd9449';
		$post["deviceaccess"]='1';*/
		
		$pass=explode('@',$post["email"]);
		$pass=$pass[0];
		

$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 = $usersConfig->get('new_usertype');
					
					if ($newUsertype) 
					{
						$newUsertype = 'Registered';
					}
				
					$user->set('id', 0);
					$user->set('name', $post["name"]);
					$user->set('username', $post["username"]);
					$user->set('password', $pass);
					$user->set('usertype', $newUsertype);
					$user->set('email', $post["email"]);
				    $user->set('dob', $post["dob"]);
					


					//$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
				
					$date =JFactory::getDate();
					$jdate = new JDate;
					$user->set('registerDate', $jdate->toSql());
		
					// If user activation is turned on, we need to set the activation information
					 $useractivation = $usersConfig->get( 'useractivation' );
					
				//	$useractivation = 0;
					if ($useractivation == '1')
					{
						jimport('joomla.user.helper');
						$user->set('activation', JApplication::getHash( JUserHelper::genRandomPassword()) );
						$user->set('block', '1');
					}
					
					$sql = 'Select id from #__usergroups where title="Registered"'; 
					$db->setQuery($sql);
					$res = $db->LoadObject();
				
				
					
			
	
				//	$user->set('groups', $res->id);
					// If there was an error with registration, set the message and display form
						
					if (!$user->save())
					{
						$_SESSION['name']=$post['name'];
						$_SESSION['email']=$post['email'];
						$_SESSION['creator']=$post['creator'];
						$_SESSION['firstname']=$post['firstname'];
						$_SESSION['title']=$post['title'];
						//$this->setRedirect ( 'index.php?option=' . $option . '&view=register');
						//return false;
					}
	
						
				$sql_temp="insert into #__user_usergroup_map(user_id,group_id) values('".$user->id."','".$res->id."')";
			     $db->setQuery($sql_temp);
     			$db->Query();
 				
				$delete = 'DELETE FROM #__user_usergroup_map WHERE user_id='.$user->id.' AND group_id=8';
				$db->setQuery($delete);
				$db->query();
						
					$sql = 'Select id from #__users where email="'.$user->email.'" '; 
					$db->setQuery($sql);
					$userdetail = $db->LoadObject();
					
					$user->set('id', $userdetail->id);
					$post["uid"]=$userdetail->id;

 $insert='INSERT INTO #__naderapp_userfield (`Country`,`uid`,`gender`,`phno`,`dob`) VALUES ("'.$post["country"].'","'.$userdetail->id.'","'.$post["gender"].'","'.$post["phno"].'","'.$post["dob"].'")';
$db->setQuery($insert);
$db->query();

		$sql="SELECT * FROM #__users WHERE id=".$userdetail->id;
		$db->setQuery($sql);
		$userdata = $db->LoadObject();
		$profile = array();
 		$profile['userId']   = $userdata->id;
		$profile['name']   = $userdata->name;
		$profile['username']  = $userdata->username;
 		$profile['email']  = $userdata->email;
		
		if($userdata)
		{
			$arr = array('success' => 1, 'username' => $userdata->username, 'profile' => $profile);
			echo json_encode($arr);exit;
		}

		else
		{
			$arr = array('success' => 0, 'user' => 'Error in Registering User');
			echo json_encode($arr);exit;
		}

    }


}



}