<?php if ( ! function_exists( 'ghostpool_gauge_update_database' ) ) {
	function ghostpool_gauge_update_database() {
	
		// If this is a new installation do not update the database 
		if ( ! get_option( 'gauge_db_version' ) ) {
			update_option( 'gauge_db_version', '1' ); // Update database version to latest version and then exit
			return;
		}
		
		/**
		 * Old updates
		 *
		 */	
		if ( get_option( 'ghostpool_v6_updated' ) !== '1' ) {

			global $wpdb;

			// Round up all _gp_user_rating field to 1 decimal place
			$wpdb->query( $wpdb->prepare( 
				"
					UPDATE $wpdb->postmeta SET meta_value = CEILING( meta_value * 10 ) / 10  WHERE meta_key = %s
				",
				'_gp_user_rating'
			) );
		
			update_option( 'ghostpool_v6_updated', '1' );

		}
		
		if ( get_option( 'ghostpool_v5_updated' ) !== '1' ) {
			
			global $wpdb;
	
			// Hub page Visual Composer spacing 
			$wpdb->query( $wpdb->prepare( 
				"
					UPDATE $wpdb->posts SET post_content = REPLACE ( post_content, %s, %s ) WHERE post_type = 'page'
				",
				'[/vc_column][vc_column width="5/12"]',
				'[vc_empty_space height="40px"][/vc_column][vc_column width="5/12"]'
			) );	
			$wpdb->query( $wpdb->prepare( 
				"
					UPDATE $wpdb->posts SET post_content = REPLACE ( post_content, %s, %s ) WHERE post_type = 'page'
				",
				'[/vc_column_inner][/vc_row_inner][vc_row_inner',
				'[/vc_column_inner][/vc_row_inner][vc_empty_space height="40px"][vc_row_inner'
			) );

			update_option( 'ghostpool_v5_updated', '1' );
			
		}
		
		/**
		 * Updating to v1.0
		 *
		 */	
		if ( version_compare( get_option( 'gauge_db_version' ), '1', '<' ) ) {

			global $wpdb;
			
			// Change sidebar option names
			 if ( get_option( 'cs_sidebars' ) ) { 
				add_option( 'ghostpool_sidebars', get_option( 'cs_sidebars' ) );
				delete_option( 'cs_sidebars' );
			}
			if ( get_option( 'cs_modifiable' ) ) { 
				add_option( 'ghostpool_modifiable', get_option( 'cs_modifiable' ) );
				delete_option( 'cs_modifiable' );
			}	
			$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->postmeta SET meta_key = %s WHERE meta_key = %s", '_ghostpool_replacements', '_cs_replacements' ) );
					
			update_option( 'gauge_db_version', '1' ); // remember to add this version to the top of page as well
																							
		}

	}	
}
add_action( 'init', 'ghostpool_gauge_update_database' );