<?php
/*
Plugin Name: Irontec - Pregunta a todos
Plugin URI: http://www.irontec.com
Description: This plugin allows to add questions for all users
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
*/

// DEFINIMOS SLUG: PREGUNTATODOS-MODAL
if ( !defined( 'BP_IRON_PREGUNTATODOSMODAL_SLUG' ) ) define( 'BP_IRON_PREGUNTATODOSMODAL_SLUG', 'questions-modal' );
function my_setup_root_iron_preguntatodosmodal () {
	bp_core_add_root_component( BP_IRON_PREGUNTATODOSMODAL_SLUG );
}
add_action( 'bp_setup_root_components', 'my_setup_root_iron_preguntatodosmodal' );
function my_action_iron_preguntatodosmodal() {
	global $bp;

	if ( $bp->current_component == BP_IRON_PREGUNTATODOSMODAL_SLUG ) {
		do_action( 'my_action_iron_preguntatodosmodal' );
		bp_core_load_template( apply_filters( 'bp_core_template_iron_preguntatodos_modal', 'preguntatodos-modal/index' ) );
	}
}
add_action( 'wp', 'my_action_iron_preguntatodosmodal', 1 );

// DEFINIMOS SLUG: PREGUNTATODOS
if ( !defined( 'BP_IRON_PREGUNTATODOS_SLUG' ) ) define( 'BP_IRON_PREGUNTATODOS_SLUG', 'questions' );
function my_setup_root_iron_preguntatodos () {
	bp_core_add_root_component( BP_IRON_PREGUNTATODOS_SLUG );
}
add_action( 'bp_setup_root_components', 'my_setup_root_iron_preguntatodos' );
function my_action_iron_preguntatodos() {
	global $bp;

	if ( $bp->current_component == BP_IRON_PREGUNTATODOS_SLUG ) {
		do_action( 'my_action_iron_preguntatodos' );
		bp_core_load_template( apply_filters( 'bp_core_template_iron_preguntatodos', 'preguntatodos/index' ) );
	}
}
add_action( 'wp', 'my_action_iron_preguntatodos', 1 );

// Definimos la clase
class Irontec_PreguntaTodos_Widget extends WP_Widget {
    /** constructor */
    function Irontec_PreguntaTodos_Widget() {
        parent::WP_Widget(false, $name = 'Irontec Pregunta a todos');
    }

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

        <?php echo $before_widget; ?>

