<?php 
/**
 * Plugin Name: Mipro Importer
 * Plugin URI: http://alura-studio.com
 * Description: Import demo content Mipro theme
 * Version: 1.1.0
 * Author: Alura Studio
 * Author URI: http://alura-studio.com
 */

if( !class_exists('Mipro_Importer') ) {

	class Mipro_Importer {

		function __construct() {
			
			add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
			add_action('admin_menu', array($this, 'menu_page'));

			add_action( 'wp_ajax_mipro_import_revslider', array($this, 'import_revslider') );
			add_action( 'wp_ajax_mipro_import_theme_options', array($this, 'import_theme_options') );
			add_action( 'wp_ajax_mipro_import_widget', array($this, 'import_widget') );
			add_action( 'wp_ajax_mipro_import_config', array($this, 'import_config') );
			add_action( 'wp_ajax_mipro_import_content', array($this, 'import_content') );
		}
		
		function enqueue_scripts() {

			wp_enqueue_style( 'mipro-import-style', plugins_url( '/assets/style.css', __FILE__ ) );
			wp_register_script( 'mipro-import-script', plugins_url( '/assets/import.js', __FILE__ ), array( 'jquery' ), false, true );
		}
		
		function menu_page() {

			add_menu_page( 'Import Demo Data', 'Dummy Content', 'switch_themes', 'mipro_importer', array($this, 'import_demo_content'), '', 61);
		}
		
		function import_demo_content() {

			wp_enqueue_script( 'mipro-import-script' );
			?>

			<div id="mipro-importer" class="wrap about-wrap">
				<h1>Mipro - Import Demo Data</h1>
				<div class="about-text">Thank you for purchasing our premium eCommerce theme</div>
				<p>
					<a href="http://alura-studio.com" target="_blank" class="button button-primary button-large">Document</a>
					<a href="http://themeforest.net/downloads" target="_blank" class="button button-primary button-large">Rate</a>
				</p>
				<h2 class="nav-tab-wrapper">
					<a href="#importer" class="nav-tab nav-tab-active">Importer</a>
					<a href="#support" class="nav-tab">Support</a>
				</h2>
				<div id="importer" class="options group">
					<table class="widefat">
						<thead>
							<tr>
								<th colspan="3">System Requirements</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>Server Info:</td>
								<td><?php echo isset( $_SERVER['SERVER_SOFTWARE'] ) ? esc_attr( sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) ) :'Unknown'; ?></td>
							</tr>
							<tr>
								<td>PHP Version:</td>
								<td>
									<?php
									$php_version = null;
									if ( defined( 'PHP_VERSION' ) ) {
										$php_version = PHP_VERSION;
									} elseif ( function_exists( 'phpversion' ) ) {
										$php_version = phpversion();
									}
									if ( null === $php_version ) {
										$message = 'PHP Version could not be detected.';
									} else {
										if ( version_compare( $php_version, '5.6.3' ) >= 0 ) {
											$message = '<mark class="yes">' . $php_version . '</mark>';
										} else {
											$message = '<mark class="error">' . sprintf('%1$s.<br /> WordPress recommendation: %2$s or above. Please update PHP Version before Import Dummy Content.',
												$php_version,
												'5.6.3' ) . '</mark>';
										}
									}
									echo $message;
									?>
								</td>
							</tr>
							<?php if ( function_exists( 'ini_get' ) ) : ?>
								<tr>
									<td>PHP Post Max Size:</td>
									<td><?php echo esc_attr( size_format( wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) ) ) ); ?></td>
								</tr>
								<tr>
									<td>PHP Time Limit:</td>
									<td>
										<?php
										$time_limit = ini_get( 'max_execution_time' );

										if ( 180 > $time_limit && 0 != $time_limit ) {
											echo '<mark class="error">' . sprintf( '%1$s - We recommend setting max execution time to at least 180.<br />See: <a href="%2$s" target="_blank" rel="noopener noreferrer">Increasing max execution to PHP</a>', $time_limit, 'http://codex.wordpress.org/Common_WordPress_Errors#Maximum_execution_time_exceeded' ) . '</mark>';
										} else {
											echo '<mark class="yes">' . esc_attr( $time_limit ) . '</mark>';
										}
										?>
									</td>
								</tr>
							<?php endif; ?>
							<tr>
								<td>MySQL Version</td>
								<td><?php global $wpdb; ?>
								<?php echo esc_attr( $wpdb->db_version() ); ?></td>
							</tr>
							<tr>
								<td>Max Upload Size</td>
								<td><?php echo esc_attr( size_format( wp_max_upload_size() ) ); ?></td>
							</tr>
						</tbody>
					</table>

					<?php if ( $this->required_plugins() ): ?>
						<div class="import-warning">
							<?php 
							printf('<p>You need to install the following plugins to unlock our import function: <strong>%s</strong>', implode(', ', $this->required_plugins()) . '</p>' 
						); 
						?>
						<a href="<?php echo esc_url( add_query_arg( 'page', urlencode( 'tgmpa-install-plugins' ), self_admin_url( 'themes.php' ) ) ); ?>" class="button-primary">Go Manage Plugins</a>
					</div>

					<?php else: ?>

						<h3>Importer:</h3>
						<span class="description"><p>Please check all for Full Import</p></span>				
						<div class="option">
							<label for="mipro_import_theme_options">
								<input type="checkbox" name="mipro_import_theme_options" id="mipro_import_theme_options" value="1" />
								Theme Options
							</label>
						</div>
						<div class="option">
							<label for="mipro_import_widget">
								<input type="checkbox" name="mipro_import_widget" id="mipro_import_widget" value="1" />
								Widgets
							</label>
						</div>
						<div class="option">
							<label for="mipro_import_revslider">
								<input type="checkbox" name="mipro_import_revslider" id="mipro_import_revslider" value="1" />
								Revolution Slider
							</label>
						</div>
						<div class="option demo-content">
							<label for="mipro_import_demo_content">
								<input type="checkbox" name="mipro_import_demo_content" id="mipro_import_demo_content" value="1" />
								Demo Content
							</label>
						</div>
						<div class="mipro-button-import">
							<button id="mipro-import-button" class="button button-primary button-large" disabled>Import</button>
							<span class="loading">Please waiting...</span>
						</div>
						<div class="messages"></div>

					<?php endif; ?>

				</div>
				<div id="support" class="group">
					<div class="card">
						<p>Mipro comes with 6 months of free support for every license you purchase. Support can be extended through subscriptions via ThemeForest.</p>
						<a href="mailto:support@alura-studio.com" class="button button-large button-primary">Contact us</a>
					</div>
					<div class="col three-col">
						<div class="col">
							<h3>Documentation</h3>
							<p>This is the place to go to reference different aspects of the theme. Our online documentaiton is an incredible resource for learning the ins and outs of using our theme.</p>
							<a href="http://alura-studio.com" class="button button-large button-primary">Document</a>
						</div>
						<div class="col">
							<h3>Follow Us</h3>
							<p>Follow us on ThemeForest to receive the latest information and our theme. You will have the opportunity to get better quality products that we are developing.</p>
							<a href="http://themeforest.net/user/alurastudio/follow" target="_blank" class="button button-large button-primary">Follow us</a>
						</div>
						<div class="col">
							<h3>Facebook</h3>
							<p>We have an amazing Facebook Group! Feel free to share the great things when you use our theme.</p>
							<a href="http://facebook.com/AluraStudio/" target="_blank" class="button button-large button-primary">Facebook Group</a>
						</div>
					</div>
				</div>
			</div>
			<?php
		}

		function required_plugins() {
			$plugins = array();

			if( ! class_exists('ReduxFramework') ) {
				$plugins[] = 'Redux Framework';
			}

			if( ! class_exists('CMB2') ) {
				$plugins[] = 'CMB2';
			}

			if( ! class_exists('RevSlider') ) {
				$plugins[] = 'Slider Revolution';
			}

			if( ! class_exists('MiproCore') ) {
				$plugins[] = 'Mipro Core';
			}

			if( ! class_exists('KingComposer') ) {
				$plugins[] = 'King Composer';
			}

			if( ! empty( $plugins ) ) {
				return $plugins;
			}

			return false;
		}

		function before_import_stage() {

			add_filter( 'intermediate_image_sizes_advanced', array($this, 'filter_image_sizes') );

			if ( function_exists( 'ini_get' ) ) {
				if ( 300 < ini_get( 'max_execution_time' ) ) {
					@ini_set( 'max_execution_time', 300 );
				}
				if ( 512 < intval( ini_get( 'memory_limit' ) ) ) {
					@ini_set( 'memory_limit', '512M' );
				}
			}
			set_time_limit(0);
		}

		function filter_image_sizes( $sizes ) {
			return array();
		}

		/* Import XML */
		function import_content() {

			$this->before_import_stage();

			if ( ! defined('WP_LOAD_IMPORTERS') ) { 
				define('WP_LOAD_IMPORTERS', true); 
			}

			if ( ! class_exists( 'WP_Importer' ) ) {
				include ABSPATH . 'wp-admin/includes/class-wp-importer.php';
			}

			if ( ! class_exists('WP_Import') ) {
				include_once dirname(__FILE__) . '/includes/wordpress-importer.php';
			}

			$file_path = dirname(__FILE__) . '/data/demo_content.xml';

			if ( file_exists($file_path) ) {
				$importer = new WP_Import();
				$importer->fetch_attachments = true;
				ob_start();
				$importer->import($file_path);
				ob_end_clean();
			}

			die();
		}

		function import_config(){
			$this->woocommerce_settings();
			$this->menu_locations();
			$this->update_options();
			$this->create_attribute();
			wp_die();
		}

		/* Import Theme Options */
		function import_theme_options() {

			$theme_options_path = dirname(__FILE__) . '/data/theme_options.txt';

			if( !file_exists($theme_options_path) || !class_exists( 'ReduxFramework' ) ) {
				wp_die();
			}

			$theme_options_url = untrailingslashit( plugin_dir_url(__FILE__) ) . '/data/theme_options.txt';
			$theme_options_content = wp_remote_get( $theme_options_url );
			$redux_options_data = json_decode( $theme_options_content['body'], true );
			$redux_options_data['kft_gmap_api_key'] = '';
			$redux_framework = \ReduxFrameworkInstances::get_instance( 'mipro_opt' );

			if ( isset( $redux_framework->args['opt_name'] ) ) { 
				$redux_framework->set_options( $redux_options_data );
			}

			die();
		}

		/* Import Widget */
		function import_widget() {

			/* Clear Widgets */
			$sidebars = wp_get_sidebars_widgets();
			$inactive = isset($sidebars['wp_inactive_widgets']) && is_array( $sidebars['wp_inactive_widgets'] ) ? $sidebars['wp_inactive_widgets'] : array();

			unset($sidebars['wp_inactive_widgets']);

			foreach ( $sidebars as $sidebar => $widgets ) {
				if( is_array( $widgets ) ){
					$inactive = array_merge($inactive, $widgets);
				}

				$sidebars[$sidebar] = array();
			}

			$sidebars['wp_inactive_widgets'] = $inactive;
			wp_set_sidebars_widgets( $sidebars );
			/* End Clear Widgets */

			$file_path = dirname(__FILE__) . '/data/widget_data.json';

			if( !file_exists($file_path) ) {
				wp_die();
			}

			$file_url = untrailingslashit( plugin_dir_url(__FILE__) ) . '/data/widget_data.json';
			$widget_json = wp_remote_get( $file_url );
			$widget_data = $widget_json['body'];
			$widget_data = json_decode( $widget_data, true);
			unset($widget_data[0]['wp_inactive_widgets']);

			$sidebar_data = $widget_data[0];
			$widget_data = $widget_data[1];

			foreach ( $widget_data as $widget_data_title => $widget_data_value ) {
				$widgets[ $widget_data_title ] = array();
				foreach ( $widget_data_value as $widget_data_key => $widget_data_array ) {
					if ( is_int( $widget_data_key ) ) {
						$widgets[ $widget_data_title ][ $widget_data_key ] = 'on';
					}
				}
			}
			unset( $widgets[''] );

			foreach( $sidebar_data as $title => $sidebar ) {
				$count = count( $sidebar );
				for ( $i = 0; $i < $count; $i++ ) {
					$widget = array( );
					$widget['type'] = trim( substr( $sidebar[$i], 0, strrpos( $sidebar[$i], '-' ) ) );
					$widget['type-index'] = trim( substr( $sidebar[$i], strrpos( $sidebar[$i], '-' ) + 1 ) );
					if ( !isset( $widgets[$widget['type']][$widget['type-index']] ) ) {
						unset( $sidebar_data[$title][$i] );
					}
				}
				$sidebar_data[$title] = array_values( $sidebar_data[$title] );
			}

			foreach( $widgets as $widget_title => $widget_value ) {
				if (is_array($widget_value) || is_object($widget_value) ) {
					foreach( $widget_value as $widget_key => $widget_value ) {
						$widgets[$widget_title][$widget_key] = $widget_data[$widget_title][$widget_key];
					}
				}
			}

			$sidebar_data = array( array_filter( $sidebar_data ), $widgets );

			/* Parse data */
			global $wp_registered_sidebars;

			$sidebars_data = $sidebar_data[0];
			$widget_data = $sidebar_data[1];

			$current_sidebars = get_option( 'sidebars_widgets' );

			$new_widgets = array();

			foreach( $sidebars_data as $import_sidebar => $import_widgets ) {
				foreach( $import_widgets as $import_widget ) {
					if( array_key_exists( $import_sidebar, $current_sidebars ) ) {
						$title = trim( substr( $import_widget, 0, strrpos( $import_widget, '-' ) ) );
						$index = trim( substr( $import_widget, strrpos( $import_widget, '-' ) + 1 ) );

						$current_widget_data = get_option( 'widget_' . $title );

						$new_widget_name = self::get_new_widget_name( $title, $index );
						$new_index = trim( substr( $new_widget_name, strrpos( $new_widget_name, '-' ) + 1 ) );

						if ( !empty( $new_widgets[ $title ] ) && is_array( $new_widgets[$title] ) ) {
							while ( array_key_exists( $new_index, $new_widgets[$title] ) ) {
								$new_index++;
							}
						}

						$current_sidebars[$import_sidebar][] = $title . '-' . $new_index;

						if ( array_key_exists( $title, $new_widgets ) ) {
							$new_widgets[$title][$new_index] = $widget_data[$title][$index];
							$multiwidget = $new_widgets[$title]['_multiwidget'];
							unset( $new_widgets[$title]['_multiwidget'] );
							$new_widgets[$title]['_multiwidget'] = $multiwidget;
						} else {
							$current_widget_data[$new_index] = $widget_data[$title][$index];
							$current_multiwidget = isset($current_widget_data['_multiwidget']) ? $current_widget_data['_multiwidget'] : false;
							$new_multiwidget = isset($widget_data[$title]['_multiwidget']) ? $widget_data[$title]['_multiwidget'] : false;
							$multiwidget = ($current_multiwidget != $new_multiwidget) ? $current_multiwidget : 1;
							unset( $current_widget_data['_multiwidget'] );
							$current_widget_data['_multiwidget'] = $multiwidget;
							$new_widgets[$title] = $current_widget_data;
						}

					}
				}
			}

			if ( isset( $new_widgets ) && isset( $current_sidebars ) ) {
				update_option( 'sidebars_widgets', $current_sidebars );

				foreach ( $new_widgets as $title => $content ) {
					$content = apply_filters( 'widget_data_import', $content, $title );
					update_option( 'widget_' . $title, $content );
				}

				return true;
			}

			return false;

			wp_die();
		}

		function get_new_widget_name( $widget_name, $widget_index ) {

			$current_sidebars = get_option( 'sidebars_widgets' );
			$all_widget_array = array();

			foreach ( $current_sidebars as $sidebar => $widgets ) {
				if ( !empty( $widgets ) && is_array( $widgets ) && $sidebar != 'wp_inactive_widgets' ) {
					foreach ( $widgets as $widget ) {
						$all_widget_array[] = $widget;
					}
				}
			}

			while ( in_array( $widget_name . '-' . $widget_index, $all_widget_array ) ) {
				$widget_index++;
			}

			$new_widget_name = $widget_name . '-' . $widget_index;
			return $new_widget_name;
		}

		/* Import Revolution Slider */
		function import_revslider() {

			if( class_exists('RevSliderSlider')) {

				$slider_directory  = dirname(__FILE__) . '/data/revslider/';
				$slider_files = array();
				$slider = new RevSlider();

				foreach( glob( $slider_directory . '*.zip' ) as $filename ) {
					$filename = basename($filename);
					$slider_files[] = $slider_directory . $filename;
				}

				foreach($slider_files as $index => $filepath) {				
					ob_start();
					$response = $slider->importSliderFromPost(true, true,$filepath);
					ob_clean();
					ob_end_clean();
				}

				die();
			}
		}

		/* Create Attribute Woocommerce */
		function create_attribute() {
			
			if (function_exists('wc_get_attribute_taxonomies')) {
				$attribute_names = array('Color', 'Size');
				$register_attributes = array();

				foreach (wc_get_attribute_taxonomies() as $attr) {
					$attr = (array)$attr;
					$register_attributes[] = $attr['attribute_label'];
				}

				foreach ($attribute_names as $attribute_name) {
					global $wpdb;
					if ( ! in_array( $attribute_name, $register_attributes ) ) {
						$attribute = array(
							'attribute_label'   => $attribute_name,
							'attribute_name'    => strtolower($attribute_name),
							'attribute_type'    => 'select',
							'attribute_orderby' => 'menu_order',
							'attribute_public'  => 0
						);
						if ( 'Color' === $attribute_name ) {
							$attribute['attribute_type'] = 'color';
						}
						$wpdb->insert( $wpdb->prefix . 'woocommerce_attribute_taxonomies', $attribute );
						delete_transient( 'wc_attribute_taxonomies' );
					}
				}
			}
		}

		/* WooCommerce Settings */
		function woocommerce_settings() {

			$woopages = array(
				'woocommerce_shop_page_id' 			=> 'Shop'
				,'woocommerce_cart_page_id' 		=> 'Shopping cart'
				,'woocommerce_checkout_page_id' 	=> 'Checkout'
				,'woocommerce_myaccount_page_id' 	=> 'My Account'
			);

			foreach( $woopages as $woo_page_name => $woo_page_title ) {
				$woopage = get_page_by_title( $woo_page_title );
				if( isset( $woopage->ID ) && $woopage->ID ) {
					update_option($woo_page_name, $woopage->ID);
				}
			}

			update_option( 'woocommerce_single_image_width', 550 );
			update_option( 'woocommerce_thumbnail_image_width', 330 );
			update_option( 'woocommerce_thumbnail_cropping', 'custom' );
			update_option( 'woocommerce_thumbnail_cropping_custom_width', '330' );
			update_option( 'woocommerce_thumbnail_cropping_custom_height', '413' );


			if( class_exists('YITH_Woocompare') ){
				update_option('yith_woocompare_compare_button_in_products_list', 'yes');
			}

			if( class_exists('WC_Admin_Notices') ){
				WC_Admin_Notices::remove_notice('install');
			}

			delete_option( '_wc_needs_pages' );
			delete_transient( '_wc_activation_redirect' );

			flush_rewrite_rules();
		}

		/* Menu Locations */
		function menu_locations() {

			$locations = get_theme_mod( 'nav_menu_locations' );
			$menus = wp_get_nav_menus();

			if( $menus ) {
				foreach($menus as $menu) {
					if( $menu->name == 'Main menu' ) {
						$locations['primary'] = $menu->term_id;
					}
					if( $menu->name == 'Shop by Categories' ) {
						$locations['vertical'] = $menu->term_id;
					}
				}
			}
			set_theme_mod( 'nav_menu_locations', $locations );
		}

		/* Update Options */
		function update_options() {

			$homepage = get_page_by_title( 'Homepage' );
			if( isset( $homepage ) && $homepage->ID ){
				update_option('show_on_front', 'page');
				update_option('page_on_front', $homepage->ID);
			}

			/* Visual Composer Custom Post Type */
			update_option( 'wpb_js_content_types', array('page', 'kft_footer') );
		}
	}

	new Mipro_Importer();
}

?>