<?php
require('../../../wp-blog-header.php');

/**** API KEYS *****/
define( 'IRON_FBCONNECT_APPID' , get_option("fbc_api_id") );
define( 'IRON_FBCONNECT_APIKEY' , get_option("fbc_api_key") );
define( 'IRON_FBCONNECT_SECRET' , get_option("fbc_api_sec" ));

$uri = home_url()."/wp-content/plugins/irontec-fb-connect/fetch_response.php";

if(count($_GET) == 0) {

    $url = "https://www.facebook.com/dialog/oauth?client_id=".IRON_FBCONNECT_APPID."&redirect_uri=".$uri."&scope=offline_access";
    wp_redirect($url);

} else if(isset($_GET["code"]) and $_GET["code"] != "") {

    $url = "https://graph.facebook.com/oauth/access_token?client_id=".IRON_FBCONNECT_APPID."&redirect_uri=".$uri."&client_secret=".IRON_FBCONNECT_SECRET."&code=".$_GET["code"];
    $token = @file_get_contents($url);

    if ($token) {

        $token = str_replace("access_token=", "", $token);
        $graph_url = "https://graph.facebook.com/me?access_token=" . $token;
        $user = json_decode(file_get_contents($graph_url));

        if (isset($user->id)) {

            global $wpdb;
            $sql = "select user_id from wp_usermeta where meta_key = 'facebook_uid' and meta_value = '".$user->id."' limit 1";

            $userID = $wpdb->get_var($sql);

            if (is_null($userID)) {

                $sql = "select user_id from wp_usermeta where meta_key = 'tmp_facebook_uid' and meta_value = '".$user->id."' limit 1";
                $userID = $wpdb->get_var($sql);

                if (is_null($userID)) {

                    //create a new user
                    $baseUsername = $username = $user->name;

                    while (is_numeric(username_exists(str_replace(" ",".", $username)))) {

                        $username = $baseUsername." ".rand(1, 99);
                    }

                    $user_data = array();
                    $user_data['user_login']    = str_replace(" ",".", $username);
                    $user_data['user_pass']     = wp_generate_password();
                    $user_data['user_nicename'] = str_replace(" ","-", $user->name);
                    $user_data['first_name']    = $user->first_name;
                    $user_data['last_name']     = $user->last_name;
                    $user_data['display_name']  = $user->first_name;
                    $user_data['user_url']      = $user->link;
                    $user_data['user_email']    = is_numeric(email_exists($user->email)) ? time()."|".$user->email : $user->email;

                    $usermeta = array(
                        "profile_field_ids" => "25,15,10,4", //ids del perfil
                        "field_25" => "ES", //país
                        "field_15" => "Con mis amigos", //privacidad
                        "field_10" => "transgresores", //categoría
                        "field_4" => "Otra patología"
                    );

                    $user_login_id = bp_core_signup_user( $user_data['user_login'], $user_data['user_pass'], $user_data['user_email'], $usermeta );

                    if( is_wp_error($user_login_id) )
                    {

                        $jfb_log .= "WP: Error creating user: " . $user_login_id->get_error_message() . "\n";
                        j_die("Error: wp_insert_user failed!<br/><br/>If you get this error while running a Wordpress MultiSite installation, it means you'll need to purchase the <a href=\"$jfb_homepage#premium\">premium version</a> of this plugin to enable full MultiSite support.<br/><br/>If you're <u><i>not</i></u> using MultiSite, please report this bug to the plugin author on the support page <a href=\"$jfb_homepage#feedback\">here</a>.");

                    } else {

                        update_user_meta($user_login_id, 'activation_key', wp_hash( $user_login_id ) );
                        update_user_meta($user_login_id, 'bp_profile_privacy', 'a:4:{i:0;s:57:"s:49:"a:5:{i:0;s:0:"";i:2;i:0;i:3;i:0;i:4;i:0;i:5;i:0;}";";i:4;i:2;i:3;i:0;i:25;i:0;}');
                        update_user_meta($user_login_id, "tmp_facebook_uid", $user->id);
                        update_user_meta($user_login_id, "tmp_facebook_token", $token);

                        update_user_meta($user_login_id, "last_name", $user_data['first_name']);
                        update_user_meta($user_login_id, "first_name", $user_data['last_name']);

                        wp_redirect(home_url()."?fbid=".$user->id);
                    }

                } else if( isset($user->id) ) {
                    
                    wp_redirect(home_url()."?fbid=".$user->id);

                } else {

                    wp_redirect(home_url());
                }

            } else {

                $userData = get_userdata($userID);

                if ($userData->user_status == "2") {

                    $msg = __('Cuenta no activada','login-with-ajax');
                    wp_redirect(home_url()."?LoginError=".urlencode($msg));
                    die;
                }

                if (is_numeric(get_user_meta($userID, 'facebook_uid', true))) {

                    if (! get_user_meta($userID, 'facebook_token', true)) {

                        update_user_meta($userID, "facebook_token", $token);
                    }

                } else {

                    update_user_meta($userID, "tmp_facebook_uid", $user->id);
                    update_user_meta($userID, "tmp_facebook_token", $token);
                }

                
                /*if (isset($userData->avatar)) {

                    $avatar = base64_decode($userData->avatar);
        
                    $classDir = dirname(__FILE__)."/../../themes/cvp-irontec/members/single/profile/fetchAvatar.php";
                    require_once($classDir);
        
                    $newAvatar = new fetchAvatar();
                    $newAvatar->setUserId($userID);
                    $newAvatar->setAvatarSrc($avatar);
        
                    if ($newAvatar->fetch()) {
        
                        delete_user_meta($userID, "avatar" );
                    }
                }*/

                wp_set_auth_cookie($userID, true, false);
                wp_redirect(home_url());
            }
        }
    }
}
