<?php

/*
+ This widget creates an album list of a selcted gallery. The gallery needs to be added to a published post or page first!
*
*/
class FancyGalleryWidget extends WP_Widget {
	
	function FancyGalleryWidget() {
		
		// widget actual processes
		$widget_opts = array (  
            'classname' => '',  
            'description' => 'Creates an album menu of the selected gallery.' 
        ); 
		
		parent::WP_Widget('fancy-gallery-widget', 'Fancy Gallery', $widget_opts);
		
	}
	
	function widget($args, $instance) {
		
		// outputs the content of the widget
		extract($args);
        $title = apply_filters( 'widget_title', empty($instance['title']) ? '' : $instance['title'], $instance, $this->id_base);
			
		global $wpdb;
		$albumTableName = $wpdb->prefix . "fg_album";
		$albums = $wpdb->get_results("SELECT * FROM " . $albumTableName . " WHERE gallery='" . $title . "' ORDER BY sort ASC");
		
		$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_content LIKE '%[fancygallery id=\'".$title."\'%' AND post_status = 'publish'" );
		
		echo $before_widget;
		if ( !empty( $title ) ) { echo $before_title . $title . $after_title; }
		
		//check if gallery has been included in a published post or page
		if( empty($postid) ) {
			echo "<p>There is no published post that has this gallery included! Please add the gallery in a published post or page first!</p>";
			return;
		}
		
		//create album menu
		echo "<ul>";
		foreach($albums as $album) {
			echo "<li><a href='" . get_permalink($postid) . "?album=".urlencode($album->title)."'>" .  $album->title . "</a></li>";
		}
		echo "</ul>";
		echo $after_widget;
		
	}

	function form($instance) {
		
		// outputs the options form on admin
		$title = esc_attr($instance['title']);
		
		//select all galleries
		global $wpdb;
		$galleryTableName = $wpdb->prefix . "fg_gallery";
		$galleries = $wpdb->get_results("SELECT * FROM " . $galleryTableName . "");
		
		echo '<p>Select a gallery:</p>';
		echo '<select name="' . $this->get_field_name('title') . '" value="'. $title . '">';
		foreach($galleries as $gallery) 
			echo '<option value="' .  $gallery->slug . '" '. selected( $gallery->slug, $title, false ) .'>' .  $gallery->title . '</option>';
		echo '</select>';
		
	}

	function update($new_instance, $old_instance) {
		
		// processes widget options to be saved
		$instance = $old_instance;
	    $instance['title'] = strip_tags($new_instance['title']);
        return $instance;
		
	}

}

?>