<?php  
    //include('../SecurityChecked/StringAuthenticationStrict.php');
	include_once('../config.php');
	
	
	

	
	/***************************************************************************************/ 
   /* gmail login */ 
	########## Google Settings.. Client ID, Client Secret #############
/**********/
   
	
	$google_client_id= '1092218374059-3dlqs5s0lgf2rt75qtjo50avea13kjee.apps.googleusercontent.com';
	$google_client_secret 	= 'ijuBDMml1vD4XPMD_ptYeT3j';
	//$google_redirect_url 	= 'https://'.$server_url.'/login/login-modals.php'; 
	$google_developer_key 	= '';   
 
 	//include google api files
	require_once 'src/Google_Client.php';
	require_once 'src/contrib/Google_Oauth2Service.php';

	//start session 

	$gClient = new Google_Client();
	$gClient->setApplicationName('Login to netbuttrfly.com');
	$gClient->setClientId($google_client_id);
	$gClient->setClientSecret($google_client_secret);
	$gClient->setRedirectUri($google_redirect_url);
	$gClient->setDeveloperKey($google_developer_key); 
	$google_oauthV2 = new Google_Oauth2Service($gClient);

	//If user wish to log out, we just unset Session variable
	if($_SESSION['social-media']!=2)
	{
    	if (isset($_REQUEST['reset'])) 
    	{
    	  unset($_SESSION['email_token']);
    	  $gClient->revokeToken();
    	  header('Location:'.filter_var($google_redirect_url, FILTER_SANITIZE_URL));
    	} 
    
    	//if (isset($_GET['code'])) 
    	if ( (isset($_GET['code'])) && (isset($_GET['scope'])) )
    	{
    		$gClient->authenticate($_GET['code']);
    		$_SESSION['email_token'] = $gClient->getAccessToken();
    		header('Location:'.filter_var($google_redirect_url, FILTER_SANITIZE_URL));
    		return;
    	}
    
    	if (isset($_SESSION['email_token'])) 
    	{ 
    		$gClient->setAccessToken($_SESSION['email_token']);
    	}   
	}
	
	if($_SESSION['social-media']!=2)
	{
    	if ($gClient->getAccessToken()) 
    	{    
    		  //Get user details if user is logged in
    		  $user 				= $google_oauthV2->userinfo->get();
    		  $user_id 				= $user['id'];
    		  $user_name 			= filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
    		  $email 		= filter_var($user['email'], FILTER_SANITIZE_EMAIL);
    		  $profile_url 			= filter_var($user['link'], FILTER_VALIDATE_URL);
    		  $profile_image_url 	= filter_var($user['picture'], FILTER_VALIDATE_URL);
    		  $personMarkup 		= "$email<div><img src='$profile_image_url?sz=50'></div>";
    		  $_SESSION['email_token'] 	= $gClient->getAccessToken();
    	}
    	else 
    	{
    		//get google login url
    		$authUrl = $gClient->createAuthUrl();
    	} 
	}
	
	/* gmail login end */
	
/**********************************************************/	 
	 if(isset($authUrl)){ } 
	 else if($_SESSION['social-media']!=2)// user logged in 
	 {
	    $_SESSION['social-media']=1;
		$stmt=$conn->prepare("select cust_id from users where email=:para1");
		$stmt->bindValue(':para1', $email, PDO::PARAM_STR);   
		$stmt->execute();   
		$affected_rows = $stmt->rowCount();   
		if($affected_rows > 0)	
		{
			$row = $stmt->fetch(PDO::FETCH_OBJ);  
			$cust_id=$row->cust_id;
			header("Location:".ROOTPATH."/login_logout.php?gmail_rand_no=$cust_id");
			die;;
		}
		else 
		{  
		    header("Location:".ROOTPATH."/custom_function/EmailConfigure.php?gmail_emailVal=$email&Emailname=$user_name");
			die;
		}			
	}
	 
	/****************************************************************/
	



