<?php

class Leap_Mailchimp_Widget extends WP_Widget {

	function __construct() {
		$widget_ops = array( 'description' => __( 'Use this widget to add a mailchimp newsletter to your site.', 'wiz' ) );
		parent::__construct( 'leap_mailchimp', __( 'LEAP: Mailchimp Newsletter', 'wiz' ), $widget_ops );
	}

	/**
	 * https://apidocs.mailchimp.com/api/2.0/lists/list.php
	 * @param type $apikey
	 */
	function mailchimp_lists_list( $apikey = '' ) {
		$dc				 = explode( "-", $apikey );
		$url			 = 'https://' . $dc[ '1' ] . '.api.mailchimp.com/2.0/lists/list.json';
		$query_args		 = array(
			'apikey' => $apikey
		);
		$lists_query	 = esc_url_raw( add_query_arg( $query_args, $url ) );
		$lists_response	 = wp_safe_remote_get( $lists_query, array( 'sslverify' => false, 'timeout' => 15 ) );

		$lists = array();

		if ( 200 == wp_remote_retrieve_response_code( $lists_response ) ) {
			if ( $response_body = wp_remote_retrieve_body( $lists_response ) ) {
				$response_data = json_decode( trim( $response_body ), true );

				if ( is_array( $response_data ) && isset( $response_data[ 'data' ] ) ) {
					$response_lists = $response_data[ 'data' ];

					foreach ( $response_lists as $list ) {
						$lists[] = array(
							'id'	 => $list[ 'id' ],
							'name'	 => $list[ 'name' ]
						);
					}
				}
			}
		} else {
			$response_body		 = wp_remote_retrieve_body( $lists_response );
			$response_data		 = json_decode( trim( $response_body ), true );
			$lists[ 'error' ]	 = $response_data[ 'error' ];
		}

		return $lists;
	}

	/**
	 * https://apidocs.mailchimp.com/api/2.0/lists/subscribe.php
	 * @param type $apikey
	 * @param type $id
	 * @param type $email
	 */
	function mailchimp_lists_subscribe( $apikey = '', $list_id = '', $email = '' ) {
		$dc				 = explode( "-", $apikey );
		$url			 = 'https://' . $dc[ '1' ] . '.api.mailchimp.com/2.0//lists/subscribe.json';
		$query_args		 = array(
			'apikey'		 => $apikey,
			'id'			 => $list_id,
			'email'			 => array(
				'email' => $email
			),
			'send_welcome'	 => true
		);
		$lists_query	 = esc_url_raw( add_query_arg( $query_args, $url ) );
		$lists_response	 = wp_safe_remote_get( $lists_query, array( 'sslverify' => false, 'timeout' => 15 ) );

		$response_data = array();

		if ( 200 == wp_remote_retrieve_response_code( $lists_response ) ) {
			if ( $response_body = wp_remote_retrieve_body( $lists_response ) ) {
				$response_data = json_decode( trim( $response_body ), true );
			}
		} else {
			$response_body	 = wp_remote_retrieve_body( $lists_response );
			$response_data	 = json_decode( trim( $response_body ), true );
		}

		return $response_data;
	}

	function widget( $args, $instance ) {
		extract( $args );

		$defaults	 = array(
			'title'					 => 'Login Form',
			'mailchimp_api_key'		 => '',
			'mailchimp_before_text'	 => '',
			'mailchimp_after_text'	 => '',
			'mailchimp_list'		 => '',
		);
		$instance	 = wp_parse_args( (array) $instance, $defaults );

		$title					 = apply_filters( 'widget_title', $instance[ 'title' ], $instance, $this->id_base );
		$mailchimp_api_key		 = apply_filters( 'leap_mailchimp_api_key', $instance[ 'mailchimp_api_key' ], $instance, $this->id_base );
		$list_id				 = apply_filters( 'leap_mailchimp_list', $instance[ 'mailchimp_list' ], $instance, $this->id_base );
		$mailchimp_before_text	 = apply_filters( 'leap_mailchimp_before_text', $instance[ 'mailchimp_before_text' ], $instance, $this->id_base );
		$mailchimp_after_text	 = apply_filters( 'leap_mailchimp_after_text', $instance[ 'mailchimp_after_text' ], $instance, $this->id_base );

		if ( isset( $_POST[ 'leap_mc_email' ] ) ) {

			$_POST[ 'leap_mc_email' ] = strip_tags( $_POST[ 'leap_mc_email' ] );

			if ( !empty( $mailchimp_api_key ) ) {

				$data = $this->mailchimp_lists_subscribe( $mailchimp_api_key, $list_id, $_POST[ 'leap_mc_email' ] );
				if ( !empty( $data ) && empty( $data[ 'error' ] ) ) {
					// It worked!   
					$msg = '<p style="color:green;">' . __( 'Success!&nbsp; Check your inbox or spam folder for a message containing a confirmation link.', 'wiz' ) . '</p>';
				} else {
					// An error ocurred, return error message   
					if ( !empty( $data[ 'error' ] ) ) {
						$msg = '<p style="color:red;"><b>' . __( 'Error', 'wiz' ) . '</b>:&nbsp; ' . $data[ 'error' ] . '</p>';
					}
				}
			}
		}



		echo $args[ 'before_widget' ];

		echo '<div class="newsletter-signup">';

		if ( !empty( $title ) )
			echo $args[ 'before_title' ] . $title . $args[ 'after_title' ];


		if ( !empty( $msg ) ) {
			echo $msg;
		}


		// GET INTRO TEXT
		if ( !empty( $mailchimp_before_text ) ) {
			echo '<p>' . $mailchimp_before_text . '</p>';
		}
		echo '		<form method="post" class="newsletter_subscribe" data-url="' . home_url() . '" name="newsletter_form">';
		echo '<div class="form-group">';
		echo '			<input type="email" autocomplete="off" required name="leap_mc_email" class="form-control nl-email" value="" placeholder="' . __( "email@example.com", 'wiz' ) . '" />';
		echo '</div>';
		echo '			<input type="hidden" name="zn_list_class" class="nl-lid" value="' . $instance[ 'mailchimp_list' ] . '" />';
		echo '			<input type="submit" name="submit" class="pull-right nl-submit btn btn-leap" value="' . __( "Join Now", 'wiz' ) . '" />';
		echo '		</form>';


		// GET INTRO TEXT
		if ( !empty( $mailchimp_after_text ) ) {
			echo '<p>' . $mailchimp_after_text . '</p>';
		}

		echo '	</div><!-- end newsletter-signup -->';
		echo $args[ 'after_widget' ];
	}

	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;

