<?php
/*Unsubscribe form shortcode*/

//shortcode
add_shortcode( 'unsubscribe-sendy-form', 'return_sendy_unsubscribe_form' );

function return_sendy_unsubscribe_form( $attr ) {

	$form_html='';

	if ( !empty( $attr['id'] ) ) {
		$ids=explode( ',', $attr['id'] );

		$form_html.='<form class="unsubscribe-sendy-form">

		<input type="text" class="unsubscribe-email" name="unsubscribe-email" id="unsubscribe-email">
		<input type="submit" value="Unsubscribe"/>';
		foreach ( $ids as $key => $list_id ) {
			$form_html.='<input type="hidden" name="list[]" value="'.$list_id.'"/>';
		}

		$form_html.='<div class="unsub_sendy_error" style="display:none;color:red"></div>
		<div class="unsub_sendy_success" style="display:none;color:green"></div>';
		$form_html.='</form> ';

		$form_html.="<script type='text/javascript'>

		jQuery(function(){

			jQuery('body').on('submit','.unsubscribe-sendy-form',function(){

				var formFields= jQuery(this).serialize();

				var emailId=document.getElementById('unsubscribe-email').value;

				var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;

				valid= String(emailId).search (filter) != -1;

				if(!valid){

					alert('Please enter a valid email address');
					return false;
				}


				jQuery.ajax({
					type:'post',
					url:'".admin_url( "admin-ajax.php" )."',
					data:{action:'delete_sendy_user',formdata:formFields}
				}).done(function(result){
					if ( result ==  1 ) {
						jQuery('.unsub_sendy_error').slideUp();
						jQuery('.unsub_sendy_success').text( 'You are unsubscribed now.' ).slideDown();
					} else {
						jQuery('.unsub_sendy_success').slideUp();
						if ( result == 'Already subscribed.' ) {
							jQuery('.unsub_sendy_error').text( 'That address is already in use.' ).slideDown();
						} else {
							jQuery('.unsub_sendy_error').text( result ).slideDown();
						}
					}
				}).fail(function(){
					console.log('Failed');
				})
return false;

})
})

</script>";



	}else {

		$form_html.= '<div style="color:red" >Please select a list from plugin backened</div>';
	}
	return $form_html;

}


