<?php

function bw_register_widget() {
	register_widget( 'bw_toplist_widget' );
}

add_action( 'widgets_init', 'bw_register_widget' );

class bw_toplist_widget extends WP_Widget {
	function __construct() {
		parent::__construct(
		    'bw_toplist_widget',
		    __('BW Toplist Widget', ' toplist_widget'),
            array( 'description' => __( 'BW Widget Plugin', 'toplist_widget' ), )
        );
	}

	public function widget( $args, $instance ) {

		$title = apply_filters( 'widget_title', $instance['title'] );
		$rows = apply_filters( 'widget_title', $instance['rows'] );
		echo $args['before_widget'];
		//if title is present
		if ( ! empty( $title ) )
			echo $args['before_title'] . $title . $args['after_title'];
		//output
		echo __( 'Toplist Widget', 'toplist_widget' );
		echo $args['after_widget'];
		echo do_shortcode( '[toplist rows='.$rows.']' );
	}

	public function form( $instance ) {
		if ( isset( $instance[ 'title' ] ) )
			$title = $instance[ 'title' ];
		else
			$title = __( 'Default Title', 'toplist_widget' );
		
		if ( isset( $instance[ 'rows' ] ) )
			$rows = $instance[ 'rows' ];
		else
			$rows = 20;
		
		?>
			<p>
				<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></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 ); ?>"/>
				<label for="<?php echo $this->get_field_id( 'rows' ); ?>"><?php _e( 'Rows:' ); ?></label>
				<input class="widefat" id="<?php echo $this->get_field_id( 'rows' ); ?>" name="<?php echo $this->get_field_name( 'rows' ); ?>" type="text" value="<?php echo esc_attr( $rows ); ?>"/>
			</p>
		<?php
	}

	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
		$instance['rows'] = ( ! empty( $new_instance['rows'] ) ) ? strip_tags( $new_instance['rows'] ) : '';
		return $instance;
	}
}