<?php

/**
 * Check if WooCommerce is active
 * */
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
	add_action( 'woocommerce_review_order_before_submit', 'add_sendy_checkbox_to_checkout', 99 );
	add_action( 'woocommerce_checkout_order_processed', 'sendy_woocommerce_subscribe_user', 10, 2 );
}


function add_sendy_checkbox_to_checkout() {
	$translated = get_option( 'sendy_translation_settings' );
	$sendy_woo_checkout_check = get_option( 'sendy_woo_checkout_check' );

	if($sendy_woo_checkout_check =='on'){
?>
	<div class="form-row woosendy">
		<input type="checkbox" class="input-checkbox" name="woosendy_susbscribe" id="woosendy_susbscribe" value="1" >
		<span class="wooms_label"><?php echo stripslashes( $translated['woo_checkout_message'] ); ?></span>
	</div>
	<?php
}
}



/**
 *  Subscribe Woocommerce User to Sendy
 */
function sendy_woocommerce_subscribe_user( $order_id, $posted ) {

	if ( !empty( $_POST['woosendy_susbscribe'] )  && $_POST['woosendy_susbscribe'] == '1' ) {

		try{

			$email = $posted['billing_email'];
			$name=$posted['billing_first_name'].' '.$posted['billing_last_name'];

			$sendy_woo_checkout_page_lists=get_option( 'sendy_woo_checkout_page_lists' );
			$sendy_lists=get_option( 'sendy_lists' );

			$list=array();

			if ( !empty( $sendy_woo_checkout_page_lists ) ) {

				foreach ( $sendy_woo_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 );
				}
			}


		} catch ( Exception $e ) {}
	}
}
