<?php
/**
 * Template Name: Testimonios
 * Description: Testimonios
 **/

get_header("modals");

global $bp, $wpdb;

if ($_GET['action']=='create' || $_POST['action']=='create') {
    
    if ($_POST['confirm']== 1) {
        
        if ($_POST['content'] && $_POST['PageTitle']) {
            
            global $current_user;
            
            $postvars = array(
                            'post_title' => $_POST['PageTitle'],
                            'post_content' => $_POST['content'],
                            'post_status' => 'publish',
                            'post_author' => $current_user->ID,
                            'post_date' => current_time('mysql'),
                            'post_date_gmt' => get_gmt_from_date(current_time('mysql')),
                            'post_type' => 'post',
                            'comment_status' => 'open',
                            'ping_status' => 'open'
            );
                
           if ($newid = wp_insert_post( $postvars )) {
               
               if ($_POST['PageTemplate'] == 1) {
                   add_post_meta($newid, '_wp_page_template', 'default');
               }
               
               // Obtenemos el estado de animo y la privacidad
               $iron_estado    = xprofile_get_field_data('EstadoAnimo', bp_loggedin_user_id());
               $iron_privacity = $_POST['activity-privacity'];
               add_post_meta($newid, 'iron-estado', $iron_estado);
               add_post_meta($newid, 'iron-privacity', $iron_privacity);
               add_post_meta($newid, '_wp_page_type', 'testimonio');
                
               // Obtenemos el id del activity update
               $table_name   = $wpdb->prefix . "bp_activity";
               $querySelActi = "SELECT id FROM ".$table_name." WHERE type='new_blog_post' AND secondary_item_id= ". $newid." LIMIT 1";
               $results      = $wpdb->get_results( $querySelActi );
               $newact       = $results[0]->id;
                
                /**
                 * Guardar activity_meta
                 * Estado de animo del usuario en el momento del post
                 */
                if ($newact) {
                    $table_name = $wpdb->prefix . "bp_activity_meta";
                    $meta_key   = "current_mood";
                    $meta_value = xprofile_get_field_data( 'EstadoAnimo', get_current_user_id());
                    $insetActiv = 'INSERT INTO '.$table_name.' (activity_id, meta_key, meta_value) VALUES ('.$newact.', "'.$meta_key.'", "'.$meta_value.'")';
                    $wpdb->query($insetActiv);
                }
                
                /**
                 * dani - irontec - quitar hitos
                 **/ 
                /*
                // Otorgar Hitos
                $table2                  = $wpdb->prefix . 'achievements';
                $table3                  = $wpdb->prefix . 'achievements_unlocked';
                $achievement_slug_bronce = 'testimonios-bronce';
                $achievement_slug_plata  = 'testimonios-plata';
                $achievement_slug_oro    = 'testimonios-oro';

                // Contamos el nº de testimonios que tiene publicados
                $queryNTestPub = "SELECT COUNT(DISTINCT ID) as counter FROM ". $wpdb->posts .", ". $wpdb->postmeta ." WHERE post_status='publish' AND meta_value='testimonio' AND ID=post_id AND post_author=".bp_loggedin_user_id();
                $res = $wpdb->get_results( $queryNTestPub );
            
                // Obtener los id de los hitos
                $hito_bronce_id = $wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_bronce."'");
                $hito_plata_id  = $wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_plata."'");
                $hito_oro_id    = $wpdb->get_results("SELECT id FROM ".$table2." WHERE slug='".$achievement_slug_oro."'");

                // Si tiene 15 testimonios, bronce
                if ($res[0]->counter >= 5 && $res[0]->counter < 10) {
                    // Otorgar hito
                    $res   = dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_bronce );
                } elseif ($res[0]->counter >= 10 && $res[0]->counter < 15) {
                    // Eliminar testimonios-bronce
                    $table = $wpdb->prefix . 'achievements_unlocked';
                    $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
                    // Otorgar hito
                    $res   = dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_plata );
                } elseif ($res[0]->counter >= 15) {
                    // Eliminar hito bronce
                    $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_bronce_id[0]->id);
                    // Eliminar hito plata
                    $wpdb->query("DELETE FROM ".$table3." WHERE user_id=" . bp_loggedin_user_id()." AND achievement_id=". $hito_plata_id[0]->id);
                    // Otorgar hito
                    $res   = dpa_force_unlock_achievement( bp_loggedin_user_id(), $achievement_slug_oro );
                }
                */
                   $result_msg  = '<div class="updated" id="message" style="margin-bottom: 10px;">';
                   $result_msg .= '<p>'. __ ('El Testimonio se ha guardado correctamente.','buddypress') .'</p>';
                   $result_msg .= '</div>';
                   $result_msg .= '<div style="float: right; margin-top: 14px; margin-right: 10px;">';
                   $result_msg .= '<a class="button" href="#" onclick="parent.jQuery.fancybox.close();">';
                   $result_msg .= __('Finalizar','buddypress') .'</a>';
                   $result_msg .= '</div>';
           } else {
                   
                   $result_msg  = '<div class="error" id="message" style="margin-bottom: 10px;">';
                   $result_msg .= '<p>'. __ ('Ha ocurrido un error al guardar.','buddypress') .'</p>';
                   $result_msg .= '</div>';
                   $result_msg .= '<div style="float: right; margin-top: 14px; margin-right: 10px;">';
                   $result_msg .= '<a class="button" href="#" onclick="parent.jQuery.fancybox.close();">';
                   $result_msg .= __('Finalizar','buddypress') .'</a>';
                   $result_msg .= '</div>';
           }
        } else {
               $result_msg  = '<div class="error" id="message" style="margin-bottom: 10px;">';
               $result_msg .= '<p>'. __ ('Ha ocurrido un error al guardar.','buddypress') .'</p>';
               $result_msg .= '</div>';
               $result_msg .= '<div style="float: right; margin-top: 14px; margin-right: 10px;">';
               $result_msg .= '<a class="button" href="#" onclick="parent.jQuery.fancybox.close();">';
               $result_msg .= __('Finalizar','buddypress') .'</a>';
               $result_msg .= '</div>';
        }
        
        if ($result_msg) {
            echo $result_msg;
            exit ();
        }
    }
    ?>
    <form method="post" id="bp-group-documents-form" class="standard-form" action="<?php echo site_url() . '/testimonies-modal'; ?>" />
    
        <label>
            <?php _e('T&iacute;tulo del testimonio','buddypress'); ?>
        </label>
        <input type="text" maxlength="200" style="width: 550px;" name="PageTitle">
        
        <label>
            <?php _e('Selecciona con qui&eacute;n quieres compartirlo','buddypress'); ?>
        </label>
        <select name="activity-privacity">
            <option value="amigos">
                <?php _e( 'con mis amigos', 'buddypress') ?>
            </option>
            <option value="publico" selected>
                <?php _e( 'con toda la comunidad', 'buddypress') ?>
            </option>
        </select>
        
        <?php 
        /** Load WordPress Administration Bootstrap */
        //the_editor( $content, $id = 'content', $prev_id = 'title', $media_buttons = true, $tab_index = 2, $extended = true);
        wp_editor( $content, $id = 'content', array( 'media_buttons' => $media_buttons ) );
        ?>
        
        <div style="float: right; margin-top: 14px; margin-right: 10px;">
            <a class="button" href="#" onclick="parent.jQuery.fancybox.close();"><?php _e('Cancelar','buddypress'); ?></a>
        </div>
        
        <?php if ($result_msg) { ?>
            <div style="position: absolute; margin-left: 230px; margin-top: -10px; width: 405px;">
                <?php echo $result_msg; ?>
            </div>
        <?php } ?>
        
        <div>
            <input style="height: 32px; margin-top: 10px; font-size: 20px; padding-top: 0px; color: #000000;" type="submit" class="button" value="<?php _e('Compartir Testimonio','buddypress'); ?> &rarr;" />
        </div>
        
        <input type="hidden" name="confirm" value="1">
        <input type="hidden" name="action" value="create">
        
    </form>
    
<?php
} elseif ($_GET['action'] == 'update' || $_POST['action'] == 'update') {
        
    if ($_GET['id']) {
        $postdata = get_post($_GET['id']);
    } else {
        $postdata = get_post($_POST['id']);
    }
    
    $priv = get_post_meta($postdata->ID, 'iron-privacity');
    
    if ($_POST['confirm']=="1") {
        global $current_user;
        
        $postvars = array(
                         'ID'            => $postdata->ID,
                         'post_title'    => $_POST['PageTitle'],
                         'post_content'  => $_POST['content']
                        );
        
        if (wp_update_post($postvars)) {
            // Actualizamos la privacidad
            update_post_meta($postdata->ID, 'iron-privacity',$_POST['activity-privacity']);
            
            $result_msg  = '<div class="updated" id="message" style="margin-bottom: 10px;">';
            $result_msg .= '<p>'. __ ('El Testimonio se ha actualizado.','buddypress') .'</p>';
            $result_msg .= '</div>';
            $result_msg .= '<div style="float: right; margin-top: 14px; margin-right: 10px;">';
            $result_msg .= '<a class="button" href="#" onclick="parent.jQuery.fancybox.close();">';
            $result_msg .= __('Finalizar','buddypress') .'</a>';
            $result_msg .= '</div>';
        } else {
            $result_msg  = '<div class="error" id="message" style="margin-bottom: 10px;">';
            $result_msg .= '<p>'. __ ('Ha ocurrido un error al guardar.','buddypress') .'</p>';
            $result_msg .= '</div>';
            $result_msg .= '<div style="float: right; margin-top: 14px; margin-right: 10px;">';
            $result_msg .= '<a class="button" href="#" onclick="parent.jQuery.fancybox.close();">';
            $result_msg .= __('Finalizar','buddypress') .'</a>';
            $result_msg .= '</div>';
        }
        
        if ($result_msg) {
            echo $result_msg;
            exit();
        }
    }
    ?>
    <form method="post" id="bp-group-documents-form" class="standard-form" action="<?php echo site_url() . '/testimonies-modal'; ?>" />
        <div class="custom-wiki-div">
            <div>
            
                <label>
                    <?php _e('T&iacute;tulo del testimonio','buddypress'); ?>
                </label>
                <input type="text" maxlength="200" style="width: 550px;" name="PageTitle" value="<?php echo $postdata->post_title; ?>">
                
                <label>
                    <?php _e('Selecciona con qui&eacute;n quieres compartirlo','buddypress'); ?>
                </label>
                
                <select name="activity-privacity">
                    <?php
                    if ($priv[0] == 'amigos') {
                        echo '<option value="amigos" selected>'.__( 'con mis amigos', 'buddypress') .'</option>';
                        echo '<option value="publico">'.__( 'con toda la comunidad', 'buddypress').'</option>';
                    }
                    elseif ($priv[0] == 'publico') {
                        echo '<option value="amigos">'.__( 'con mis amigos', 'buddypress') .'</option>';
                        echo '<option value="publico" selected>'.__( 'con toda la comunidad', 'buddypress').'</option>';
                    }
                    else {
                        echo '<option value="amigos">'.__( 'con mis amigos', 'buddypress') .'</option>';
                        echo '<option value="publico" selected>'.__( 'con toda la comunidad', 'buddypress').'</option>';
                    }
                    ?>
                </select>
                
                <label>
                    <?php _e('Contenido','buddypress'); ?>
                </label>
                
                <?php 
                /** Load WordPress Administration Bootstrap */
                the_editor( $postdata->post_content, $id = 'content', $prev_id = 'title', $media_buttons = true, $tab_index = 2 );
                ?>
            </div>
            
            <div style="float: right; margin-top: 14px; margin-right: 10px;">
                <a class="button" href="#" onclick="parent.jQuery.fancybox.close();"><?php _e('Cancelar','buddypress'); ?></a>
            </div>
            
            <?php if ($result_msg) { ?>
                <div style="position: absolute; margin-left: 230px; margin-top: -10px; width: 405px;">
                    <?php echo $result_msg; ?>
                </div>
            <?php } ?>
            
            <div>
                <input style="margin-top: 10px; font-size: 20px; padding-top: 0px; color: #000000;" type="submit" class="button" value="<?php _e('Actualizar','buddypress'); ?> &rarr;" />
            </div>
            <input type="hidden" name="confirm" value="1">
            <input type="hidden" name="action" value="update">

            <input type="hidden" name="id" value="<?php echo $postdata->ID; ?>">
            
        </div> <!-- .custom-wiki-div -->
    </form>
<?php
} elseif ($_GET['action']=='delete' && $_GET['id']) {
    
    if ($_GET['id']) {
        $postdata = get_post($_GET['id']);
    } else {
        $postdata = get_post($_POST['id']);
    }

    // Comprobamos que sea el autor
    if ($postdata->post_author == get_current_user_id()) {
        
        /**
         * se eliminan todas las notificaciones relacionadas con este post (testimonio)
         */
        $wpdb->delete( 'wp_bp_notifications', array( 'item_id' => $postdata->ID, 'component_name' => 'iron_notifier', 'component_action' => 'new_blog_comment_'.$postdata->ID ) );
        
        wp_delete_post( $postdata->ID );
        header( 'Location: ' . bp_loggedin_user_domain() . 'testimonies/' ) ;
    }
}
require_once(dirname(__FILE__) . '/includesEditor/headers.php');
?>
</body>
</html>