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

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
                $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', 'pregunta');
                
                // Obtenemos el id del activity update
                $table_name = $wpdb->prefix . "bp_activity";
                $results    = $wpdb->get_results("SELECT id FROM ".$table_name." WHERE type='new_blog_post' AND secondary_item_id= ". $newid." LIMIT 1");
                $newact = $results[0]->id;
                
                // Guardar activity_meta
                if ($newact) {
                    // Estado de animo del usuario en el momento del post
                    $table_name = $wpdb->prefix . "bp_activity_meta";
                    $meta_key   = "current_mood";
                    $meta_value = xprofile_get_field_data( 'EstadoAnimo', get_current_user_id());
                    $wpdb->query('INSERT INTO '.$table_name.' (activity_id, meta_key, meta_value) VALUES ('.$newact.', "'.$meta_key.'", "'.$meta_value.'")');
                }
                
                $result_msg = '<div class="updated" id="message" style="margin-bottom: 10px;">';
                $result_msg .= '<p>'. __ ('La pregunta se ha guardado.', '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 action="<?php echo site_url() . '/questions-modal'; ?>" method="POST" id="bp-group-documents-form" class="standard-form">
    
        <label>
            <?php _e('T&iacute;tulo de la pregunta','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 );
        ?>
        
        <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 Pregunta','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>'. __ ('La pregunta 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 action="<?php echo site_url() . '/questions-modal'; ?>" method="POST" id="bp-group-documents-form" class="standard-form" >
        <div class="custom-wiki-div">
            <div>
            
                <label>
                    <?php _e('T&iacute;tulo de la pregunta','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>';
                    //echo '<option value="privado">s&oacute;lo para m&iacute;</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>';
                    //echo '<option value="privado">s&oacute;lo para m&iacute;</option>';
                }
                else {
                    echo '<option value="amigos">'.__( 'con mis amigos', 'buddypress') .'</option>';
                    echo '<option value="publico" selected>'.__( 'con toda la comunidad', 'buddypress').'</option>';
                    //echo '<option value="privado">s&oacute;lo para m&iacute;</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() . 'questions/' ) ;
    }
}

require_once(dirname(__FILE__) . '/includesEditor/headers.php');

?>
</body>
</html>