<?php
/**
 * Adds JArchive widget.
 */
class JArchive extends WP_Widget 
{

	/**
	 * Register widget with WordPress.
	 */
	public function __construct() 
	{
		parent::__construct(
	 		'jarchive_widget', // Base ID
			__( 'Jalali Archive', 'wp-persian' ), // Name
			array( 'description' => __( 'A jalali monthly archive of your site’s posts', 'wp-persian' ), ) // 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 (!isset($instance['type'])) {
			$type="monthly";
		//} else {
			//$type = $instance['type'];
		//}
		$show_post_count = ($instance['show_post_count'] == '1') ? "1" : "0"; // More Safer Way
		$dropdown = ($instance['dropdown'] == '1') ? "1" : "0";
		echo $before_widget;
		echo $before_title . $title . $after_title;
		if ($dropdown) {
			echo "<select name=\"jarchive-dropdown\" onchange='document.location.href=this.options[this.selectedIndex].value;'> <option value=\"\">".attribute_escape($title)."</option>";
			self::Monthly("type=$type&format=option&show_post_count=$show_post_count");
			echo "</select>";
		} else {
			echo '<ul>';
			self::Monthly("type=$type"."&show_post_count=".$show_post_count);
			echo '</ul>';
		}
/*
		if ( ! empty( $title ) )
			echo $before_title . $title . $after_title;
		echo __( 'Hello, World!', 'text_domain' );
*/
		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['type'] = 'monthly';
		$instance['show_post_count'] = strip_tags( $new_instance['show_post_count'] );
		$instance['dropdown'] = strip_tags( $new_instance['dropdown'] );

		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' ];
			$type = $instance[ 'type' ];
			$show_post_count = $instance[ 'show_post_count' ];
			$dropdown = $instance[ 'dropdown' ];
		}
		else {
			$title = __( 'title', 'wp_persian' );
		}
		?>

		<p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:','wp-persian' ); ?> <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></p>
		<p><input name="<?php echo $this->get_field_name( 'dropdown' ); ?>" type="checkbox" value="1" id="<?php echo $this->get_field_id( 'dropdown' ); ?>" <?php echo $dropdown=='1' ? 'checked="checked"':'' ?> /> <label for="<?php echo $this->get_field_id( 'dropdown' ); ?>"><?php _e( 'Display as dropdown','wp-persian' ); ?></label><br />
		<input name="<?php echo $this->get_field_name( 'show_post_count' ); ?>" type="checkbox" value="1" id="<?php echo $this->get_field_id( 'show_post_count' ); ?>" <?php echo $show_post_count=='1' ? 'checked="checked"':'' ?> /> <label for="<?php echo $this->get_field_id( 'show_post_count' ); ?>"><?php _e( 'Show post counts','wp-persian' ); ?></label></p>
		
		<?php 
	}
	
	public static function Monthly($args = '') 
	{
		parse_str($args, $r);
		if (!isset($r['limit'])) $r['limit'] = '';
		if (!isset($r['format'])) $r['format'] = 'html';
		if (!isset($r['before'])) $r['before'] = '';
		if (!isset($r['after'])) $r['after'] = '';
		if (!isset($r['show_post_count'])) $r['show_post_count'] = false;
		self::_wpp_get_monthly_archives( $r['limit'], $r['format'], $r['before'], $r['after'], $r['show_post_count']);
	}

	private static function _wpp_get_monthly_archives($limit='', $format='html', $before = '', $after = '', $show_post_count = false) 
	{
		global $wpdb;

		if ('' != $limit && 0 != $limit) {
			$limit = (int) $limit;
		}

		$arcresults = $wpdb->get_results( "
					SELECT YEAR( post_date ) AS year, MONTH( post_date ) AS month, DAY( post_date ) as day
					FROM $wpdb->posts
					WHERE post_type = 'post' AND post_date < NOW() AND post_status = 'publish'
					ORDER BY post_date DESC" );
		
		if ($arcresults)
		{
			$i = 1;$predate=0;$posts=1;
			$archive=array();
			foreach($arcresults as $arc)
			{
				$month = zeroise( $arc->month, 2 );
				$year = $arc->year;
				$gmt = mktime(0 ,0 , 0, $month, $arc->day, $year);
				$date = jdate('Ym',$gmt);
				
				if($predate == $date)
					$posts++;
				else
					$posts=1;

				$predate = $date;
				
				$archive[$date]=array(
							'text'=>WPPersian::PersianNumbers(jdate('M Y',$gmt)),
							'url'=>get_month_link(jdate('Y',$gmt), jdate('m',$gmt)),
							'posts'=>WPPersian::PersianNumbers($posts),
							
							);
				
				if($i == $limit) break;
				$i++;
			}
			$post_count='';
			foreach($archive as $v)
			{
				if ($show_post_count)
					$post_count = '&nbsp;('.$v['posts'].')';
				echo get_archives_link($v['url'], $v['text'], $format, $before, $post_count.$after);
			}
		}
	}
	
} // class JArchive



/**
 * Adds JCalendar widget.
 */
class JCalendar extends WP_Widget 
{

	/**
	 * Register widget with WordPress.
	 */
	public function __construct() 
	{
		parent::__construct(
	 		'jcalendar_widget', // Base ID
			__( 'Jalali Calendar', 'wp-persian' ), // Name
			array( 'description' => __( 'A jalali calendar of your site’s posts', 'wp-persian' ), ) // Args
		);
	}
	private static function _calendar() 
	{
		global $m,$year;
		$i_year='';
		if ($m != '') {
			$m = '' . preg_replace('|[^0-9]|', '', $m);
			$i_year = substr($m,0,4);
		} else if ($year != '') {
			$i_year = $year;
		}
		if ($i_year > 1700) get_calendar(); else get_jcalendar();
	}
	/**
	 * 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;
		echo $before_title . $title . $after_title;
		self::_calendar();
		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'] );

		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 = __( 'title', 'wp_persian' );
		}
		?>
		<p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?> <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></p>
		<?php 
	}



} // class JCalendar



function register_wpp_widgets() 
{
	load_plugin_textdomain( 'wp-persian', false, dirname( plugin_basename( __FILE__ ) ) . '/lang' );;
	register_widget( 'JArchive' );  
	register_widget( 'JCalendar' );  
} 


add_action( 'widgets_init', 'register_wpp_widgets' );
?>