<?php

class Intense_Widget_Template extends WP_Widget {

	function __construct() {

		$widget_ops = array( 'classname' => 'templates', 'description' => 'Add template content' );
		$control_ops = array( 'id_base' => 'template-widget' );
		parent::__construct( 'template-widget', '(Intense) Template', $widget_ops, $control_ops );

	}

	function widget( $args, $instance ) {
		global $intense_visions_options;

		extract( $args );

		echo $before_widget;

		$title = apply_filters( 'widget_title', isset( $instance['title'] ) ? $instance['title'] : '' );
		
		if ( $title ) {
			echo $before_title . $title . $after_title;
		}

		?>

		<div id="template_<?php echo $widget_id; ?>" class="intense widget-template" >
			<?php 
			echo intense_run_shortcode( 'intense_template', array( 
				'template' => $instance[ 'template_id'],
				'widget_id' => $widget_id
			) ); 
			?>
		</div>

		<?php

		echo $after_widget;
	}

	function update( $new_instance, $old_instance ) {
		global $intense_visions_options;

		$instance = $old_instance;

		$instance[ 'template_id' ] = $new_instance[ 'template_id' ];

		return $instance;

	}

	function form( $instance ) {
		global $intense_visions_options;

		$defaults = array(
			'template_id' => ''
		);

		$instance = wp_parse_args( (array) $instance, $defaults );

		$query = new WP_Query( array( 'post_type' => 'intense_templates', 'nopaging' => 'true' ) );
		$templates = array();

		$templates = intense_locate_available_plugin_templates('/template/');		
		
		?>

		<p>
			<label for="<?php echo $this->get_field_id( 'template_id' ); ?>"><?php _e( 'Template:', 'intense' ); ?></label>			
			<select id="<?php echo $this->get_field_id( 'template_id' ); ?>" name="<?php echo $this->get_field_name( 'template_id' ); ?>" class="widefat" style="width:100%;">
				<?php

				foreach ($templates as $key => $value) {
					echo '<option ' . ($instance['template_id'] == $key ? 'selected="selected"' : '') . ' value="' . esc_attr( $key ) . '">' . esc_html( $value ) . '</option>';
				}
				
				?>
			</select>
		</p>

		<?php
	}
}
