<?php


function wpestate_core_add_to_footer(){
    $ga =esc_html(get_option('wp_estate_google_analytics_code', ''));
    if ($ga != '') { ?>

    <script>
        //<![CDATA[
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

      ga('create', '<?php echo esc_html($ga); ?>', '<?php     echo esc_html($_SERVER['SERVER_NAME']); ?>');
      ga('send', 'pageview');
    //]]>
    </script>


    <?php } 
}



////////////////////////////////////////////////////////////////////////////////
/// Ajax  Google login form
////////////////////////////////////////////////////////////////////////////////
add_action( 'wp_ajax_nopriv_wpestate_ajax_facebook_login', 'wpestate_ajax_facebook_login' );  
add_action( 'wp_ajax_wpestate_ajax_facebook_login', 'wpestate_ajax_facebook_login' );  

  
if( !function_exists('wpestate_ajax_facebook_login') ):
    function wpestate_ajax_facebook_login(){ 
        check_ajax_referer( 'wpestate_login_register_nonce', 'security' );
        session_start();
        $facebook_api               =   esc_html ( get_option('wp_estate_facebook_api','') );
        $facebook_secret            =   esc_html ( get_option('wp_estate_facebook_secret','') );

        $fb = new Facebook\Facebook([
            'app_id'                => $facebook_api,
            'app_secret'            => $facebook_secret,
            'default_graph_version' => 'v2.12',
        ]);

        $helper         = $fb->getRedirectLoginHelper();
        $permissions    = ['email']; // optional
      
        print    $loginUrl = $helper->getLoginUrl(wpestate_get_template_link('user_dashboard_profile.php'), $permissions);
        die();
    }
   
endif; // end   wpestate_ajax_facebook_login 


////////////////////////////////////////////////////////////////////////////////
/// Facebook  Login
////////////////////////////////////////////////////////////////////////////////
if( !function_exists('estate_facebook_login') ):

function estate_facebook_login($get_vars){
    $facebook_api               =   esc_html ( get_option('wp_estate_facebook_api','') );
    $facebook_secret            =   esc_html ( get_option('wp_estate_facebook_secret','') );
 
    $fb = new Facebook\Facebook([
            'app_id'  => $facebook_api,
            'app_secret' => $facebook_secret,
            'default_graph_version' => 'v2.12',
        ]);
    $helper = $fb->getRedirectLoginHelper();
        

    $secret      =   $facebook_secret;
    try {
        $accessToken = $helper->getAccessToken();
    } catch(Facebook\Exceptions\FacebookResponseException $e) {
         // When Graph returns an error
        print 'Graph returned an error: ' . $e->getMessage();
    exit;
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
        // When validation fails or other local issues
        print 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }
    
    
    // Logged in
    // var_dump($accessToken->getValue());

    // The OAuth 2.0 client handler helps us manage access tokens
    $oAuth2Client = $fb->getOAuth2Client();

    // Get the access token metadata from /debug_token
    $tokenMetadata = $oAuth2Client->debugToken($accessToken);
    //print '<h3>Metadata</h3>';
    //var_dump($tokenMetadata);

    // Validation (these will throw FacebookSDKException's when they fail)
    $tokenMetadata->validateAppId($facebook_api); 
    
    // If you know the user ID this access token belongs to, you can validate it here
    //$tokenMetadata->validateUserId('123');
    $tokenMetadata->validateExpiration();

    if (! $accessToken->isLongLived()) {
        // Exchanges a short-lived access token for a long-lived one
        try {
          $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
          print "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
          exit;
        }

    // print '<h3>Long-lived</h3>';
    //  var_dump($accessToken->getValue());
    }

    $_SESSION['fb_access_token'] = (string) $accessToken;
    
    try {
        // Returns a `Facebook\FacebookResponse` object
        $response = $fb->get('/me?fields=id,email,name,first_name,last_name', $accessToken);
    } catch(Facebook\Exceptions\FacebookResponseException $e) {
        print 'Graph returned an error: ' . $e->getMessage();
        exit;
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
        print 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }

    $user = $response->getGraphUser();
  
    
    if(isset($user['name'])){
        $full_name=$user['name'];
    }
    if(isset($user['email'])){
        $email=$user['email'];
    }
    $identity_code=$secret.$user['id'];  
    wpestate_register_user_via_google($email,$full_name,$identity_code,$user['first_name'],$user['last_name']); 
    
    
   
    $existing_user=get_user_by('email',$email);
    wp_set_password( $identity_code, $existing_user->ID );
    
    $info                   = array();
    $info['user_login']     = $full_name;
    $info['user_password']  = $identity_code;
    $info['remember']       = true;

    $user_signon            = wp_signon( $info, true );
        
        
    if ( is_wp_error($user_signon) ){ 
        wp_redirect( esc_url(home_url('/') ) ); exit(); 
    }else{
        wpestate_update_old_users($user_signon->ID);
        wp_redirect( wpestate_get_template_link('user_dashboard_profile.php') );
        exit();
    }

}