/***************************************************************************************/ 
   /* facebook login start */  
	 
   // Include the autoloader provided in the SDK
    require_once 'facebook-php-sdk/autoload.php';
     
    // Include required libraries
    use Facebook\Facebook;
    use Facebook\Exceptions\FacebookResponseException;
    use Facebook\Exceptions\FacebookSDKException;
    
    
    $appId = '746422176215416';
    $appSecret = 'ffa23e85bdea5578dd84faf8730eff12';
    $redirectURL = 'https://'.$server_url.'/login/login-modals.php';
    $fbPermissions = array('email');  //Optional permissions
     
    $fb = new Facebook(array(
        'app_id' => $appId,
        'app_secret' => $appSecret,
        'default_graph_version' => 'v2.9',
            ));
     
    // Get redirect login helper
    $helper = $fb->getRedirectLoginHelper();
	
	if( ($_GET['error']=='access_denied') && ($_GET['error_code']='200') )
    {
    	header("Location: ".ROOTPATH."/");
    	die;
    }
	
    // Try to get access token
   // try {
	
        // Already login
        if (isset($_SESSION['facebook_access_token'])) {
            $accessToken = $_SESSION['facebook_access_token'];
        } else {
            $accessToken = $helper->getAccessToken();
        }
     
        if (isset($accessToken)) {
            if (isset($_SESSION['facebook_access_token'])) {
                $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
            } else {
                // Put short-lived access token in session
                $_SESSION['facebook_access_token'] = (string) $accessToken;
     
                // OAuth 2.0 client handler helps to manage access tokens
                $oAuth2Client = $fb->getOAuth2Client();
     
                // Exchanges a short-lived access token for a long-lived one
                $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
                $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
     
                // Set default access token to be used in script
                $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
                $_SESSION['social-media']=2;
            }
     
            // Redirect the user back to the same page if url has "code" parameter in query string
            //if (isset($_GET['code'])) 
            if ( (isset($_GET['code'])) && ($_SESSION['social-media']==2)) 
			{
                // Getting user facebook profile info
                try {
                    $profileRequest = $fb->get('/me?fields=id,name,first_name,last_name,email,link,gender,locale,picture');
                    $fbUserProfile = $profileRequest->getGraphNode()->asArray();
                    // Here you can redirect to your Home Page.
                    /*echo "<pre/>";
                    print_r($fbUserProfile);
    				
    				echo '<pre>';print_r($fbUserProfile['email']).'<br><br>Id:=>';
    				echo '<pre>';print_r($fbUserProfile['id']).'<br>';
    				die; 		*/	
				    $facebook_id=$fbUserProfile['id'];
    				$stmt=$conn->prepare("select * from  users where Fb_Id=:Fb_Id || email=:email");
    				$stmt->bindValue(':Fb_Id', $fbUserProfile['id'], PDO::PARAM_STR);   
    				$stmt->bindValue(':email', $fbUserProfile['email'], PDO::PARAM_STR);   
    				$stmt->execute();   
    				$affected_rows = $stmt->rowCount();
    				if($affected_rows > 0)	
    				{				
                        $row = $stmt->fetch(PDO::FETCH_OBJ);  
                        $cust_id=$row->cust_id;
					    header("Location:".ROOTPATH."/login_logout.php?facebook_rand_no=$cust_id&ID=$facebook_id");
					    die;
    				} 
					else 
				    {
				        if($fbUserProfile['email']!='')
				        {
    				        $name=$fbUserProfile['name'];
    						$facebook_email=$fbUserProfile['email'];
    				        header("Location:".ROOTPATH."/custom_function/EmailConfigure.php?facebook_emailVal=$facebook_email&Emailname=$name&ID=$facebook_id");
    						die;
				        }
				        else
				        {
				            unset($_SESSION['facebook_access_token']);
                    		unset($_SESSION['social-media']);
				            header("Location: ".ROOTPATH."/");
				            echo "Please try again with another account";
				            //echo '<script>alert("Please try again with another account")</script>';
				            die;
				        }
					}    				
                } catch (FacebookResponseException $e) {
                    echo 'Graph returned an error: ' . $e->getMessage();
					unset($_SESSION['facebook_access_token']);
					unset($_SESSION['social-media']);
                    // Redirect user back to app login page
                    header("Location: ".ROOTPATH."/");
                    exit;
                } catch (FacebookSDKException $e) {
                    echo 'Facebook SDK returned an error: ' . $e->getMessage();
                    unset($_SESSION['facebook_access_token']);
					unset($_SESSION['social-media']);
					header("Location: ".ROOTPATH."/");
                    exit;
                }
            }
        } 
		else {
            // Get login url     
            $loginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);
        }
    /*} catch (FacebookResponseException $e) {
        echo 'Graph returned an error: ' . $e->getMessage();		
		unset($_SESSION['facebook_access_token']);
        exit;
    } catch (FacebookSDKException $e) {
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }*/	 

  /* facebook login end */ 
