<?php
/*
Plugin Name: Irontec - Events Widget
Plugin URI: http://www.irontec.com
Description: Adds a custom events widget
Version: 0.1
Author: Irontec
Author URI: http://www.irontec.com
License: GNU General Public License 2.0 (GPL) http://www.gnu.org/licenses/gpl.html
*/
class Irontec_Events_Widget extends WP_Widget {
    /** constructor */
    function Irontec_Events_Widget() {
        parent::WP_Widget(false, $name = 'Irontec Events');
    }

    /** @see WP_Widget::widget */
	function widget($args, $instance) {
		global $bp;
        extract( $args );
        ?>

        <?php echo $before_widget; ?>

        <?php
		// Use plugin own css
        if ( $instance['use_css'] == 1) {
			echo '<style>
			div.irontec-widget-padder { line-height: 115%; overflow: hidden; padding: 0px 8px; margin: 6px 0px; }
			div.irontec-widget-links-padder { overflow: hidden; padding: 2px 0 0 2px; }
			div.irontec-widget-content-item { margin-bottom: 6px; }
			div.irontec-widget-nmembers { color: #888; font-size: 11px; margin-top: 4px; }
			div.irontec-widget-content-item a { font-weight: bold; }
			div.irontec-widget-links-padder a { font-weight: normal; font-size: 11px; }
			</style>';
		}

		// Apply left margin if avatars are displayed
		$leftmargin = intval($instance['avatar_size'])+10;
		if ($instance['display_avatar'] == 1) {
			echo '<style>
			div.irontec-widget-content-item { margin-left: '. $leftmargin .'px }
			</style>';
		}

        // change the title
        $title = apply_filters('widget_title', $instance['title']);
        if ( $title ) {
        	$before_title = str_replace ('widgettitle','widgettitle events', $before_title);
			echo $before_title;
			echo '<a href="'. site_url() .'/eventos/" title="'. __('Eventos', 'buddypress') .'">';
			echo __('Eventos', 'buddypress');
			echo '</a>';
			echo $after_title;
		}

		// links content
		$links_content = "";
		if ($instance['links_align'] == "right")
			$links_content .= '<div class="irontec-widget-links-padder" style="text-align: right">';
		else
			$links_content .= '<div class="irontec-widget-links-padder">';

		// Show all and create links
		if ($instance['display_showall'] == 1) {
			$links_content .= '<a href="'. site_url() .'/eventos/" title="'. __('Eventos', 'buddypress') .'">';
			$links_content .= __('Ver todos','buddypress');
			$links_content .= '</a>';
		}
		if ($instance['display_showall'] == 1 && $instance['display_create'] == 1)
			$links_content .= '&nbsp;&middot;&nbsp;';
		if ($instance['display_create'] == 1) {
			//$links_content .= '<a class="fancybox-events" href="'. site_url() .'/events/create" title="Crear Evento">Crear Evento</a>';
			$links_content .= '<a href="'. site_url() .'/eventos-create/" title="' . __('Crear evento','buddypress') . '">';
			$links_content .= __('Crear evento','buddypress');
			$links_content .= '</a>';
		}
		$links_content .= '</div>';
		?>

		<?php
		global $wpdb;
		$tablename1= $wpdb->prefix . "jet_events";
		$tablename2= $wpdb->prefix . "jet_events_eventmeta";
		$tablename3= $wpdb->prefix . "jet_events_members";
		
		// Estado de animo actual del usuario
		$current_state = xprofile_get_field_data( 'EstadoAnimo', bp_loggedin_user_id());

		// Default values
		$EventFilter='active';
		$Scope='just-me';

		// Admin sees all events and can approve
		$addquery="(eventapproved=1 OR eventapproved=0)";
		// Limit the query by config
		$limitquery=" LIMIT ".$instance['number'];

		// Scope
		if ($Scope == 'just-me') {
			$addquery .= ' AND e.id IN (SELECT emm.event_id FROM '.$tablename3.' emm WHERE emm.user_id='. get_current_user_id().')';
		}

		// Search
		if ($EventSearch) {
			$addquery .= ' AND ( e.name LIKE "%'. $EventSearch .'%" || e.description LIKE "%'. $EventSearch .'%" )';
		}

		// Dejamos que pase 1 dia completo para que no se muestren los eventos como activos
		$now = time() - 86400;

		// Filters
		if ($EventFilter) {
			if ($EventFilter == 'soon')
				$addquery .= ' AND edtedunix > '.$now.' ORDER BY edtsdunix ASC';
			elseif ($EventFilter == 'active')
				$addquery .= ' AND edtedunix > '.$now.' ORDER BY edtsdunix ASC';
			elseif ($EventFilter == 'alphabetical')
				$addquery .= ' ORDER BY name ASC';
			elseif ($EventFilter == 'past')
				$addquery .= ' AND edtedunix < '.$now.' ORDER BY edtsdunix DESC';
			elseif ($EventFilter == 'newest')
				$addquery .= ' ORDER BY date_created DESC';
		}

		// Primary SQL
		/*
		$list = $wpdb->get_results("SELECT e.* FROM ". $tablename1 ." e
		INNER JOIN ".$tablename2." em ON em.event_id = e.ID AND em.meta_key='ironestado' AND em.meta_value='".$current_state."'
		WHERE ". $addquery . $limitquery);
		*/
		
		$list = $wpdb->get_results("SELECT e.* FROM ". $tablename1 ." e
		INNER JOIN ".$tablename2." em ON em.event_id = e.ID AND em.meta_key='ironestado'
		WHERE ". $addquery . $limitquery);
		
		echo mysql_error();
		?>

		<?php $main_content = '<div class="irontec-widget-padder">'; ?>

		<?php
		if (sizeof($list)>0) :

		foreach ($list as $ev) {

			$eventdata = $wpdb->get_results("SELECT * FROM ". $tablename2 ." WHERE meta_key='total_member_count' AND event_id=". $ev->id);
			foreach ($eventdata as $evdata) {
				$event_total_member_count = $evdata->meta_value;
			}
			?>
			<?php
			// Avatar
			if ($instance['display_avatar'] == 1)
				$main_content .= '<div class="irontec-widget-avatar">
				<a href="'. site_url() .'/events/'. $ev->slug .'" title="'. $ev->name .'">';
				$main_content .= jes_core_fetch_avatar( array ('width'=>$instance['avatar_size'],'height'=>$instance['avatar_size'], 'item_id'=>$ev->id ) );
				$main_content .= '</a></div>';

			// Content
			$main_content .= '<div class="irontec-widget-content-item">';
			$main_content .= '<a href="'. site_url() .'/eventos/?view='. $ev->slug .'" title="'. $ev->name .'">'. $ev->name .'</a>';

			// Member count
			if ($instance['display_nmem'] == 1) {
				if ($event_total_member_count==1) {
                    $num_text = __ ('member','buddypress');
                } else {
                    $num_text = __ ('members','buddypress');
                }
                 
				$main_content .= '<div class="irontec-widget-nmembers">'. $event_total_member_count. ' '. $num_text.'</div>';
			}

			// Days remaining to start
			if ($instance['display_daysrem'] == 1) {
				$cdate = $ev->edtsdunix;
				$today = time();
				$difference = $cdate - $today;
				if ($difference <= 0) {
					$main_content .= '<div class="irontec-widget-nmembers">'. __('Ha comenzado','buddypress') .'</div>';
				}
				else {
					$main_content .= '<div class="irontec-widget-nmembers">'. __('Comienza en','buddypress') .' '. floor(($difference/60/60/24)+1).' '. __('d&iacute;as','buddypress') .'</div>';
				}
			}

			$main_content .= '</div> <!-- irontec-widget-content-item -->';
			?>
		<?php }
		?>

		<?php $main_content .= '</div> <!-- irontec-widget-padder -->'; ?>

		<?php else : ?>

			<?php
			// If no events are found for this user
			$main_content .= '<div class="irontec-widget-padder">';
			$main_content .= '<span class="nodata" style="font-size: 10px;">';
			$main_content .= __('Actualmente no eres miembro de ning&uacute;n evento activo!','buddypress');
			$main_content .= '</span>';
			$main_content .= '</div>';
			?>

		<?php endif; ?>

		<?php
		// Display the content
		if ($instance['links_valign'] == "top")
			echo $links_content . $main_content;
		else
			echo $main_content . $links_content;
		?>

		<?php echo $after_widget;
	}

	/** @see WP_Widget::update */
    function update($new_instance, $old_instance) {
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['number'] = strip_tags($new_instance['number']);
		$instance['avatar_size'] = strip_tags($new_instance['avatar_size']);
		$instance['display_nmem'] = strip_tags($new_instance['display_nmem']);
		$instance['display_daysrem'] = strip_tags($new_instance['display_daysrem']);
		$instance['display_avatar'] = strip_tags($new_instance['display_avatar']);
		$instance['display_create'] = intval($new_instance['display_create']);
		$instance['display_showall'] = intval($new_instance['display_showall']);
		$instance['use_css'] = strip_tags($new_instance['use_css']);
		$instance['display_links'] = strip_tags($new_instance['display_links']);
		$instance['links_valign'] = strip_tags($new_instance['links_valign']);
		$instance['links_align'] = strip_tags($new_instance['links_align']);

		return $instance;
    }

    /** @see WP_Widget::form */
    function form($instance) {
		$title = esc_attr($instance['title']);
		$number = esc_attr($instance['number']);
		$avatar_size = esc_attr($instance['avatar_size']);
		$display_nmem = esc_attr($instance['display_nmem']);
		$display_daysrem = esc_attr($instance['display_daysrem']);
		$display_avatar = esc_attr($instance['display_avatar']);
		$display_create = esc_attr($instance['display_create']);
		$display_showall = esc_attr($instance['display_showall']);
		$display_links = esc_attr($instance['display_links']);
		$use_css = esc_attr($instance['use_css']);
		$links_valign = esc_attr($instance['links_valign']);
		$links_align = esc_attr($instance['links_align']);
        ?>
		<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 if ($title) echo $title; else echo "Your Events"; ?>" />
        </p>
        <p>
          <label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of items:'); ?></label>
          <input style="width:40px;" id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php if ($number) echo $number; else echo "10"; ?>" maxlength="3" />
        </p>
        <p>
          <label for="<?php echo $this->get_field_id('use_css'); ?>"><?php _e('Use plugin CSS ?'); ?></label>
          <input id="<?php echo $this->get_field_id('use_css'); ?>" name="<?php echo $this->get_field_name('use_css'); ?>" type="checkbox" value="1" <?php if ($use_css==1) echo "checked"; ?> />
        </p>
        <p>
          <label for="<?php echo $this->get_field_id('display_nmem'); ?>"><?php _e('Display Member Count ?'); ?></label>
          <input id="<?php echo $this->get_field_id('display_nmem'); ?>" name="<?php echo $this->get_field_name('display_nmem'); ?>" type="checkbox" value="1" <?php if ($display_nmem==1) echo "checked"; ?> />
        </p>
        <p>
          <label for="<?php echo $this->get_field_id('display_daysrem'); ?>"><?php _e('Display Days Remaining ?'); ?></label>
          <input id="<?php echo $this->get_field_id('display_daysrem'); ?>" name="<?php echo $this->get_field_name('display_daysrem'); ?>" type="checkbox" value="1" <?php if ($display_daysrem==1) echo "checked"; ?> />
        </p>
        <p>
          <label for="<?php echo $this->get_field_id('display_avatar'); ?>"><?php _e('Display Event Avatar ?'); ?></label>
          <input id="<?php echo $this->get_field_id('display_avatar'); ?>" name="<?php echo $this->get_field_name('display_avatar'); ?>" type="checkbox" value="1" <?php if ($display_avatar==1) echo "checked"; ?> />
        </p>
        <?php if ( $display_avatar == 1 ) { ?>
	        <p>
	          <label for="<?php echo $this->get_field_id('avatar_size'); ?>"><?php _e('Avatar Size:'); ?></label>
	          <input style="width:40px;" id="<?php echo $this->get_field_id('avatar_size'); ?>" name="<?php echo $this->get_field_name('avatar_size'); ?>" type="text" value="<?php if ($avatar_size) echo $avatar_size; else echo "32"; ?>" maxlength="3" />&nbsp;px
	        </p>
        <?php } ?>
        <p>
          <label for="<?php echo $this->get_field_id('display_links'); ?>"><?php _e('Display Links ?'); ?></label>
          <input id="<?php echo $this->get_field_id('display_links'); ?>" name="<?php echo $this->get_field_name('display_links'); ?>" type="checkbox" value="1" <?php if ($display_links==1) echo "checked"; ?> />
        </p>
        <?php if ( $display_links == 1 ) { ?>
	        <p>
	          <label for="<?php echo $this->get_field_id('links_align'); ?>"><?php _e('Links align:'); ?></label>
	          <p>
	          Left <input id="<?php echo $this->get_field_id('links_align'); ?>" name="<?php echo $this->get_field_name('links_align'); ?>" type="radio" value="left" <?php if ($links_align== "left") echo "checked"; ?> />&nbsp;
	          Right <input id="<?php echo $this->get_field_id('links_align'); ?>" name="<?php echo $this->get_field_name('links_align'); ?>" type="radio" value="right" <?php if ($links_align == "right") echo "checked"; ?> />
	          </p>
	        </p>
	        <p>
	          <label for="<?php echo $this->get_field_id('links_valign'); ?>"><?php _e('Links v-align:'); ?></label>
	          <p>
	          Top <input id="<?php echo $this->get_field_id('links_valign'); ?>" name="<?php echo $this->get_field_name('links_valign'); ?>" type="radio" value="top" <?php if ($links_valign== "top") echo "checked"; ?> />&nbsp;
	          Bottom <input id="<?php echo $this->get_field_id('links_valign'); ?>" name="<?php echo $this->get_field_name('links_valign'); ?>" type="radio" value="bottom" <?php if ($links_valign == "bottom") echo "checked"; ?> />
	          </p>
	        </p>
	        <p>
	          <label for="<?php echo $this->get_field_id('display_showall'); ?>"><?php _e('Display Show all link ?'); ?></label>
	          <input id="<?php echo $this->get_field_id('display_showall'); ?>" name="<?php echo $this->get_field_name('display_showall'); ?>" type="checkbox" value="1" <?php if ($display_showall==1) echo "checked"; ?> />
	        </p>
	        <p>
	          <label for="<?php echo $this->get_field_id('display_create'); ?>"><?php _e('Display Create link ?'); ?></label>
	          <input id="<?php echo $this->get_field_id('display_create'); ?>" name="<?php echo $this->get_field_name('display_create'); ?>" type="checkbox" value="1" <?php if ($display_create==1) echo "checked"; ?> />
	        </p>
        <?php } ?>
	<?php }
}

add_action('widgets_init', create_function('', 'return register_widget("Irontec_Events_Widget");'));
?>