<?php

/**
 * Querystring is set via AJAX in _inc/ajax.php - bp_dtheme_activity_loop() 
 **/ 

do_action( 'bp_before_activity_loop' );

global $wpdb, $bp, $current_user;

/**
 * Obtenemos el valor de sc (scope) de los enlaces ( Solo yo, Mis amigos, etc. )
 * filter, que viene dado de los botones de colores
 * establecemos el type a activity_update para mostrar solo textos
 * $querypags, num de elementos por pag
 **/

$sc     = check_scFilterMuro($_GET['sc']);
$filter = check_ironEstadoFilterMuro(esc_attr($_POST['IronEstadoFilter']),esc_attr($_GET['IronEstadoFilter']));

$type  = 'activity_update';
$type2 = 'new_blog_post';
$type3 = 'friendship_created';
$type4 = 'created_event';
$type5 = 'created_group';
//$type2 = 'new_blog_post';

/**
 * dani - irontec - quitar hitos
 * no salen en el entry.php
 **/ 
//$type6 = 'new_achievement';

$querypags   = '&per_page=10';
$friend_list = bp_get_friend_ids( bp_loggedin_user_id() );

if (!$friend_list) {
    $friend_list = bp_loggedin_user_id();
}

$afriend_list = explode (',', $friend_list);

/*
echo "comp: ".$bp->current_component;
echo "act: ".$bp->current_action;
*/

/**
 * tablas de la bbdd
 **/
$tablename1 = $wpdb->prefix . "bp_activity";
$tablename2 = $wpdb->prefix . "bp_activity_meta";

/**
 * Si estamos en grupos, mostramos solo los items del grupo
 **/
if ($bp->current_component == 'groups') {
    $addquery1 = " AND type='activity_update' AND item_id = ".bp_get_group_id();
} elseif ($bp->current_action == 'just-me') {
    $addquery1 = " AND user_id = ".bp_displayed_user_id();
}

/**
 * Scope
 **/
if ($sc == 'groups') {
    $addquery2 = " AND type='activity_update' AND item_id != 0 ";
} elseif ($sc == 'personal') {
    $addquery2 = " AND user_id = ". bp_loggedin_user_id();
}  elseif ($sc == 'friends') {
    $friend_list .= ',' . bp_loggedin_user_id();
    $addquery2    = " AND user_id IN (". $friend_list .")";
}

/**
 * Consulta SQL
 * Si ponemos secondary_item_id = 0 va a coger solo posts, no los comentarios
 **/

/**
 * @author dani -irontec
 * @incidencia 30392
 */
if ($sc != 'groups') {
    $queryPreguntas   = "select wba.id, wba.user_id, wba.item_id, wba.secondary_item_id, wba.type from wp_posts as wpp inner join wp_postmeta as wppm on wpp.ID = wppm.post_id inner join wp_bp_activity as wba on wpp.ID = wba.secondary_item_id and wba.type='new_blog_post' where wppm.meta_value = 'pregunta'   ORDER BY wpp.post_date DESC LIMIT 1";
    $queryTestimonios = "select wba.id, wba.user_id, wba.item_id, wba.secondary_item_id, wba.type from wp_posts as wpp inner join wp_postmeta as wppm on wpp.ID = wppm.post_id inner join wp_bp_activity as wba on wpp.ID = wba.secondary_item_id and wba.type='new_blog_post' where wppm.meta_value = 'testimonio' ORDER BY wpp.post_date DESC LIMIT 1";
    $queryEventos     = "select wp_bp_activity.id, wp_bp_activity.user_id, wp_bp_activity.item_id, wp_bp_activity.secondary_item_id, wp_bp_activity.type from wp_jet_events inner join wp_bp_activity on wp_jet_events.id = wp_bp_activity.item_id and type='created_event' where FROM_UNIXTIME(edtedunix) > NOW() ORDER BY date_recorded DESC LIMIT 1";
    
    $preguntaTRUE = reset($wpdb->get_results($wpdb->prepare($queryPreguntas)));
    if ($preguntaTRUE) {
        $firtView[] = $preguntaTRUE;
    }
    
    $testimonioTRUE = reset($wpdb->get_results($wpdb->prepare($queryTestimonios)));
    if ($testimonioTRUE) {
        $firtView[] = $testimonioTRUE;
    }
    
    $eventoTRUE = reset($wpdb->get_results($wpdb->prepare($queryEventos)));
    if ($eventoTRUE) {
        $firtView[] = $eventoTRUE;
    }
    
    if ($firtView) {
        foreach ($firtView as $vals) {
            if ($vals) {
                $notIdsRepeat[] = $vals->id;
            }
        }
    }
}

