<?php
add_action( 'register_form', 'sendy_add_registration_fields' );
add_action( 'user_register', 'sendy_add_registered_user_to_list' );

function sendy_add_registration_fields() {

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

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

	if ( $sendy_on_register !='disable' ) {
		$sendy_register_page_lists=get_option( 'sendy_register_page_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
				}

			}
			if ( $sendy_on_register == 'on' ) {
?>
			<p>

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

			<?php
			}
		}
	}
}

function sendy_add_registered_user_to_list( $user_id ) {
	$first_name='';
	$sendy_on_register=get_option( 'sendy_on_register' );
	$user_info = get_userdata( $user_id );
	if( !empty($user_info->first_name)){
		$first_name=$user_info->first_name.' '.$user_info->last_name;
	} else {
		$first_name= $user_info->user_login;
	}
	$user_email=$user_info->user_email;
	$sendy_lists=get_option( 'sendy_lists' );

	if ( isset( $_POST['sendy_signup'] )   ) {
		add_user_to_sendy( $first_name, $user_email, $_POST['listids'] );
	}else if ( $sendy_on_register == 'direct' ) {
			$sendy_register_page_lists=get_option( 'sendy_register_page_lists' );
			if ( !empty( $sendy_register_page_lists ) ) {
				add_user_to_sendy( $first_name, $user_email, $sendy_register_page_lists );

			}

		}
}
