<?php
    global $wpdb;

    if ( isset($_GET["action"]) and $_GET["action"] == "unlink" and isset($_GET["fbid"]) ) {

        $fbid = array_shift(get_user_meta(get_current_user_id(), 'facebook_uid'));

        if ( $fbid != $_GET["fbid"] ) {

            die;
        }

        $fbtoken = array_shift(get_user_meta(get_current_user_id(), 'facebook_token'));

        delete_user_meta(get_current_user_id(), 'facebook_uid', $fbid);
        delete_user_meta(get_current_user_id(), 'facebook_token', $fbtoken);

        wp_redirect($_SERVER["HTTP_REFERER"]);
        die;
    }

    if( isset($_GET["action"]) and $_GET["action"] == "finish") {

        /***
         * El usuario ha pulsado en vincular su cuenta oauth-krone y ha pulsado en el enlace del correo
         * para finalizar el proceso
         */

         //Delete current user from wp_users
         $q = sprintf("select user_id as ID from %s WHERE meta_key = 'tmp_facebook_uid' and meta_value = %d", $wpdb->usermeta, $_GET["fbid"]);
         $userObj = $wpdb->get_row($q);

         if($userObj === false or is_null($userObj)) {

             Throw new Exception("target user not found");
         }

         $user_obj = get_userdata($userObj->ID);

         delete_user_meta($user_obj->ID, "tmp_facebook_uid");
         update_user_meta($user_obj->ID, "facebook_uid", $_GET["fbid"] );

         $fbtoken = get_user_meta($user_obj->ID, "tmp_facebook_token", true);
         if ($fbtoken) {

             delete_user_meta($user_obj->ID, "tmp_facebook_token");
             update_user_meta($user_obj->ID, "facebook_token", $fbtoken );
         }

         wp_set_auth_cookie($user_obj->ID, true, false);
         wp_set_current_user($user_obj->ID);

         wp_redirect(home_url());
         die;
    }

    if(!isset($_GET["fbid"]) or !is_numeric($_GET["fbid"])) {

        Throw new Exception("Error");
    }

    $q = sprintf("select user_id from %s WHERE meta_key = 'tmp_facebook_uid' and meta_value = %d", $wpdb->usermeta, $_GET["fbid"]);
    $fId = $wpdb->get_row($q);

    if (! isset($fId->user_id)) {

        $q = sprintf("select user_id from %s WHERE meta_key = 'facebook_uid' and meta_value = %d", $wpdb->usermeta, $_GET["fbid"]);
        $fId = $wpdb->get_row($q);

        if(! isset($fId->user_id)) {
            Throw new Exception("User not found");
        }
    }

    $fId = $fId->user_id;

    if (is_null($fId)) {

        Throw new Exception("User not found");
    }

    $user_obj = get_userdata($fId);

    if (isset($user_obj->user_email) and $user_obj->user_email != "") {

        $user_obj->user_email = preg_replace("/^[0-9]*\|/","",$user_obj->user_email);
    }

    //fetch ajax requests (Validations)
    if ( (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest") or isset($_GET["vincular"]) ) {

        $response = array();

        if ( isset($_GET["signup_displayname"])) {

            $userId = username_exists($_GET["signup_displayname"]);

            if(is_numeric($userId) and $_GET["signup_displayname"] != $user_obj->user_login) {

                $response = array(
                    "isValid" => false,
                    "text" => "Este nombre de usuario ya esta en uso",
                );

            } else {

                if ( validate_username($_GET["signup_displayname"]) ) {

                    $userNameAndPasswd['passwd'] = $password = preg_replace("/[^0-9a-zA-Z]/", "", wp_generate_password());
                    $userNameAndPasswd['username'] = $_GET["signup_displayname"];

                    $data = array(
                        'ID' => $user_obj->ID,
                        'user_login' => $_GET["signup_displayname"],
                        'user_nicename' => $_GET["signup_displayname"],
                        'user_pass' => $password
                    );

                    wp_update_user($data);
                    $q = sprintf( "UPDATE %s SET user_login='%s' WHERE ID=%d", $wpdb->users, $_GET["signup_displayname"], $user_obj->ID );
                    $wpdb->query($q);

                    $response = array(
                        "isValid" => true,
                        "text" => "Nombre de usuario guardado correctamente"
                    );
                    
                    delete_user_meta($user_obj->ID, "tmp_facebook_uid");
                    update_user_meta($user_obj->ID, "facebook_uid", $_GET["fbid"]);
                    
                    $token = get_user_meta($user_obj->ID, "tmp_facebook_token", true);
                    delete_user_meta($user_obj->ID, "tmp_facebook_token");
                    update_user_meta($user_obj->ID, "facebook_token", $token);

                    iron_signup_mail_message($user_obj->ID, '', '', $userNameAndPasswd);

                } else {

                    $response = array(
                        "isValid" => false,
                        "text" => "El nombre de usuario facilitado no es valido"
                    );
                }
            }

        } else if ( isset($_GET["signup_email"])) {

            if (!is_email($_GET["signup_email"])) {

                $response = array(
                    "isValid" => false,
                    "vinculable" => false,
                    "done" => false,
                    "text" => "El email facilitado no es correcto",
                    "email" => $_GET["signup_email"]
                );

            } else {

                $userId = email_exists($_GET["signup_email"]);
                if (is_numeric($userId) and $userId != $user_obj->ID) {
                    
                    $vincularUserData = get_userdata($userId);
                    if (!isset($vincularUserData->user_status) or $vincularUserData->user_status == 2) {
                        
                        $response = array(
                            "isValid" => false,
                            "vinculable" => false,
                            "done" => false,
                            "text" => "Ya existe un usuario registrado con este email, pero aún no ha sido validado. Revise su correo antes de continuar.",
                        );
                        
                    } else {

                        $response = array(
                            "isValid" => false,
                            "vinculable" => true,
                            "done" => false,
                            "text" => "",
                        );
                    }

                } else {

                    $data = array(
                        'ID' => $user_obj->ID,
                        'user_email' => $_GET["signup_email"]
                    );

                    wp_update_user($data);

                    /*wp_set_auth_cookie($user_obj->ID, true, false);
                    wp_set_current_user($user_obj->ID);*/

                    $response = array(
                        "isValid" => true,
                        "vinculable" => false,
                        "done" => true,
                        "text" => "Email guardado correctamente"
                    );
                }
            }

        } else if ( isset($_GET["vincular"]) ) {

            //validar email:
            if (!is_email($_GET["vincular"])) {

                Throw new Exception("Invalid email");
            }

            /*** Cargamos el usuario objetivo ***/
            $target_user_obj = get_user_by_email($_GET["vincular"]);

            /*** Eliminar usuario actual (ya no es necesario) ***/
            $q = sprintf("DELETE FROM %s WHERE ID=%d", $wpdb->users, $user_obj->ID );
            $wpdb->query($q);

            //Delete user metadata from wp_usermeta
            $q = sprintf("DELETE FROM %s WHERE user_id=%d", $wpdb->usermeta, $user_obj->ID );
            $wpdb->query($q);

            //Add facebook_uid key to the target user
            update_user_meta($target_user_obj->ID, "tmp_facebook_uid", $user_obj->tmp_facebook_uid);
            update_user_meta($target_user_obj->ID, "tmp_facebook_token", $user_obj->tmp_facebook_token );

            $to = $_GET["vincular"];
            $subject = "Kronet: vincular facebook a su cuenta";
            $message = "Hemos recibido una solucitud para vincular su cuenta de facebook con su perfil de usuario de Kronet.
            Para ejecutar esta acción pulse <a href='".home_url()."/oauth?fbid=".$_GET["fbid"]."&vincular=true&action=finish'>aquí</a>. <br /><br /> Si usted no ha solicitado esta acción o ya no desea realizarla,
            simplemente ignore este correo.";

            iron_signup_mail_message($target_user_obj->ID, $subject, $message);
            $response["text"] = "done!";

        } else if (isset($_GET["fetchAvatar"])) {

            update_user_meta($user_obj->ID, "avatar", $_GET["avatar"] );
            $response = $_GET;
        }

        echo json_encode($response);
        die;
    }

?>