<?php
/**
 * Plugin Name: Irontec - Testimonies
 * Plugin URI: http://www.irontec.com
 * Description: This plugin allows to add testimonies to your site in the form of blog posts.
 * 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: TESTIMONIES-MODAL
 */
if ( !defined( 'BP_IRON_TESTIMONIESMODAL_SLUG' ) ) define( 'BP_IRON_TESTIMONIESMODAL_SLUG', 'testimonies-modal' );
function my_setup_root_iron_testimoniesmodal () {
    bp_core_add_root_component( BP_IRON_TESTIMONIESMODAL_SLUG );
}
add_action( 'bp_setup_root_components', 'my_setup_root_iron_testimoniesmodal' );

function my_action_iron_testimoniesmodal() {
    global $bp;
    
    if ( $bp->current_component == BP_IRON_TESTIMONIESMODAL_SLUG ) {
        do_action( 'my_action_iron_testimoniesmodal' );
        bp_core_load_template( apply_filters( 'bp_core_template_iron_testimonios_modal', 'testimonies-modal/index' ) );
    }
}
add_action( 'wp', 'my_action_iron_testimoniesmodal', 1 );

/**
 * DEFINIMOS SLUG: TESTIMONIES
 */
if ( !defined( 'BP_IRON_TESTIMONIES_SLUG' ) ) define( 'BP_IRON_TESTIMONIES_SLUG', 'testimonies' );
function my_setup_root_iron_testimonies () {
    bp_core_add_root_component( BP_IRON_TESTIMONIES_SLUG );
}
add_action( 'bp_setup_root_components', 'my_setup_root_iron_testimonies' );

function my_action_iron_testimonies() {
    global $bp;
    
    if ( $bp->current_component == BP_IRON_TESTIMONIES_SLUG ) {
        do_action( 'my_action_iron_testimonies' );
        bp_core_load_template( apply_filters( 'bp_core_template_iron_testimonios', 'testimonies/index' ) );
    }
}
add_action( 'wp', 'my_action_iron_testimonies', 1 );

/**
 * Definimos la clase
 */
class Irontec_Testimonies_Widget extends WP_Widget {
    
    /**
     * constructor
     */
    function Irontec_Testimonies_Widget() {
        parent::WP_Widget(false, $name = 'Irontec Testimonies');
    }
    
    /**
     * @see WP_Widget::widget
     */
    function widget($args, $instance) {
        global $bp;
        extract( $args );
        
        echo $before_widget;
        
        /**
         * change the title
         */
        $title = apply_filters('widget_title', $instance['title']);
        
        if ( $title ) {
            $before_title = str_replace ('widgettitle','widgettitle testimonies', $before_title);
            echo $before_title;
            echo '<a href="'. bp_loggedin_user_domain() .'testimonies" title="'. __('Testimonios','buddypress') .'">';
            _e('Testimonios','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() .'testimonies" 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-testimonies" href="'. site_url() .'/testimonies-modal/?action=create" title="' . __ ('Crear testimonio','buddypress') . '">';
                $links_content .= __ ('Crear testimonio','buddypress');
                $links_content .= '</a>';
            }
        }
        
        $links_content .= '</div>';
        
        /*
        $list = get_posts( '&numberposts='. $instance['number'] .'&order=DESC&meta_key=_wp_page_type&meta_value=testimonio' );
        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">';
                    $main_content .= sprintf (__('por %s','buddypress') , bp_core_get_userlink( $post->post_author )) . '</div>';
                }
                ?>

            <?php } ?>

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

        <?php }
        */
        
        global $wpdb;
        /**
         * Listado de amigos + el usuario actual
         */
        $friend_list = bp_get_friend_ids( bp_loggedin_user_id() );
        if ($friend_list) {
            $friend_list = $friend_list . ',' . bp_loggedin_user_id();
        } else {
            $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='testimonio'
            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='testimonio'
            INNER JOIN ".$wpdb->postmeta." pm2 ON pm2.post_id = p.ID AND pm2.meta_key='iron-estado' AND pm2.meta_value='".$current_state."'
            INNER JOIN ".$wpdb->postmeta." pmm ON pmm.post_id = p.ID AND pmm.meta_key='iron-privacity' AND
            (pmm.meta_value='publico' OR (pmm.meta_value='amigos' AND p.post_author IN (". $friend_list.")))
            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 );
                
                $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 testimonios.', 'buddypress');
            $main_content .= '</span>';
            $main_content .= '</div>';
        }
        
        // Display the content
        if ($instance['links_valign'] == "top") {
            echo $links_content . $main_content;
        } else {
            echo $main_content . $links_content;
        }
        
        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 "Testimonies"; ?>" />
        </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_Testimonies_Widget");'));
?>