<?php
$file = dirname(__FILE__);
$file = substr($file, 0, stripos($file, "wp-content") );
require( $file . "/wp-load.php");
global $wpdb;
global $current_user;
$user = $current_user->ID;
$profilepicture = $_FILES['profilepicture'];

if($profilepicture['size'] > 100000) {
	$respuesta = json_encode
    ( 
        array(
			'erras'     => true, 
			'mensaje' => 'error_image',
			'tamaño'  => $profilepicture['size'],
			'codigo'  => 2
        )
    );
	echo $respuesta;
	exit;

} else {
	if( $profilepicture['name'] != ''){
		$profilepicture['name'] = str_replace(' ', '_', $profilepicture['name']);
		$wordpress_upload_dir = wp_upload_dir();
		$i = 1; // number of tries when the file with the same name is already exists
		$new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
		$new_file_mime = mime_content_type( $profilepicture['tmp_name'] );
		if( empty( $profilepicture ) ){
			wp_redirect(bloginfo('url'));
		}
		if( $profilepicture['error'] ){
			wp_redirect(bloginfo('url'));
		}
		if( $profilepicture['size'] > wp_max_upload_size() )
			die( 'It is too large than expected.' );
		if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
			die( 'WordPress doesn\'t allow this type of uploads.' );
		while( file_exists( $new_file_path ) ) {
			$i++;
			$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
		}
		// looks like everything is OK
		
		if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
			$upload_id = wp_insert_attachment( array(
				'guid'           => $new_file_path, 
				'post_mime_type' => $new_file_mime,
				'post_title'     => preg_replace( '/\.[^.]+$/', '', $profilepicture['name'] ),
				'post_content'   => '',
				'post_status'    => 'inherit'
			), $new_file_path );
			// wp_generate_attachment_metadata() won't work if you do not include this file
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
			// Generate and save the attachment metas into the database
			wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
		 	$imaged =  $wordpress_upload_dir['url'] . '/' . basename( $new_file_path );
			$user_id = get_current_user_id();
			$imagen = get_user_meta($user_id, 'foto_back', true);
			if($imagen == null or $imagen == true) {
				update_user_meta( $user_id, 'foto_back', $imaged );
			} else {
				add_user_meta( $user_id , 'foto_back' , $imaged );
			}
		} 
		
	}
}
$description = $_POST['edit-user-perfil-description'];
$nacimiento = $_POST['edit-user-perfil-nacimiento'];
$pais = $_POST['edit-user-perfil-pais'];
#Se actualiza la descripcion
update_user_meta( $user, 'description', $description );
update_user_meta( $user, 'nacimiento', $nacimiento );
update_user_meta( $user, 'pais', $pais );



$respuesta = json_encode
    ( 
        array(
            'error' => $profilepicture['size'],
            'extension' => $new_file_mime,
        )
    );
echo $respuesta;