		$instance[ 'title' ]				 = sanitize_text_field( $new_instance[ 'title' ] );
		$instance[ 'mailchimp_api_key' ]	 = sanitize_text_field( $new_instance[ 'mailchimp_api_key' ] );
		$instance[ 'mailchimp_before_text' ] = wp_filter_nohtml_kses( $new_instance[ 'mailchimp_before_text' ] );
		$instance[ 'mailchimp_after_text' ]	 = wp_filter_nohtml_kses( $new_instance[ 'mailchimp_after_text' ] );
		$instance[ 'mailchimp_list' ]		 = sanitize_text_field( $new_instance[ 'mailchimp_list' ] );
		return $instance;
	}

	function form( $instance ) {

		$defaults	 = array(
			'title'					 => 'Login Form',
			'mailchimp_api_key'		 => '',
			'mailchimp_before_text'	 => '',
			'mailchimp_after_text'	 => '',
			'mailchimp_list'		 => '',
		);
		$instance	 = wp_parse_args( (array) $instance, $defaults );

		$title					 = isset( $instance[ 'title' ] ) ? $instance[ 'title' ] : '';
		$mailchimp_api_key		 = isset( $instance[ 'mailchimp_api_key' ] ) ? $instance[ 'mailchimp_api_key' ] : '';
		$mailchimp_before_text	 = isset( $instance[ 'mailchimp_before_text' ] ) ? $instance[ 'mailchimp_before_text' ] : '';
		$mailchimp_after_text	 = isset( $instance[ 'mailchimp_after_text' ] ) ? $instance[ 'mailchimp_after_text' ] : '';
		$mailchimp_list			 = isset( $instance[ 'mailchimp_list' ] ) ? $instance[ 'mailchimp_list' ] : '';


		if ( empty( $mailchimp_api_key ) ) {
			echo __( 'Please enter your MailChimp API KEY prior of using this widget.', 'wiz' );
		}


		if ( !empty( $mailchimp_api_key ) ) {
			$lists = $this->mailchimp_lists_list( $mailchimp_api_key );
		}
		?>
		<p>
			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'wiz' ) ?></label>
			<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $title; ?>" />
		</p>

		<p>
			<label for="<?php echo $this->get_field_id( 'mailchimp_api_key' ); ?>"><?php _e( 'Mailchimp API Key:', 'wiz' ) ?></label>
			<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'mailchimp_api_key' ); ?>" name="<?php echo $this->get_field_name( 'mailchimp_api_key' ); ?>" value="<?php echo $mailchimp_api_key; ?>" />
		</p>

		<?php if ( isset( $mailchimp_api_key ) && !empty( $mailchimp_api_key ) ) { ?>

			<?php if ( empty( $lists[ 'error' ] ) ) { ?>
				<p>
					<label for="<?php echo $this->get_field_id( 'mailchimp_list' ); ?>"><?php _e( 'Select List:', 'wiz' ); ?></label>
					<select id="<?php echo $this->get_field_id( 'mailchimp_list' ); ?>" name="<?php echo $this->get_field_name( 'mailchimp_list' ); ?>">

						<?php
						foreach ( $lists as $list ) {
							$selected = (isset( $mailchimp_list ) && $mailchimp_list == $list[ 'id' ]) ? ' selected="selected" ' : '';
							?>	
							<option <?php echo $selected; ?>value="<?php echo $list[ 'id' ]; ?>"><?php echo $list[ 'name' ]; ?></option>
							<?php
						}
						?>
					</select>
				</p>
				<?php
			} else {
				echo '<p style="color: red;">' . $lists[ 'error' ] . '</p>';
			}
			?>

		<?php } else { ?>
			<p style="color: red;">Please enter your Mailchimp API Key first so we can fetch your lists.</p>
		<?php } ?>

		<p>
		<div><label for="<?php echo $this->get_field_id( 'mailchimp_before_text' ); ?>"><?php echo __( 'Intro Text', 'wiz' ); ?></label></div>
		<div><textarea id="<?php echo $this->get_field_id( 'mailchimp_before_text' ); ?>" name="<?php echo $this->get_field_name( 'mailchimp_before_text' ); ?>" cols="35" rows="5"><?php echo $mailchimp_before_text; ?></textarea></div>
		</p>
		<p>
		<div><label for="<?php echo $this->get_field_id( 'mailchimp_after_text' ); ?>"><?php echo __( 'After Form Text', 'wiz' ); ?></label></div>
		<div><textarea id="<?php echo $this->get_field_id( 'mailchimp_after_text' ); ?>" name="<?php echo $this->get_field_name( 'mailchimp_after_text' ); ?>" cols="35" rows="5"><?php echo $mailchimp_after_text; ?></textarea></div>
		</p>

		<?php
	}

}

function leap_mailchimp_widget() {
	register_widget( 'Leap_Mailchimp_Widget' );
}

add_action( 'widgets_init', 'leap_mailchimp_widget' );
