<?php

class archive_widget extends WP_Widget {
    public function __construct() {
    	parent::__construct(
	 		'archive_widget',
			'Special Post Archive',
			array( 'description' => __( 'Post Archive by years and months', 'pippajean' ), ) // Args
		);
	}

    public function widget( $args, $instance ) {
		global $wpdb;
		extract( $args );
        $title = apply_filters( 'widget_title', $instance['title'] );
        echo $before_widget;
        echo "<div class='archive-by-year'>";
        echo $before_title . $title . $after_title;
        echo "<div id='archives' class='accordion'>";

        /* http://www.wpbeginner.com/wp-themes/how-to-customize-the-display-of-wordpress-archives-in-your-sidebar/ */

		$limit = 0;
		$year_prev = null;
		$months = $wpdb->get_results("SELECT DISTINCT MONTH( post_date ) AS month ,	YEAR( post_date ) AS year, COUNT( id ) as post_count FROM $wpdb->posts WHERE post_status = 'publish' and post_date <= now( ) and post_type = 'post' GROUP BY month , year ORDER BY post_date DESC");

		foreach($months as $month) :
			$year_current = $month->year;
			if ($year_current != $year_prev){ echo "<h3>$month->year</h3><ul>"; } ?>
			<li><a href="<?php bloginfo('url') ?>/<?php echo $month->year; ?>/<?php echo date("m", mktime(0, 0, 0, $month->month, 1, $month->year)) ?>"><?php echo date("F", mktime(0, 0, 0, $month->month, 1, $month->year)) ?></a></li>
			<?php 
			if ($year_current == $year_prev) echo "</ul>";
			$year_prev = $year_current;
		endforeach;

		echo "</div></div>";
        echo $after_widget;
	}

	public function update( $new_instance, $old_instance ) {
		$instance = $old_instance;
		$instance['title'] = strip_tags( $new_instance['title'] );
		return $instance;
	}

	public function form( $instance ) {
		if ( $instance ) { 
            $title = esc_attr( $instance[ 'title' ] );
        } else {
            $title = __( '', 'pippajean' );
        } ?>
	    <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>"  title="Title"><?php _e( 'Title:', 'pippajean' ); ?></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 $title; ?>" />
		</p>
		<?php 
	}
}

add_action( 'widgets_init', create_function( '', 'register_widget( "archive_widget" );' ) );