<?php
    global $wpdb;
    require_once(dirname(__FILE__)."/../../../../plugins/irontec-kronet-connect/utilities.php");
    $blowfish = new Blowfish();

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

        $q = sprintf("delete from %s WHERE meta_key = 'asoc".$_GET["kc"]."' and user_id = %d", $wpdb->usermeta, get_current_user_id());

        delete_user_meta(get_current_user_id(), 'asoc'.$_GET["kc"], get_user_meta(get_current_user_id(), 'asoc'.$_GET["kc"], true));

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

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

        /***
         * El usuario ha pulsado en vincular su cuenta oauth-kronet 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_asoc".$_GET["kc"]."' and meta_value = %d", $wpdb->usermeta, $_GET["kcu"]);
         $userObj = $wpdb->get_row($q);

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

             Throw new Exception("Usuario no encontrado");
         }

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

         delete_user_meta($user_obj->ID, "tmp_asoc".$_GET["kc"]);
         update_user_meta($user_obj->ID, "asoc".$_GET["kc"], $_GET["kcu"] );

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

         wp_redirect(home_url());
         die;
    }

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

        Throw new Exception("Enlace no válido");
    }

    /***
     * Load user info
     */

    $id = $_GET["kc"];

    $cookie = base64_decode($_COOKIE["kc".$_GET["kc"]]);

    global $wpdb;
    $query = "Select * from `".$wpdb->prefix."kconnect_satellites` where id = '".$_GET["kc"]."'";
    $site = array_shift($wpdb->get_results($query));

    if (!isset($site->Key)) {

        Throw new Exception("Web remota no válida");
    }

    $blowfish->key = $site->Key;

    list($uid, $hash) = explode("_", $blowfish->decrypt($cookie), 2);

    $q = sprintf("select user_id from %s WHERE meta_key = 'asoc".$_GET["kc"]."' and meta_value = %d", $wpdb->usermeta, $uid);

    $fId = $wpdb->get_row($q);

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

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

        $tmp = get_userdata($fId->user_id);

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

            if (is_numeric($uid)) { //

                $postdata = http_build_query(
                    array(
                        'hash' => base64_encode($blowfish->encrypt($hash)),
                        'uid' => base64_encode($blowfish->encrypt($uid))
                    )
                );

                $opts = array('http' =>
                    array(
                        'method'  => 'POST',
                        'header'  => 'Content-type: application/x-www-form-urlencoded',
                        'content' => $postdata
                    )
                );

                $context  = stream_context_create($opts);

                $domain = trim($site->domain."wp-content/plugins/kronet-connect/fetch.php");
                $response = trim(file_get_contents($domain, false, $context));

                if ("ok_" == substr($response,0,3)) {

                    $response = $blowfish->decrypt(base64_decode(substr($response, 3)));
                    $user = unserialize($response);

                    if (!isset($user->ID)) {

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

                $origUserName = $user->user_login;

                while (username_exists($user->user_login)) {

                    $user->user_login = $origUserName.rand(1,99);
                }

                $user_data = array();
                $user_data['user_login']    = $user->user_login;
                $user_data['user_pass']     = wp_generate_password();
                $user_data['user_nicename'] = $user->user_nicename;
                $user_data['first_name']    = $user->first_name;
                $user_data['last_name']     = $user->last_name;
                $user_data['display_name']  = $user->display_name;
                $user_data['user_url']      = $user->user_url;
                $user_data['user_email']    = time()."|".$user->user_email;

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

                $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) )
                {
                    //var_dump($user_login_id);
                    Throw new Exception("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>.");
                }

                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, "asoc".$_GET["kc"], $user->ID);
                update_user_meta($user_login_id, "avatar", $user->avatar);
                //update_user_meta($user_login_id, "first_name", $user->first_name);
                //update_user_meta($user_login_id, "last_name", $user->last_name);

                $fId = new stdClass();
                $fId->user_id = $user_login_id;
            }
        }

    } else {

        $tmp = get_userdata($fId->user_id);
        if (isset($tmp->user_status) and $tmp->user_status == "0") {

            $cKey = "kc".$_GET["kc"];
            setcookie($cKey, $_COOKIE[$cKey], (time() + (24*3600*365)) );
            wp_set_auth_cookie($fId->user_id, true, false);
            ?>
            <script type="text/javascript">
                parent.jQuery.fancybox.close();
            </script>
            <?php
            die;
        }
    }

    if (is_null($fId)) {

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

    $fId = $fId->user_id;
    $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"],
                        'display_name' => $_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"
                    );

                    /*$uid = get_user_meta($user_obj->ID, "tmp_asoc".$_GET["kc"], true);

                    delete_user_meta($user_obj->ID, "tmp_asoc".$_GET["kc"], $uid);
                    update_user_meta($user_obj->ID, "asoc".$_GET["kc"], $uid);*/

                    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"]
                    );

                    if (empty($user_obj->ID)) {

                    	$response = array(
	                        "isValid" => false,
	                        "vinculable" => false,
	                        "done" => false,
	                        "text" => "Se produjo un error de comunicaci&oacute;n con la asociaci&oacute;n"
	                    );

                    } else {

                        //TODO :: ¿¿¿Mostrar email en uso???

	                    wp_update_user($data);

	                    $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"]);

            //Add key to the target user

            $uid = get_user_meta($user_obj->ID, "asoc".$_GET["kc"], true);

            delete_user_meta($target_user_obj->ID, "asoc".$_GET["kc"], $uid);
            update_user_meta($target_user_obj->ID, "tmp_asoc".$_GET["kc"], $uid);

            //update_user_meta($target_user_obj->ID, "tmp_asoc".$_GET["kc"], $uid);

            $to = $_GET["vincular"];
            $subject = "kronikoensarea: vincular facebook a su cuenta";
            $message = "Hemos recibido una solucitud para vincular su cuenta de facebook con su perfil de usuario de kronikoensarea.
            Para ejecutar esta acción pulse <a href='".home_url()."/oauth?kc=".$_GET["kc"]."&kcu=".$uid."&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!";

            /*** 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);

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

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

        }  else if (isset ($_GET['first_name']) && isset($_GET['last_name']) ) {

        	// Actualizar Nombre y apellidos
        	update_user_meta($user_obj->ID, "first_name", $_GET["first_name"] );
        	update_user_meta($user_obj->ID, "last_name", $_GET["last_name"] );

        	// Enviar respuesta
        	$response = array(
                "isValid" => true,
                "text" => "Nombre y apellidos guardados correctamente"
            );
        }

        echo json_encode($response);
        die;
    }

?>