if ($notIdsRepeat) {
    $addquery3 = ' AND id NOT IN (' . implode(',', $notIdsRepeat) . ') ';
}

$actQuery  = "SELECT id, user_id, item_id, secondary_item_id, type FROM " . $tablename1 . " WHERE ((type='" . $type . "' AND secondary_item_id = 0) ";
$actQuery .= " OR type='". $type2 ."' ";
//$actQuery.=" OR type='". $type3 ."' ";
$actQuery .= " OR type='".$type4."' ";
$actQuery .= " OR type='".$type5."' ";
$actQuery .= " OR type='".$type6."' and item_id != '0')" . $addquery1 . $addquery2 . $addquery3 . " ";
$actQuery .= " ORDER BY date_recorded DESC";

$resutlActQuery = $wpdb->get_results($actQuery);

$list = $resutlActQuery;
/*
echo "SELECT id, user_id, item_id FROM ".$tablename1."
WHERE ((type='". $type ."' AND secondary_item_id = 0) OR type='". $type2 ."' OR type='". $type3 ."' OR type='".$type4."')".$addquery1.$addquery2."
ORDER BY date_recorded DESC";
*/

/**
 * Confeccionamos la includelist de ids separados por coma
 * La chapuza del cont es para guardar el valor del activity anterior
 * usando el viejo truco de par/impar xD
 **/

$cont = 0;

