<?php
/*
Plugin Name: Irontec - User Info Widget
Plugin URI: http://www.irontec.com
Description: Adds a custom user info 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
*/

// AvisoLegal slug
// DEFINIMOS SLUG: Aviso Legal
// No necesario, esta todo en activity/index.php
/*
if ( !defined( 'BP_IRON_AVISOLEGAL_SLUG' ) ) define( 'BP_IRON_AVISOLEGAL_SLUG', 'avisolegal' );
function my_setup_root_iron_avisolegal () {
    bp_core_add_root_component( BP_IRON_AVISOLEGAL_SLUG );
}
add_action( 'bp_setup_root_components', 'my_setup_root_iron_avisolegal' );
function my_action_iron_avisolegal() {
    global $bp;

    if ( $bp->current_component == BP_IRON_AVISOLEGAL_SLUG ) {
        do_action( 'my_action_iron_avisolegal' );
        bp_core_load_template( apply_filters( 'bp_core_template_iron_search', 'avisolegal/index' ) );
    }
}
add_action( 'wp', 'my_action_iron_avisolegal', 1 );
*/

// Custom search slug
// Search slug
// DEFINIMOS SLUG: SEARCH
if ( !defined( 'BP_IRON_SEARCH_SLUG' ) ) define( 'BP_IRON_SEARCH_SLUG', 'customsearch' );
function my_setup_root_iron_search () {
    bp_core_add_root_component( BP_IRON_SEARCH_SLUG );
}
add_action( 'bp_setup_root_components', 'my_setup_root_iron_search' );
function my_action_iron_search() {
    global $bp;

    if ( $bp->current_component == BP_IRON_SEARCH_SLUG ) {
        do_action( 'my_action_iron_search' );
        bp_core_load_template( apply_filters( 'bp_core_template_iron_search', 'customsearch/index' ) );
    }
}
add_action( 'wp', 'my_action_iron_search', 1 );

// Notifications Widget Custom slug
// Custom slug for notifications
if ( !defined( 'BP_IRON_NOTIFICATIONS_SLUG' ) ) define( 'BP_IRON_NOTIFICATIONS_SLUG', 'notifications' );

function my_setup_root_iron_notifications () {
	bp_core_add_root_component( BP_IRON_NOTIFICATIONS_SLUG );
}

add_action( 'bp_setup_root_components', 'my_setup_root_iron_notifications' );

function my_action_iron_notifications() {
	global $bp;

	if ( $bp->current_component == BP_IRON_NOTIFICATIONS_SLUG ) {
		do_action( 'my_action_iron_notifications' );
		bp_core_load_template( apply_filters( 'bp_core_template_iron_notifications', 'notifications/index' ) );
	}
}

add_action( 'wp', 'my_action_iron_notifications', 1 );
// End custom slug for notifications

class Irontec_UserInfo_Widget extends WP_Widget {
    /** constructor */
    function Irontec_UserInfo_Widget() {
        parent::WP_Widget(false, $name = 'Irontec User Info');
    }

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

        <?php echo $before_widget; ?>

		<?php
        // change the title
        if ($instance['display_title'] == 1) {
        	$title = apply_filters('widget_title', $instance['title']);
        	if ( $title ) echo $before_title . $title . $after_title;
        }
		?>