/***************************************************************************************/
?>
<script src="<?php echo ROOTPATH;?>/view/js/tab/login.js"></script>
<script>  
$(document).ready(function()
{      
    $("#LoadingDiv").hide();   
    $('#login_content').show();  
    
    $(".Login_box").click( function()
	 {
		user=1;
		setCookie(user,30);
		url = URL+"/login/login-modals.php";
		$("#LoginModalLoad").load(url); 
		$("#login").modal({
			show: 'true',
			backdrop: 'static',
			keyboard:false
		});   		
		removeCookie(); 
	 });
	 
	 $(".Register_box").click( function()
	 {
		user=2;
		setCookie(user,30);
		url = URL+"/login/login-modals.php";
		$("#LoginModalLoad").load(url); 
		$("#login").modal({
			show: 'true',
			backdrop: 'static',
			keyboard:false
		});    
		removeCookie(); 
	 });
	 
	$("#forgot_password_modal").click( function()
	{
		user=3;
		setCookie(user,30);
		url = URL+"/login/login-modals.php";
		$("#LoginModalLoad").load(url); 
		$("#login").modal({
			show: 'true',
			backdrop: 'static',
			keyboard:false
		});    
		removeCookie(); 
	});
	
	if(site_custom_id!='')
	{
	    var userph="<?php echo $login_details->ph; ?>";
	    if(userph!='')
	    {
	        $('#login_id').attr('disabled', 'disabled');
	    }
	}
});    
</script> 

	    <p style="margin:115px;" id="LoadingDiv">Loading.....</p> 
		<span id="login_content">
		 <span class="logo-center"><img src="<?php echo ROOTPATH;?>/view/images/wt-logo-mob.png" alt="Netbuttrfly Images" style="padding: 27px 0px 27px 0px;"></span>
		<?php if($_COOKIE['loginCookies']==1){ ?>
		<span id="login_here_content" style="width:100%">
		<h2 id="login_here">Login Here</h2>
		<p class="logSubHead" id="loginhead">Enter your Mobile No to Login/Sign Up</p>
			<form class="login_form1" action="" method="post" id="loginform" autocomplete="off">
           
                <span id="login_msg" style="color:red;" class="otp-count"></span>
                <div class="floating-form">
                  <div class="floating-label" >      
                    <input class="floating-input loginInput" type="text" value="<?php if(isset($_COOKIE['site_custom_id'])) { if($login_details->ph!='') echo $login_details->ph; } ?> " placeholder=" " [(ngModel)] = 'line1' maxlength="80" name="login_id"  id="login_id" >
                    <label id="login_id_label">Mobile No</label>
                  </div>
                </div>
 
			<!--<input class="loginInput" type="text" placeholder="Mobile No / Email Address" name="login_id"  id="login_id" />-->
			<input type="button" class="loginButton" name="contineCheck"  value="Continue"  id="contineCheck" />	 
			<div class="clearfix"></div> 
		 
		    <div class="job-filter">
			<input class="checkBox " type="checkbox" name="login_terms" value="1" id="login_terms"/> 
            <span class="terms_condn otp-count" id="login_terms_condn" >I am agree with the <a href="<?php echo ROOTPATH;?>/UserServices/terms_use.php" target="_blank"   > <u>terms and conditions</u></a></span>
            </div>
			 
			<input class="loginButton" type="button" name="submit_login_otp"  value="Login with OTP"  id="submit_login_otp" /> 
			<input type="hidden" name="ConfirmReceiverLogin" value="1">
			<div class="floating-form">
               <div class="floating-label" >
			     <input class="floating-input loginInput" type="text" placeholder=" " [(ngModel)] = 'line1' name="entered_opt"  id="entered_opt"  />
			     <label id="entered_opt_label">Enter OTP</label>
			   </div>
            </div>	
			<span id="some_div" class="otp-count"></span>
           <a href="javascript:void(0);" id="resend_otp" class="otp-count">Resend OTP</a>
			<input type="button" class="loginButton" name="submit_otp"  value="Submit"  id="submit_otp" />	
			<!--<span id="login_msg" style="color:red;"></span>-->
        </form>
	  <p class="text-center otp-count" id="social_heading">
	<!--	<span></span>  -->
	 </p>
	  
	 
	  
	  <img class="hideImagesIn" src="<?php echo ROOTPATH;?>/view/images/login-img.png" alt="Netbuttrfly Images" style="width:200px;display:block; margin:auto; margin-top:15px;">
	  </span>
	  <?php } 
		else if($_COOKIE['loginCookies']==2)
		{
	   ?>    
		<span id="registration_content">
		    <span id="registerfrm">
		    <span id="regi"><h2>Register Here</h2></span>
		    <p class="logSubHead" id="registerhead">Enter your details to Sign Up on Netbutterfly</p>
    		 <form  method="post"  id="registrationform" autocomplete="off" >
			 <span id="registration_msg" style="color:red;"></span>
			 <div class="floating-form">
                  <div class="floating-label"> 
            		<input class="floating-input loginInput" type="text" placeholder=" " [(ngModel)] = 'line1' name="registered_name"  id="registered_name"  onchange="get_first_name(this.value,1);" />	
            		<label id="registered_name_label">Name</label>
            	  </div>
             </div>
             <div class="floating-form">
                  <div class="floating-label"> 
            		<input class="floating-input loginInput" type="text" placeholder=" " [(ngModel)] = 'line1' name="registered_mob"  id="registered_mob"  />
            		<label id="registered_mob_label">Mobile No</label>
            	  </div>
             </div>
             <div class="floating-form">
                  <div class="floating-label"> 
            		<input class="floating-input loginInput" type="text" placeholder=" " [(ngModel)] = 'line1' name="registered_email"  id="registered_email"  />
            		<label id="registered_email_label">Email</label>
            	  </div>
             </div>
			<div class="clearfix"></div>
		    <div class="eye-icon">
                <div class="floating-form">
                    <div class="floating-label" > 
                        <a href="javascript:void(0);" id="registered_pwd"><i id="show_regipwd" class="fa fa-eye" aria-hidden="true"></i></a>     
             
                    </div>
                </div>
            </div>
    	<!--	<span id="message">
    			<h5>Password must contain the following:</h5>
    			<span id="letter" class="invalid"><b>lowercase</b> letter</span>
    			<span id="capital" class="invalid"><b>uppercase</b> letter</span>
    			<span id="number" class="invalid"><b>number</b></span>
    			<span id="length" class="invalid">Minimum <b>6 characters</b></span>
    			<span id="special_character" class="invalid"><b>special character</b></span>
    		</span><br>-->
    		
    		<div class="job-filter">
    		<input class="checkBox" type="checkbox" name="reg_terms" value="1" id="reg_terms"/> <span class="iam" id="iam">I am agree with the <a href="<?php echo ROOTPATH;?>/UserServices/terms_use.php" target="_blank"   > <u>terms and conditions</u></a></span>
    		</div>
    		<input class="loginButton" type="submit"   name="submit_reg"  value="Create Account"  id="submit_reg" />
    		<div class="clearfix"></div>
			 <p class="text-center" id="log">
			  Already registered <a href="javascript:void(0);" class="Login_box" id="Login_box">Login Here</a>
			  </p>
			</span>
			<span id="registerfrm1">
			    <div class="floating-form">
            	  <div class="floating-label" >
    		         <input class="floating-input loginInput" type="text" placeholder=" " [(ngModel)] = 'line1' name="entered_OTP"  id="entered_OTP"  />
    		         <label id="entered_OTP_label">Enter OTP</label>
    		      </div>
    		    </div>   
    		<span id="reg_some_div"></span>
            <center><a href="javascript:void(0);" id="resend_reg_otp">Resend OTP</a></center><br>	
    		<input type="button" class="loginButton" name="submit_OTP"  value="Submit"  id="submit_OTP" />
			</span>
         </form>	
    	 
		</span>     
	 <?php }  else if($_COOKIE['loginCookies']==3) {?>
	    <span id="forgot_password_content" 
	     <h2 id="forgot_password_heading">Forgot Password</h2>
		 <form method="post" id="forgot_password_form" autocomplete="off">
		    <span id="forgot_password_msg" style="color:red;"></span>
		    <div class="floating-form">
                <div class="floating-label" > 
                  <input class="floating-input loginInput" type="text" placeholder=" " [(ngModel)] = 'line1' name="forgot_pass"  id="forgot_pass" />
			      <label>Enter Registered Email Address</label>
			    </div>
			</div>
			<input type="submit" class="loginButton" name="submit_forgot"  value="Submit"  id="submit_forgot" />			
         </form>
		 <p class="text-center otp-count" id="log">
    	  Already registered <a href="javascript:void(0);" class="Login_box" id="Login_box">Login Here</a>
    	  </p>
		   
	    </span>
	 <?php } ?>
	 </span>  
	 
	 
