<?php


function register_sendy_widget_pro() {

	register_widget( 'Sendy_Widget_PRO' );

}

add_action( 'widgets_init', 'register_sendy_widget_pro' );

class Sendy_Widget_PRO extends WP_Widget {


	public function __construct() {
		parent::__construct(
			'sendy_widget_pro', // Base ID
			'Sendy Widget (Deprecated)', // Name
			array( 'description' => __( 'A simple Widget to integrate Sendy', 'sendywidget' ), ) // Args
		);
	}

	/**
	 * Front-end display of widget.
	 *
	 * @see WP_Widget::widget()
	 *
	 * @param array   $args     Widget arguments.
	 * @param array   $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {
		extract( $args );
		$title = apply_filters( 'widget_title', $instance['title'] );

		echo $before_widget;
		if ( ! empty( $title ) )
			echo $before_title . $title . $after_title;

		$translated = get_option( 'sendy_translation_settings' );
		$redirect_url = get_option( 'sendy_redirect_url' );

?>

			<script type="text/javascript">


				jQuery(function(){

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

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

						var emailId=document.getElementById('subscriber-email').value;
						var redirect_url = "<?php echo $redirect_url; ?>";

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

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

						if(!valid){

							alert("<?php echo $translated['email_error'] ?>");
							return false;
						}

						$terms=jQuery( '#sendy_terms' )
						if($terms.length>0){
							if(! $terms.prop( 'checked' )){

								alert('Please accept terms & conditions');
								return false;
							}}

							jQuery.ajax({
								type:'post',
								url:'<?php echo admin_url( "admin-ajax.php" ); ?>',
								data:{action:'add_sendy_user',formdata:formFields}
							}).done(function(result){
								if ( result ==  1 ) {
									jQuery('.sendy_error').slideUp();
									jQuery('.sendy_success').text( "<?php echo $translated['success_message'] ?>" ).slideDown();
									if(redirect_url !=''){
										window.location.href = redirect_url;
									}
								} else {
									jQuery('.sendy_success').slideUp();
									if ( result == 'Already subscribed.' ) {
										jQuery('.sendy_error').text( "<?php echo $translated['already_subscribed'] ?>" ).slideDown();
										document.getElementById('siimage').src = '<?php echo SENDY_WIDGET_PRO_URL; ?>/inc/captcha/securimage_show.php?sid=' + Math.random();
										jQuery('#captcha_widget_code').val('');
									}else if(result == 'captcha_error'){

										jQuery('.sendy_error').text( "<?php echo $translated['captcha_error'] ?>"  ).slideDown();
									}
									else {
										jQuery('.sendy_error').text( result ).slideDown();
										document.getElementById('siimage').src = '<?php echo SENDY_WIDGET_PRO_URL; ?>/inc/captcha/securimage_show.php?sid=' + Math.random();
										jQuery('#captcha_widget_code').val('');
									}

								}
							}).fail(function(){
								console.log('Failed');
							})
							return false;
						})
})

</script>



<form  class="subscribe-form" action="<?php echo get_option( 'sendy_url' ); ?>/subscribe" method="POST" accept-charset="utf-8">
	<?php if ( $instance['hidename']!='on' ) { ?>
	<div class="name-cont sendy-form-row"><label for="name"><?php echo $translated['name'] ?></label>
		<input type="text" name="name" id="subscriber-name"/></div>

		<?php } ?>

		<div class="name-cont sendy-form-row"><label for="email"><?php echo $translated['email'] ?></label>
			<input type="text" name="email" id="subscriber-email"/></div>
			<div class="sendy-form-row">

				<?php

		$sendy_url=get_option( 'sendy_url' );
		$sendy_api_key=get_option( 'sendy_api_key' );
		$sendy_lists=get_option( 'sendy_lists' );
		$count=0;
		if ( $sendy_lists ) {
			$url=$sendy_url.'/api/subscribers/active-subscriber-count.php';

		}


		if ( $sendy_lists && !empty( $instance['listids'] ) ) {

			foreach ( $instance['listids'] as $key => $list_id ) {

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

					$response= wp_remote_post( $url, array( 'body'=>array( 'api_key'=>$sendy_api_key, 'list_id'=>$list_id ) ) );

					if ( is_wp_error( $response ) ) {

						$error_message = $response->get_error_message();

						$count=0;

					} else {

						$count+=$response['body'];
					}

					$list_field = apply_filters( 'swp_list_field_type', '<input type="hidden" class="list" name="list[]" value="'.$list_id.'"/>', $list_id, $sendy_lists );

					echo $list_field;
				}

			}

		}else {

			echo '<div style="color:red">Error: Please select a list from widget</div>';

		}

		if ( $instance['count']!='on' ) { ?>
					<div class="sendy-subscriber-count">
						<?php echo $count.' '.$translated['subscriber_counter']; ?>
					</div>
					<?php } ?>
				</div>



				<?php if ( $instance['sendy_captcha']=='on' ) { ?>
				<div class="sendy-form-row">

					<img id="siimage" class="captcha-image"  src="<?php echo SENDY_WIDGET_PRO_URL.'/inc/captcha/securimage_show.php?sid='.md5( uniqid() ); ?>" alt="CAPTCHA Image" >

					<div>
					 Code:  <input type="text" id="captcha_widget_code" class="captcha-input" name="captcha_code" size="10" maxlength="6" />


						<a tabindex="-1" href="#" title="Refresh Image" onclick="document.getElementById('siimage').src = '<?php echo SENDY_WIDGET_PRO_URL; ?>/inc/captcha/securimage_show.php?sid=' + Math.random(); this.blur(); return false">

							<img class="img-captcha-ref" style="vertical-align:middle" src="<?php echo SENDY_WIDGET_PRO_URL; ?>/inc/captcha/images/refresh.png" alt="Reload Image" onclick="this.blur()"  border="0"></a>
						</div>
					</div>
					<?php }

		$terms_link = get_option( 'sendy_terms_link' );

		if ( $instance['sendy_terms']== 'on' && $terms_link ) { ?>
						<div class="sendy_terms sendy-form-row">
							<input type="checkbox" id="sendy_terms" > <a target="_blank" href="<?php echo $terms_link; ?>"><?php echo $translated['terms_text'] ?></a>
						</div>
						<?php } ?>

						<div class="sendy_error" style="display:none;color:red"></div>
						<div class="sendy_success" style="display:none;color:green"></div>
						<input type="submit" name="sub-submit" value="<?php echo $translated['subscribe_button'] ?>"  class="sendy-submit-btn"/>
						<div class="resp"></div>
					</form>

					<?php echo $after_widget;

	}

	/**
	 * Sanitize widget form values as they are saved.
	 *
	 * @see WP_Widget::update()
	 *
	 * @param array   $new_instance Values just sent to be saved.
	 * @param array   $old_instance Previously saved values from database.
	 *
	 * @return array Updated safe values to be saved.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['sendyurl'] = strip_tags( $new_instance['sendyurl'] );
		$instance['listids'] = $new_instance['listids'];
		$instance['hidename'] = strip_tags( $new_instance['hidename'] );
		$instance['count'] = strip_tags( $new_instance['count'] );
		$instance['sendy_captcha'] = strip_tags( $new_instance['sendy_captcha'] );
		$instance['sendy_terms'] = strip_tags( $new_instance['sendy_terms'] );


		return $instance;
	}

	/**
	 * Back-end widget form.
	 *
	 * @see WP_Widget::form()
	 *
	 * @param array   $instance Previously saved values from database.
	 */
	public function form( $instance ) {
		if ( isset( $instance[ 'title' ] ) ) {
			$title = $instance[ 'title' ];
		}
		else {
			$title = __( ' ', 'sendywidget' );
		}
		if ( ! isset( $instance[ 'count' ] ) ) {
			$instance[ 'count' ] ='';
		}
		if ( ! isset( $instance[ 'hidename' ] ) ) {
			$instance[ 'hidename' ] ='';
		}
		if ( ! isset( $instance[ 'sendy_captcha' ] ) ) {
			$instance[ 'sendy_captcha' ] ='';
		}
		if ( ! isset( $instance[ 'sendy_terms' ] ) ) {
			$instance[ 'sendy_terms' ] ='';
		}
		if ( ! isset( $instance[ 'listids' ] ) ) {
			$instance[ 'listids' ] ='';
		}

?>
		<p>
			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Heading:', 'sendywidget' ); ?></label>
			<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
		</p>

		<p>
			<input class="checkbox" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" type="checkbox"  <?php echo ( $instance[ 'count' ]=='on' )?'checked="checked"':'' ; ?>  />
			<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Hide Subscriber Count?', 'sendywidget' ); ?></label><br/>
			<input class="checkbox" id="<?php echo $this->get_field_id( 'hidename' ); ?>" name="<?php echo $this->get_field_name( 'hidename' ); ?>" type="checkbox"  <?php echo ( $instance[ 'hidename' ]=='on' )?'checked="checked"':'' ; ?>  />
			<label for="<?php echo $this->get_field_id( 'hidename' ); ?>"><?php _e( 'Hide Name?', 'sendywidget' ); ?></label><br/>

			<input class="checkbox" id="<?php echo $this->get_field_id( 'sendy_captcha' ); ?>" name="<?php echo $this->get_field_name( 'sendy_captcha' ); ?>" type="checkbox"  <?php echo ( $instance[ 'sendy_captcha' ]=='on' )?'checked="checked"':'' ; ?>  />
			<label for="<?php echo $this->get_field_id( 'sendy_captcha' ); ?>"><?php _e( 'Show Captcha?', 'sendywidget' ); ?></label><br/>
			<input class="checkbox" id="<?php echo $this->get_field_id( 'sendy_terms' ); ?>" name="<?php echo $this->get_field_name( 'sendy_terms' ); ?>" type="checkbox"  <?php echo ( $instance[ 'sendy_terms' ]=='on' )?'checked="checked"':'' ; ?>  />
			<label for="<?php echo $this->get_field_id( 'sendy_terms' ); ?>"><?php _e( 'Show terms & conditions checkbox?', 'sendywidget' ); ?></label>

		</p>

		<p>

			<label for="<?php echo $this->get_field_id( 'listids' ); ?>"><?php _e( 'Select Lists:', 'sendywidget' ); ?></label>
			<br/>
			<?php
		$checked_lists=$instance['listids'];
		$sendy_lists=get_option( 'sendy_lists' );
		if ( $sendy_lists ) {

			foreach ( $sendy_lists as $list_id => $list_name ) {

?>
					<input id="<?php echo $this->get_field_id( '$list_id' ); ?>" <?php if ( is_array( $checked_lists ) ) { echo  in_array( $list_id, $checked_lists )?'checked' : ''; } ?> type="checkbox" name="<?php echo $this->get_field_name( 'listids' ); ?>[]" value="<?php echo $list_id; ?>"> <label><?php  echo $list_name; ?></label>
					<br/>
					<?php

			}
		}


?>

		</p>
		<?php

	}

} // class Sendy_Widget