		<?php
		if ( is_user_logged_in() ) {
			global $current_user, $bp, $wpdb;

			// Recogemos el valor de los campos Categoria y EstadoAnimo de la bbdd
			$defaultmood = xprofile_get_field_data( 'Categoria', get_current_user_id());
			$origmood = xprofile_get_field_data( 'EstadoAnimo', get_current_user_id());

			$cats=get_categories(array('hide_empty' => 0, 'parent' => 1));
			if (sizeof($cats)>0) {
				foreach ($cats as $cat) {
					if ($cat->slug==$origmood) {
						$catdata=iron_tunnels_get_category_data ($cat->term_id);
						if ($_COOKIE['LANG']=='eu')
							$current_st = $catdata->category_phrase_eu;
						elseif ($_COOKIE['LANG']=='en')
							$current_st = $catdata->category_phrase_en;
						else
							$current_st = $catdata->category_phrase;
					}
				}
			}

			//$avatar_size = $instance['avatar_size'];
			$avatar_size=0;
			if (!$avatar_size) $avatar_size="full";

			echo '<p class="clear userinfo-avatar">';
			echo '<a class="cluetip-through" rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id=15" href="'. bp_core_get_user_domain( $bp->loggedin_user->id ) .'" title="' . __( 'Tu perfil','buddypress' ) . '">' .

			//bp_core_fetch_avatar( array( 'item_id' => $bp->loggedin_user->id, 'type' => $avatar_size, 'no_grav' => true ) ) .
			  bp_core_fetch_avatar( array( 'item_id' => $bp->loggedin_user->id, 'type' => $avatar_size, 'width' => 32, 'height' => 32 ) ) .
			//bp_core_fetch_avatar( array( 'item_id' => $bp->loggedin_user->id, 'type' => 'thumb', 'no_grav' => true ) ) .
			'</a>';

			echo '</p>';
			echo '<p class="clear userinfo-name">' . xprofile_get_field_data( 'Nombre', $bp->loggedin_user->id) . ' ' . xprofile_get_field_data( 'Apellidos', $bp->loggedin_user->id);
			echo '<br />';
			echo  '<span id="mentions">@'. get_userdata( $bp->loggedin_user->id )->user_login .'</span>';
			if ( current_user_can ('manage_options') ) {
                		echo '<br /><font style="font-size: 8px;"><a href="'. site_url() .'/wp-admin/" target="_blank">wp-admin</a></font>';
		        }
			echo '</p>';
			/*
			echo '<p class="userinfo-phrase" style="cursor: pointer;">';
			_e('¿c&oacute;mo te sientes hoy?', 'buddypress');
			echo '</p>';
			*/
			echo '<p class="clear userinfo-button">';
			//echo '<a id="userinfo-state" href="'. get_stylesheet_directory_uri() . '/_inc/tips.php?tip=jtip_userinfo-state" title="Como te encuentras hoy">'. $current_st .'</a>';
			echo '<a id="userinfo-state" href="#" title="'. $current_st .'">'. $current_st .'</a>';
			echo '</p>';
			?>

			<div id="status-menu" style="width: 158px; text-align: left; font-size: 10px; color: #555; display: none; position: absolute; z-index: 1000; padding: 5px 10px 10px 25px; margin-top: -77px; margin-left: 122px;">
			<p style="margin: 5px; margin-top: 8px; height: 32px; text-align: center; margin-left: -10px;"><?php _e('¿c&oacute;mo te sientes hoy?', 'buddypress'); ?></p>
			<?php
			$cats=get_categories(array('hide_empty' => 0, 'parent' => 1));
			$n=0;
			if (sizeof($cats)>0) {
				echo '<form method="post" action="" name="estadoanimoform">';
				echo '<ul id="userinfo-state-ul" class="userinfo-ul3">';
				//echo '<li class="userinfo-state-phrase">';
				//echo '</li>';
				foreach ($cats as $cat) {
					$catdata=iron_tunnels_get_category_data ($cat->term_id);
					if ($_COOKIE['LANG']=='eu')
						$catdata_phrase = $catdata->category_phrase_eu;
					elseif ($_COOKIE['LANG']=='en')
						$catdata_phrase = $catdata->category_phrase_en;
					else
						$catdata_phrase = $catdata->category_phrase;

					if ($current_st == $catdata_phrase ) { $n++; continue; }
					$n++;
					?>
					<li class="userinfo-li_<?php echo $n; ?>">

					<input style="cursor: pointer; margin-top: 6px;" type="radio" name="st" value="<?php echo $cat->term_id; ?>" <?php if ($cat->slug == $origmood) echo " checked"; ?> onclick="document.estadoanimoform.submit();">

					<span style="position: absolute; margin-top: 6px; margin-left: 2px;">
					<?php echo $catdata_phrase; ?>
					</span>
					</li>
				<?php }

				echo '</ul>';
				echo '</form>';
				echo '<p class="clear"></p>';
				?>

				<?php
			}
			?>
			</div>

			<?php
			$ptot=4;
			$n=0;

			// Calculate percentage of the profile
			if (xprofile_get_field_data( 'Nombre', get_current_user_id()) != "") $n++;
			if ((xprofile_get_field_data( 'Apellidos', get_current_user_id()) != "") && (xprofile_get_field_data( 'Apellidos', get_current_user_id()) != " ")) $n++;
			if ((xprofile_get_field_data( 'Poblacion', get_current_user_id()) != "") && (xprofile_get_field_data( 'Poblacion', get_current_user_id()) != " ")) $n++;
			if ((xprofile_get_field_data( 'Patologia', get_current_user_id()) != "") && (xprofile_get_field_data( 'Patologia', get_current_user_id()) != " ")) $n++;

			if ($ptot>0) $profile_porc=number_format(($n*100)/$ptot,0). "%";
			?>

			<?php
			// Countings
			$nmessages = bp_get_total_unread_messages_count();
			if (!$nmessages) $nmessages = '0';

			$nfriends = bp_get_total_friend_count( bp_loggedin_user_id() );
			if (!$nfriends) $nfriends = '0';

            $event_user = $wpdb->get_results("SELECT * FROM ". $wpdb->prefix ."jet_events_members WHERE user_id='".get_current_user_id()."'");

			$event_user_valid .= '(';
			for($i=0;$i<=(count($event_user)-1);$i++)
	        {
			$event_user_valid .= 'id="'.$event_user[$i]->event_id.'" or ';
            }
			$event_user_valid .= 'id="")';
			$addquery = "(eventapproved=1 OR eventapproved=0)";
			$addquery .= ' AND edtedunix > '.time().' ORDER BY date_created DESC';
			$list = $wpdb->get_results("SELECT * FROM ". $wpdb->prefix ."jet_events WHERE ". $event_user_valid ." and ". $addquery);
			$nevents = count($list);
			if (!$nevents) $nevents = '0';

			$ngroups = bp_get_total_group_count_for_user( bp_loggedin_user_id() );
			if (!$ngroups) $ngroups = '0';

			// Get Notifications
			//$notifications = bp_core_get_notifications_for_user( $user_id = bp_loggedin_user_id() );
			//$notifications = BP_Core_Notification::get_all_for_user( bp_loggedin_user_id() );
			//var_dump($notifications);
			/*
			if ( $notifications = BP_Core_Notification::get_all_for_user( bp_loggedin_user_id() ) ) { ?>
				<p><?php $nalerts = count( $notifications ) ?></p>
				<p><?php foreach ($notifications as $notif) : ?>
				<?php echo $notif; ?>
				<?php endforeach; ?>
				</p>
			<?php }
			*/

			// Esta es la manera buena de contar notificaciones
			//$notifications = bp_core_get_notifications_for_user( bp_loggedin_user_id() );
			$notifications = BP_Core_Notification::get_all_for_user( wp_get_current_user()->ID );//Para custom events

			if (is_array($notifications)) { $nalerts = count ($notifications); }
			else { $nalerts=0; }

			echo '<ul class="userinfo-ul">';

			echo '<li class="userinfo-li"></li>';

			/*
			echo '<li class="userinfo-li"><a class="userinfo-a cluetip-through" rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id=11" href="'. bp_loggedin_user_domain() . 'profile/edit">';
			_e ('Editar perfil','buddypress');
			echo '</a> <span style="background:none;color: #4EA6CC;" class="userinfo-addnote">'. $profile_porc .'</span></li>';
			*/

			if ($nmessages>0) $classmes="messages-on"; else $classmes="messages-off";
			echo '<li class="userinfo-li" style="margin-top: 10px;"><a class="userinfo-a cluetip-through '.$classmes.'" rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id=33" href="'. bp_loggedin_user_domain() .'messages/inbox">';
			_e ('Mensajes','buddypress');
			echo '</a>';
			if ($nmessages)
				echo '&nbsp;<span class="userinfo-addnote">'. $nmessages .'</span>';
			echo '</li>';

			if ($nmessages>0) $classnot="notifications-on"; else $classnot="notifications-off";
			echo '<li class="userinfo-li"><a class="userinfo-a cluetip-through '.$classnot.'" rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id=35" href="'. site_url() .'/notifications">';
			_e ('Notificaciones','buddypress');
			echo '</a>';
			if ($nalerts)
				echo '&nbsp;<span class="userinfo-addnote">'. $nalerts .'</span>';
			echo '</li>';

			echo '<li class="userinfo-li2" style="margin-top: 10px;"><a class="userinfo-a2 cluetip-through friends" rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id=34" href="'. bp_loggedin_user_domain() .'friends">';
			_e ('Amigos','buddypress');
			echo '</a> <span class="userinfo-addnote2">'. $nfriends .'</span></li>';
			echo '<li class="userinfo-li2"><a class="userinfo-a2 cluetip-through events" rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id=25" href="'. site_url() .'/eventos/">';
			_e ('Eventos','buddypress');
			echo '</a> <span class="userinfo-addnote2">'. $nevents .'</span></li>';
			echo '<li class="userinfo-li2"><a class="userinfo-a2 cluetip-through groups" rel="'. get_stylesheet_directory_uri() .'/_inc/tips.php?id=32" href="'. bp_loggedin_user_domain().'groups/">';
			_e ('Grupos','buddypress');
			echo '</a> <span class="userinfo-addnote2">'. $ngroups .'</span></li>';
			echo '</ul>';
		}
		else
			_e ('Elige tu experiencia y participa en la red.','buddypress');
		?>