<!-- Modal -->
<!--<div class="modal fade" id="login" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog loginPop" role="document">
    <div class="modal-content loginBox" >
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
		<div class="loginLogo">
		<img src="<?php echo ROOTPATH;?>/view/images/wt-logo.png" alt="Netbuttrfly Images">
		</div>
		<div class="loginRight" id="LoginModalLoad">  
	        <p style="margin:115px;">Loading.....</p> 
	  </div>  
    </div>
  </div>
</div>-->
<!-- Latest compiled and minified CSS -->	 


<script>
/*
var myInput = document.getElementById("registered_password");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");
var special_character=document.getElementById("special_character");

document.getElementById("message").style.display = "none";

// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
  document.getElementById("message").style.display = "block";
}

// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
  document.getElementById("message").style.display = "none";
}

// When the user starts to type something inside the password field
myInput.onkeyup = function() {
			
	
  // Validate lowercase letters
  var lowerCaseLetters = /[a-z]/g;
  if(myInput.value.match(lowerCaseLetters)) {  
    letter.classList.remove("invalid");
    letter.classList.add("correct");
  } else {
    letter.classList.remove("correct");
    letter.classList.add("invalid");
  }
  
  // Validate capital letters
  var upperCaseLetters = /[A-Z]/g;
  if(myInput.value.match(upperCaseLetters)) {  
    capital.classList.remove("invalid");
    capital.classList.add("correct");
  } else {
    capital.classList.remove("correct");
    capital.classList.add("invalid");
  }

  // Validate numbers
  var numbers = /[0-9]/g;
  if(myInput.value.match(numbers)) {  
    number.classList.remove("invalid");
    number.classList.add("correct");
  } else {
    number.classList.remove("correct");
    number.classList.add("invalid");
  }
  
  // Validate length
  if(myInput.value.length >= 6) {
    length.classList.remove("invalid");
    length.classList.add("correct");
  } else {
    length.classList.remove("correct");
    length.classList.add("invalid");
  }
  
  // Validate special character
   var Spaecialcharacters = /[!@#\$%\^\&*]/g;
  if(myInput.value.match(Spaecialcharacters)) {  
    special_character.classList.remove("invalid");
    special_character.classList.add("correct");
  } else {
    special_character.classList.remove("correct");
    special_character.classList.add("invalid");
  }
} 
*/
</script>
