<?php
/*
Plugin Name: Irontec - Groups Widget
Plugin URI: http://www.irontec.com
Description: Adds a custom friends 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_Groups_Widget extends WP_Widget {
    /** constructor */
    function Irontec_Groups_Widget() {
        parent::WP_Widget(false, $name = 'Irontec BP Groups');
    }

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

        <?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; }
			ul.irontec-widget-ul li { overflow: hidden; }
			div.irontec-widget-padder img.avatar { margin-bottom: 4px; }
			';
	        // Apply left margin if avatars are displayed
			$leftmargin = intval($instance['avatar_size'])+10;
			if ($instance['display_avatar'] == 1) {
				echo '
				div.irontec-widget-content-item { margin-left: '. $leftmargin .'px; }
				';
			}
			echo '</style>';
		}

		echo $args['before_widget'];

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

		// links content
		$links_content = "";
		if ($instance['display_links']) {
			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() .'/grupos" title="' . __('Ver todos','buddypress') . '">';
				$links_content .= __('Ver todos','buddypress');
				$links_content .= '</a>';
			}
			if ($instance['display_create'] == 1) {

				if (xprofile_get_field_data('Privacidad', bp_loggedin_user_id()) != 'Privado') {
					$links_content .= '&nbsp;&middot;&nbsp;';
					$links_content .= '<a class="fancybox-groups" href="'. site_url() .'/grupos/create" title="'. __('Crear grupo','buddypress') .'">';
					$links_content .= __('Crear grupo','buddypress');
					$links_content .= '</a>';
				}
			}
			$links_content .= '</div>';
		}

		// loggedin_user mood
		$usermood = xprofile_get_field_data('EstadoAnimo', bp_loggedin_user_id());

		// main content
		$table1 = $wpdb->prefix . 'bp_groups';
		$table2 = $wpdb->prefix . 'bp_groups_groupmeta';
		$table3 = $wpdb->prefix . 'bp_groups_members';

		$res_groups = $wpdb->get_results ('
		SELECT g.id, g.name, g.slug, gm.meta_value as ironestado, gmm.meta_value as last_activity FROM '. $table1 .' g
		INNER JOIN '. $table2 .' gm ON g.id=gm.group_id AND gm.meta_key="ironestado" AND gm.meta_value="'.$usermood.'"
		INNER JOIN '. $table2 .' gmm ON g.id=gmm.group_id AND gmm.meta_key="last_activity"
		INNER JOIN '.$table3.' g3 ON g3.group_id=g.id AND g3.user_id = '. bp_loggedin_user_id().'
		ORDER BY gmm.meta_value DESC
		LIMIT '.$instance['number']);
		$main_content = '';
		if (count($res_groups)>0) { ?>

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

			<?php
			foreach ($res_groups as $group) {
				$total_members = groups_get_groupmeta ($group->id, 'total_member_count');

				$main_content .= '<li>';

				if (!$instance['avatar_size']) $instance['avatar_size']='32';
				if ($instance['display_avatar'] == 1) {
					$main_content .= '<div class="irontec-widget-avatar">';
					$main_content .= '<a href="'. site_url() .'/grupos/'. $group->slug .'" title="'. $group->name .'">';
					$main_content .= bp_core_fetch_avatar( 'object=group&item_id='.$group->id.'&type=full&width='. $instance['avatar_size'] .'&height='. $instance['avatar_size']);
					$main_content .= '</a></div>';
				}

				$main_content .= '<div class="irontec-widget-content-item">';
				$main_content .= '<a href="'. site_url() .'/grupos/'. $group->slug .'" title="'. $group->name .'">'. $group->name .'</a>';

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

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

			<?php $main_content .= '</ul></div>'; ?>

		<?php }
		// Si no tiene grupos del estado de animo actual mostramos los grupos en los que esta inscrito
		else {

			$res_groups = $wpdb->get_results ('
			SELECT g.id, g.name, g.slug FROM '. $table1 .' g, '. $table3 .' gm
			WHERE g.id=gm.group_id AND gm.user_id= '. bp_loggedin_user_id() .'
			ORDER BY g.name LIMIT '.$instance['number']);

			$main_content = '';
			if (count($res_groups)>0) { ?>

				<?php
				foreach ($res_groups as $group) {
					$total_members = groups_get_groupmeta ($group->id, 'total_member_count');

					$main_content .= '<li>';

					if (!$instance['avatar_size']) $instance['avatar_size']='32';
					if ($instance['display_avatar'] == 1) {
						$main_content .= '<div class="irontec-widget-avatar">';
						$main_content .= '<a href="'. site_url() .'/grupos/'. $group->slug .'" title="'. $group->name .'">';
						$main_content .= bp_core_fetch_avatar( 'object=group&item_id='.$group->id.'&type=full&width='. $instance['avatar_size'] .'&height='. $instance['avatar_size']);
						$main_content .= '</a></div>';
					}

					$main_content .= '<div class="irontec-widget-content-item">';
					$main_content .= '<a href="'. site_url() .'/grupos/'. $group->slug .'" title="'. $group->name .'">'. $group->name .'</a>';

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

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

			<?php }
			else {
				$main_content .= '<div class="irontec-widget-padder">';
				$main_content .= '<span class="nodata" style="font-size: 10px;">';
				$main_content .= __('Actualmente no est&aacute;s inscrito a grupos !','buddypress');
				$main_content .= '</span></div>';
			}
			?>

		<?php }
		?>

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

		<?php echo $args['after_widget']; ?>

	<?php }

    /** @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_avatar'] = strip_tags($new_instance['display_avatar']);
		$instance['display_links'] = strip_tags($new_instance['display_links']);
		$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['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_avatar = esc_attr($instance['display_avatar']);
		$display_links = esc_attr($instance['display_links']);
		$display_create = esc_attr($instance['display_create']);
		$display_showall = esc_attr($instance['display_showall']);
		$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 "Grupos"; ?>" />
        </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_avatar'); ?>"><?php _e('Display Group 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_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_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_Groups_Widget");'));
?>