		<?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['avatar_size'] = strip_tags($new_instance['avatar_size']);
		$instance['display_title'] = strip_tags($new_instance['display_title']);
		$instance['post_activity'] = strip_tags($new_instance['post_activity']);

		return $instance;
    }

    /** @see WP_Widget::form */
    function form($instance) {
		$title = esc_attr($instance['title']);
		$avatar_size = esc_attr($instance['avatar_size']);
		$display_title = esc_attr($instance['display_title']);
		$post_activity = esc_attr($instance['post_activity']);
        ?>
		<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; ?>" />
        </p>
        <p>
          <label for="<?php echo $this->get_field_id('display_title'); ?>"><?php _e('Display Title ?'); ?></label>
          <input id="<?php echo $this->get_field_id('display_title'); ?>" name="<?php echo $this->get_field_name('display_title'); ?>" type="checkbox" value="1" <?php if ($display_title==1) echo "checked"; ?> />
        </p>
        <p>
          <label for="<?php echo $this->get_field_id('avatar_size'); ?>"><?php _e('Avatar size:'); ?></label>
          <input class="widefat" 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 "40"; ?>" style="width: 50px;" maxlength="3" />
        </p>
        <p>
          <label for="<?php echo $this->get_field_id('post_activity'); ?>"><?php _e('Post Activity Updates on Mood Change ?'); ?></label>
          <input type="checkbox" id="<?php echo $this->get_field_id('post_activity'); ?>" name="<?php echo $this->get_field_name('post_activity'); ?>" value="1" <?php if ($post_activity==1) echo "checked"; ?> />
        </p>
	<?php }
}

