<?php


function register_sendy_widget_pro_widget() {

	register_widget( 'SendyWidgetPRO' );

}

add_action( 'widgets_init', 'register_sendy_widget_pro_widget' );

class SendyWidgetPRO extends WP_Widget {


	public function __construct() {
		parent::__construct(
			'sendy_widget_pro_widget', // Base ID
			'Sendy Widget PRO', // 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 );

		echo $before_widget;
		$form_id = $instance['form_id'];

		echo do_shortcode('[swp-forms id='.$form_id.']');

		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['form_id'] = strip_tags( $new_instance['form_id'] );
		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' );
		}

		$the_query = new WP_Query(
			array(
				'post_type'=>'swp_forms',
				'post_status'=>'published',
				'posts_per_page' => -1
			)
		);

		if ( $the_query->have_posts() ) {

			while ( $the_query->have_posts() ) {
				$the_query->the_post();
				get_the_title();
				$forms[get_the_ID()]= get_the_title();
			}
			wp_reset_postdata();
		} else {
			$forms['0'] ='No Form Found';
		}

?>
		<p>
			<label for="<?php echo $this->get_field_id( 'form_id' ); ?>"><?php _e( 'Select Form:', 'sendywidget' ); ?></label>
			<select id="<?php echo $this->get_field_id( 'form_id' ); ?>" name="<?php echo $this->get_field_name( 'form_id' ); ?>">
			<?php foreach ($forms as $id => $title): ?>
				<option value="<?php echo $id ?>"><?php echo $title; ?></option>
			<?php endforeach ?>
			</select>

		</p>

		<p>
		<?php



	}

} // class Sendy_Widget