		<?php
        // change the title
        $title = apply_filters('widget_title', $instance['title']);
		if ( $title ) {
			$before_title = str_replace ('widgettitle','widgettitle questions', $before_title);
			echo $before_title;
			echo '<a href="'. bp_loggedin_user_domain() .'questions" title="'. __('Pregunta a todos','buddypress') .'">';
			_e('Pregunta a todos','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">';

		if ($instance['display_showall'] == 1) {
			$links_content .= '<a href="'. bp_loggedin_user_domain() .'questions" title="' . __('Ver todas','buddypress') .'">';
			$links_content .= __('Ver todas','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-preguntatodos" href="'. site_url() .'/questions-modal/?action=create" title="' . __( 'Crear pregunta','buddypress' ) . '">';
				$links_content .= __('Crear pregunta','buddypress');
				$links_content .= '</a>';
			}
		}
		$links_content .= '</div>';
		?>

		<?php
		/*
		$list = get_posts( '&numberposts='. $instance['number'] .'&order=DESC&meta_key=_wp_page_type&meta_value=pregunta' );
		if (sizeof($list)>0) {

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

			foreach ($list as $post) {
				// Calcular estado de animo
				$class=calculate_moodbar( $post->post_author );
				?>

				<?php
				$main_content .= '<a class="iron-widget-title" href="'. $post->guid .'" title="'. $post->post_title .'">'. $post->post_title .'</a>';

				if ($instance['display_author'] == 1) {
					$main_content .= '<div class="irontec-widget-author">' . sprintf( __( 'por %s', 'buddypress' ), bp_core_get_userlink( $post->post_author ) );
					$main_content .= sprintf (__(' el %s','buddypress') , date ("d/m/Y", strtotime ($post->post_date)));
					$main_content .= '</div>';
				}
				?>

			<?php } ?>

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

		<?php }
		else {
			$main_content = '<div class="irontec-widget-padder" style="font-size: 10px;">';
			$main_content .= '<span class="nodata" style="font-size: 10px;">';
			$main_content .= 'No se han encontrado preguntas !';
			$main_content .= '</span>';
			$main_content .= '</div>';
		}
		*/

		global $wpdb;
		// Listado de amigos + el usuario actual
		$friend_list = bp_get_friend_ids( bp_loggedin_user_id() );
		$friend_list = $friend_list . ',' . bp_loggedin_user_id();
		$addquery="";

		// Estado de animo actual del usuario
		$current_state = xprofile_get_field_data( 'EstadoAnimo', bp_loggedin_user_id());

		if ($_GET['sc'] == 'mine') {
			$addquery= ' AND post_author='. bp_loggedin_user_id();

			$list = $wpdb->get_results("SELECT * FROM ". $wpdb->posts .", ".$wpdb->postmeta."
			WHERE ID=post_id AND post_type='post' AND post_status='publish' ".$addquery."
			AND meta_key='_wp_page_type' AND meta_value='pregunta'
			ORDER BY post_date DESC LIMIT 3");
		}
		else {
			// Aqui cogemos los publicos y los de nuestros amigos
			$list = $wpdb->get_results("SELECT p.* FROM ". $wpdb->posts ." p
			INNER JOIN ".$wpdb->postmeta." pm ON pm.post_id = p.ID AND pm.meta_key='_wp_page_type' AND pm.meta_value='pregunta'
			INNER JOIN ".$wpdb->postmeta." pm2 ON pm2.post_id = p.ID AND pm2.meta_key='iron-estado' AND pm2.meta_value='".$current_state."'
			WHERE p.post_type='post' AND p.post_status='publish' ORDER BY p.post_date DESC LIMIT 3");

			echo mysql_error();
		}

		if (sizeof($list)>0) {

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

			foreach ($list as $post) {
				$class=calculate_moodbar( $post->post_author );
				?>

				<?php
				$main_content .= '<a class="iron-widget-title" href="'. $post->guid .'" title="'. $post->post_title .'">'. $post->post_title .'</a>';

				if ($instance['display_author'] == 1) {
					$main_content .= '<div class="irontec-widget-author">';
					$main_content .= sprintf (__('por %s','buddypress') , bp_core_get_userlink( $post->post_author ));
					$main_content .= sprintf (__(' el %s','buddypress') , date ("d/m/Y", strtotime ($post->post_date)));
					$main_content .= '</div>';
				}
			}

			$main_content .= '</div>';
		}
		else {
			$main_content = '<div class="irontec-widget-padder" style="font-size: 10px;">';
			$main_content .= '<span class="nodata" style="font-size: 10px;">';
			$main_content .= __ ('No se han encontrado preguntas !', 'buddypress');
			$main_content .= '</span>';
			$main_content .= '</div>';
		}
		?>

		<?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['display_author'] = intval($new_instance['display_author']);
		$instance['display_links'] = strip_tags($new_instance['display_links']);
		$instance['display_showall'] = intval($new_instance['display_showall']);
		$instance['display_create'] = intval($new_instance['display_create']);
		$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']);
		$display_author = esc_attr($instance['display_author']);
		$display_links = esc_attr($instance['display_links']);
		$display_showall = esc_attr($instance['display_showall']);
		$display_create = esc_attr($instance['display_create']);
		$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 "Pregunta a todos"; ?>" />
        </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('display_author'); ?>"><?php _e('Display author ?'); ?></label>
          <input id="<?php echo $this->get_field_id('display_author'); ?>" name="<?php echo $this->get_field_name('display_author'); ?>" type="checkbox" value="1" <?php if ($display_author==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_PreguntaTodos_Widget");'));
?>
