<?php

add_action( 'edd_purchase_form_before_submit', 'add_sendy_newsletter_checkbox_edd_checkout', 99 );


function add_sendy_newsletter_checkbox_edd_checkout() {
	$translated = get_option( 'sendy_translation_settings' );
?>
	<div class="form-row ">
		<input type="checkbox" class="input-checkbox" name="sendy_susbscribe" id="sendy_susbscribe" value="1" >
		<span class="_label"><?php echo stripslashes( $translated['woo_checkout_message'] ); ?></span>
	</div>
	<?php
}

/**
 * Add the user to the list on edd
 *
 * @author Aman Saini
 * @since  1.0
 * @param [type]  $post
 * @param [type]  $user_info
 * @param [type]  $valid_data
 * @return  void
 */
function sendy_edd_subscribe_user( $post, $user_info, $valid_data ) {

	if ( !empty( $post['sendy_susbscribe'] )  && $post['sendy_susbscribe'] == '1' ) {
		$email = $user_info['email'];
		$name = $user_info['first_name'].' '.$user_info['last_name'];
		$sendy_edd_checkout_page_lists=get_option( 'sendy_edd_checkout_page_lists' );
		$sendy_lists=get_option( 'sendy_lists' );

		$list=array();

		if ( !empty( $sendy_edd_checkout_page_lists ) ) {

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

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

					$list[]=$value;
				}
			}
			if ( !empty( $list ) ) {
				add_user_to_sendy( $name, $email, $list );
			}
		}
	}

}
add_action( 'edd_checkout_before_gateway', 'sendy_edd_subscribe_user', 10, 3 );