endif; // end   estate_facebook_login 



  
////////////////////////////////////////////////////////////////////////////////
/// Ajax  Google login form OAUTH
////////////////////////////////////////////////////////////////////////////////
  add_action( 'wp_ajax_nopriv_wpestate_ajax_google_login_oauth', 'wpestate_ajax_google_login_oauth' );  
  add_action( 'wp_ajax_wpestate_ajax_google_login_oauth', 'wpestate_ajax_google_login_oauth' );  

  
if( !function_exists('wpestate_ajax_google_login_oauth') ):
  
    function wpestate_ajax_google_login_oauth(){  
        check_ajax_referer( 'wpestate_login_register_nonce', 'security' );
        set_include_path( get_include_path() . PATH_SEPARATOR . get_template_directory().'/libs/resources');
        $google_client_id       =   esc_html ( get_option('wp_estate_google_oauth_api','') );
        $google_client_secret   =   esc_html ( get_option('wp_estate_google_oauth_client_secret','') );
        $google_redirect_url    =   wpestate_get_dashboard_profile_link();
        $google_developer_key   =   esc_html ( get_option('wp_estate_google_api_key','') );
        
         
        $gClient = new Google_Client();
        $gClient->setApplicationName('Login to WpEstate');
        $gClient->setClientId($google_client_id);
        $gClient->setClientSecret($google_client_secret);
        $gClient->setRedirectUri($google_redirect_url);
        $gClient->setDeveloperKey($google_developer_key);
        $gClient->setScopes(array('email', 'profile') );
        $google_oauthV2 = new Google_Oauth2Service($gClient);
        print $authUrl = ($gClient->createAuthUrl());
        die();
    }
  
endif; // end   wpestate_ajax_google_login 

  


////////////////////////////////////////////////////////////////////////////////
/// estate_google_oauth_login  Login
////////////////////////////////////////////////////////////////////////////////
if( !function_exists('estate_google_oauth_login') ):

function estate_google_oauth_login($get_vars){
    $allowed_html   =   array();
    
    $google_client_id       =   esc_html ( get_option('wp_estate_google_oauth_api','') );
    $google_client_secret   =   esc_html ( get_option('wp_estate_google_oauth_client_secret','') );
    $google_redirect_url    =   wpestate_get_dashboard_profile_link();
    $google_developer_key   =   esc_html ( get_option('wp_estate_google_api_key','') );

    $gClient = new Google_Client();
    $gClient->setApplicationName('Login to WpResidence');
    $gClient->setClientId($google_client_id);
    $gClient->setClientSecret($google_client_secret);
    $gClient->setRedirectUri($google_redirect_url);
    $gClient->setDeveloperKey($google_developer_key);
    $gClient->setScopes(array('email', 'profile') );
    $google_oauthV2 = new Google_Oauth2Service($gClient);
    
    if (isset($_GET['code'])) { 
        $code= esc_html( wp_kses($_GET['code'],$allowed_html ) );
        $gClient->authenticate($code);
    }
    
    
    
    if ($gClient->getAccessToken()) 
    {     
        $allowed_html       =   array();
        $dashboard_url      =   wpestate_get_template_link('user_dashboard_profile.php');
        $user               =   $google_oauthV2->userinfo->get();
        $user_id            =   $user['id'];
        $full_name          =   wp_kses($user['name'], $allowed_html);
        $email              =   wp_kses($user['email'], $allowed_html);
        $full_name          =   str_replace(' ','.',$full_name);  
        
        
        
        wpestate_register_user_via_google($email,$full_name,$user_id); 
        
        $wordpress_user_id  =   username_exists($full_name);
        wp_set_password( $code, $wordpress_user_id ) ;
        
        $info                   = array();
        $info['user_login']     = $full_name;
        $info['user_password']  = $code;
        $info['remember']       = true;
        $user_signon            = wp_signon( $info, true );
        
 
        
        if ( is_wp_error($user_signon) ){ 
            wp_redirect( esc_url( home_url('/') ) );  exit;
        }else{
            wpestate_update_old_users($user_signon->ID);
            wp_redirect($dashboard_url);exit;
        }
    }
    
    
    
}

endif; // end   estate_google_oauth_login 

?>