add_action('widgets_init', create_function('', 'return register_widget("Irontec_UserInfo_Widget");'));

// Control de Estado en Login
// Se asegura de crear los campos EstadoAnimo y Categoria a cada usuario
// wp_login action Hook
//add_action('wp_login','irontec_st_control');

// Hook wp_login function
/*
function irontec_st_control () {

	// Cargamos wpdb y definimos los nombres de las tablas
	global $wpdb;
	$st_field_id = 5; // Id del campo EstadoAnimo en wordpress
	$cat_field_id = 10; // Id del campo Categor�a en wordpress
	$users_table_name = $wpdb->prefix . "users";
	$profile_table_name = $wpdb->prefix . "bp_xprofile_data";

	// Recogemos login y password
	$login = strip_tags($_POST['log']);
	$password = strip_tags($_POST['pwd']);

	// Primero obtenemos el id del usuario
	if ($login && $password) {
		$userdata = $wpdb->get_results( "SELECT ID FROM ".$users_table_name."
		WHERE user_login='".$login."'");

		// Si tenemos el ID de usuario
		if ($userdata[0]->ID) {
			// Obtenemos el valor del campo auto_estado
			$auto_st = xprofile_get_field_data( 'auto_estado', $userdata[0]->ID);
			// Obtenemos el valor del campo categoria
			$defaultmood = xprofile_get_field_data( 'Categoria', $userdata[0]->ID);
			// Actualizamos el campo EstadoAnimo al mismo de la Categor�a
			// Si auto_estado no esta marcado
			if ($auto_st == '') {
				$wpdb->query('UPDATE '.$profile_table_name.' SET value="'.$defaultmood.'", last_updated="'.date("Y-m-d H:i:s").'" WHERE user_id='.$userdata[0]->ID.' AND field_id='.$st_field_id);
			}
		}
	}

	echo "login: ".$login;
	echo " | pass: ".$password;
	echo " | id: ".$userdata[0]->ID;
	echo " | mood: ".$defaultmood;
	echo " | st: ".$auto_st;
	echo " | create: ".$create;

}
*/
?>