foreach ($list as $item) {
    
    $current_mood = '';
    $privacity    ='';
    $queryitem    = "SELECT meta_key, meta_value FROM ".$tablename2." WHERE activity_id = ". $item->id;
    $results      = $wpdb->get_results( $queryitem );
    
    /**
     * Esto sirve para coger las meta privacity y current_mood
     **/
    foreach ($results as $metaval) {
        if ($metaval->meta_key == 'privacity') {
            $privacity = $metaval->meta_value;
        } elseif ($metaval->meta_key == 'current_mood') {
            $current_mood = $metaval->meta_value;
        }
    }
    
    /**
     * debug
     */
    /*
    if ($item->user_id == $ant_secondary_item_id && $item->secondary_item_id == $ant_user_id) { echo '!!'; }
    echo '<br /><b>este</b> -> user_id: '.$item->user_id.' sec_id: '. $item->secondary_item_id.' <b>ant</b> ->  user_id: ' . $ant_user_id . ' sec_id: ' . $ant_secondary_item_id;
    */
    
    /**
     * Si no es privado, miramos si es solo para amigos y el filtro por estado
     **/
    if ($privacity != 'privado') {
        
        /**
         * Solo para amigos
         **/
        if ($privacity == 'amigos') {
            
            if (in_array($item->user_id, $afriend_list) || $item->user_id == bp_loggedin_user_id()) {
                
                /**
                 * Filtro por estado (bolitas)
                 **/
                if ($filter && $current_mood == $filter) {
                    
                    /**
                     * Quitamos los new_friendship repetidos
                     **/ 
                    if ($item->type == 'friendship_created') {
                        
                        if ($item->user_id != $ant_secondary_item_id && $item->secondary_item_id != $ant_user_id) {
                            
                            /**
                             * Los usuarios que esten como privados no ven esto
                             **/
                            if (!check_private_profile(bp_loggedin_user_id())) {
                                $includelist .= $item->id.",";
                            }
                        }
                    } elseif (
                                $item->type == 'created_group'   ||
                                $item->type == 'created_event'   ||
                                $item->type == 'new_blog_post'   ||
                                $item->type == 'new_achievement'
                              ) {
                      
                    /**
                     * SI SON CREACIONES DE GRUPOS, EVENTOS, TESTIMONIOS, ETC. MOSTRAMOS
                     * SOLO LOS DE NUESTROS AMIGOS y LO NUESTRO, A PESAR DE ESTAR EN "TODOS"
                     **/
                        if (in_array($item->user_id, $afriend_list) || $item->user_id == bp_loggedin_user_id()) {
                            if (!check_private_profile(bp_loggedin_user_id())) {
                                $includelist .= $item->id.",";
                            }
                        }
                    } else {
                        $includelist .= $item->id.",";
                    }
                } elseif (!$filter) {
                    /**
                     * Sin filtro por estado (bolitas)
                     * Quitamos los new_friendship repetidos
                     **/
                    if ($item->type=='friendship_created') {
                        if ($item->user_id != $ant_secondary_item_id && $item->secondary_item_id != $ant_user_id) {
                            /**
                             * Los usuarios que esten como privados no ven esto
                             **/
                            if (!check_private_profile(bp_loggedin_user_id())) {
                                $includelist .= $item->id.",";
                            }
                        }
                    } elseif (
                                $item->type == 'created_group' ||
                                $item->type == 'created_event' ||
                                $item->type == 'new_blog_post' ||
                                $item->type == 'new_achievement'
                              ) {
                        /**
                         * SI SON CREACIONES DE GRUPOS, EVENTOS, TESTIMONIOS, ETC. MOSTRAMOS
                         * SOLO LOS DE NUESTROS AMIGOS y LO NUESTRO, A PESAR DE ESTAR EN "TODOS"
                         **/
                        if (in_array($item->user_id, $afriend_list) || $item->user_id == bp_loggedin_user_id()) {
                            /**
                             * Los usuarios que esten como privados no ven esto
                             **/
                            if (!check_private_profile(bp_loggedin_user_id())) {
                                $includelist .= $item->id.",";
                            }
                        }
                    } else {
                        $includelist .= $item->id.",";
                    }
                }
            }
        } else {
            /**
             * Filtro por estado (bolitas)
             **/
            if ($filter && $current_mood == $filter) {
                /**
                 * Quitamos los new_friendship repetidos
                 **/
                if ($item->type=='friendship_created') {
                    if ($item->user_id != $ant_secondary_item_id && $item->secondary_item_id != $ant_user_id) {
                        /**
                         * Los usuarios que esten como privados no ven esto
                         **/
                        if (!check_private_profile(bp_loggedin_user_id())) {
                            $includelist .= $item->id.",";
                        }
                    }
                } elseif (
                            $item->type == 'created_group'   ||
                            $item->type == 'created_event'   ||
                            $item->type == 'new_blog_post'   ||
                            $item->type == 'new_achievement'
                         ) {
                    /**
                     * SI SON CREACIONES DE GRUPOS, EVENTOS, TESTIMONIOS, ETC. MOSTRAMOS
                     * SOLO LOS DE NUESTROS AMIGOS y LO NUESTRO, A PESAR DE ESTAR EN "TODOS"
                     **/
                    if (in_array($item->user_id, $afriend_list) || $item->user_id == bp_loggedin_user_id()) {
                        
                        /**
                         * Los usuarios que esten como privados no ven esto
                         **/
                        if (!check_private_profile(bp_loggedin_user_id())) {
                            
                            $includelist .= $item->id.",";
                        }
                    }
                } else {
                    
                    $includelist .= $item->id.",";
                }
                
            } elseif (!$filter) {
                
                /**
                 * Sin filtro por estado (bolitas)
                 * Quitamos los new_friendship repetidos
                 **/
                if ($item->type=='friendship_created') {
                    
                    if ($item->user_id != $ant_secondary_item_id && $item->secondary_item_id != $ant_user_id) {
                        /**
                         * Los usuarios que esten como privados no ven esto
                         **/
                        if (!check_private_profile(bp_loggedin_user_id())) {
                            $includelist .= $item->id.",";
                        }
                    }
                } elseif (
                            $item->type == 'created_group' ||
                            $item->type == 'created_event' ||
                            $item->type == 'new_blog_post' ||
                            $item->type == 'new_achievement'
                         ) {
                    /**
                     * SI SON CREACIONES DE GRUPOS, EVENTOS, TESTIMONIOS, ETC. MOSTRAMOS
                     * SOLO LOS DE NUESTROS AMIGOS y LO NUESTRO, A PESAR DE ESTAR EN "TODOS"
                     **/
                    if (in_array($item->user_id, $afriend_list) || $item->user_id == bp_loggedin_user_id()) {
                        
                        /**
                         * Los usuarios que esten como privados no ven esto
                         **/
                        if (!check_private_profile(bp_loggedin_user_id())) {
                            
                            $includelist .= $item->id.",";
                        }
                    }
                } else {
                    
                    $includelist .= $item->id.",";
                }
            }
        }
    } elseif ( $privacity == 'privado' && $item->user_id == bp_loggedin_user_id() ) {
        /**
         * Si es privado, el autor del post lo puede ver
         * En version beta esta feature no se usa
         * Filtro por estado
         **/ 
        if ($filter && $current_mood == $filter) {
            $includelist .= $item->id.",";
        }
        elseif (!$filter) {
            $includelist .= $item->id.",";
        }
    }
    
    /**
     * Si es impar recogemos el valor
     * para poder compararlo despues
     **/
    $cont++;
    
    if ($cont%2!=0) {
        
        $ant_user_id           = $item->user_id;
        $ant_secondary_item_id = $item->secondary_item_id;
    } else {
        $ant_user_id           = '';
        $ant_secondary_item_id = '';
    }
}

