<?php

add_action( 'bp_signup_profile_fields', 'sendy_add_buddypress_registration_fields' );
add_action( 'bp_core_signup_user', 'sendy_buddypress_add_user_meta', 10, 5 );
add_action( 'bp_core_activated_user', 'sendy_add_bp_registered_user_to_list' );

function sendy_add_buddypress_registration_fields() {

	//Get and set any values already sent
	$sendy_signup = ( isset( $_POST['sendy_buddypress_signup'] ) ) ? 'checked="checked"' : '';

	$sendy_on_register=get_option( 'sendy_buddypress_check' );
	$translated = get_option( 'sendy_translation_settings' );

	if ( $sendy_on_register =='on' ) {
		$sendy_register_page_lists=get_option( 'sendy_buddypress_lists' );
		$sendy_lists=get_option( 'sendy_lists' );

		if ( !empty( $sendy_register_page_lists ) ) {

			foreach ( $sendy_register_page_lists as $key => $value ) {

				if ( array_key_exists( $value, $sendy_lists ) ) {

?>
					<input type="hidden" name="listids[]" value="<?php echo $value; ?>" >
					<?php
				}

			}

?>
			<p>
				<input type="checkbox" name="sendy_buddypress_signup" id="sendy_buddypress_signup" class="checkbox" <?php echo $sendy_signup; ?> />
				<?php echo $translated['sigup_text']; ?>
			</p>

			<?php

		}
	}
}






function sendy_buddypress_add_user_meta( $user_id, $user_login, $user_password, $user_email, $usermeta ) {
	if ( isset( $_POST['sendy_buddypress_signup'] ) ) {
		update_user_meta( $user_id, 'subscribe_to_sendy', '1' );
	}
}

function sendy_add_bp_registered_user_to_list( $signup ) {

	$sendy_register_page_lists=get_option( 'sendy_buddypress_lists' );
	$sendy_lists=get_option( 'sendy_lists' );

	if ( !empty( $sendy_register_page_lists ) ) {

		foreach ( $sendy_register_page_lists as $key => $value ) {

			if ( array_key_exists( $value, $sendy_lists ) ) {

				$listid[]=$value;
			}
		}
	}

	$user_info = get_userdata( $signup );
	$subscribe = get_user_meta( $user_info->ID, 'subscribe_to_sendy', true );

	if ( $subscribe == '1' ) {
		add_user_to_sendy( $user_info->user_nicename, $user_info->user_email, $listid );
	}
}