/**
 * Por defecto no incluimos nada (cuando un usuario no tiene amigos ni updates hechos,
 * tenemos que pasar siempre algún id por include, sino mostraré la activity completa)
 **/
$queryinc     = '&include=-1';

/**
 * Quitamos la ultima coma del listado
 **/ 

$includelist  = substr($includelist,0,strlen($includelist)-1);

/**
 * Pasamos el includelist a la consulta bp_has_activities
 * asi wordpress se ocupa de todo lo demas, como la paginacion
 **/
if ($includelist) {
    
    if ($notIdsRepeat) {
        $queryinc = '&include=' . implode(',', $notIdsRepeat) . ',' .$includelist;
    } else {
        $queryinc = '&include=' . $includelist;
    }
}

if ( bp_has_activities( bp_ajax_querystring( 'activity' ) . $queryscope . $queryinc . $querypags . $queryaction ) ) {
    
    /**
     * Show pagination if JS is not enabled, since the "Load More" link will do nothing
     */
    ?>
    <noscript>
        <div class="pagination">
            <div class="pag-count"><?php bp_activity_pagination_count() ?></div>
            <div class="pagination-links"><?php bp_activity_pagination_links() ?></div>
        </div>
    </noscript>
    
    <?php
    if ( empty( $_POST['page'] ) ) {
        ?>
        <ul id="activity-stream" class="activity-list item-list">
        <?php
    }
    
    while ( bp_activities() ) : bp_the_activity();
        
        include( locate_template( array( 'activity/entry.php' ), false ) );
        
    endwhile;
    
    if ( bp_get_activity_count() == bp_get_activity_per_page() ) {
    ?>
        <li class="load-more">
            <img src="<?php echo get_stylesheet_directory_uri() .'/_inc/images/down-arrow.gif'; ?>">
            <a href="#more"><?php _e( 'Load More', 'buddypress' ) ?></a> &nbsp; <span class="ajax-loader"></span>
        </li>
    <?php
    }
    
    if ( empty( $_POST['page'] ) ) {
    ?>
        </ul>
    <?php
    }
    
} else {
    ?>
    <div id="message" class="info">
        <p><?php _e( 'No se ha encontrado nada, prueba una b&uacute;squeda diferente.', 'buddypress' ) ?></p>
    </div>
<?php
} 

do_action( 'bp_after_activity_loop' );

?>

<form action="" name="activity-loop-form" id="activity-loop-form" method="post">
    <?php wp_nonce_field( 'activity_filter', '_wpnonce_activity_filter' ) ?>
    <input type="hidden" name="sc" value="<?php echo $_GET['sc']; ?>">
</form>