<?php
/**
 * DateBook Importer
 */

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

// Load Importer API
require_once ABSPATH . 'wp-admin/includes/import.php';

$importerError = false;

if ( ! class_exists( 'WP_Importer' ) ) {
	$class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
	if ( file_exists( $class_wp_importer ) ) {
		require_once $class_wp_importer;
	}
} else {
	$importerError = true;
}

if ( ! class_exists( 'WP_Import' ) ) {
	$class_wp_import = DATEBOOK_DIR . 'framework/wordpress-importer/wordpress-importer.php';
	if ( file_exists( $class_wp_import ) ) {
		require_once $class_wp_import;
	} else {
		$importerError = true;
	}
}

if ( ! class_exists( 'WidgetsImporter' ) ) {
class DateBook_WidgetsImporter extends WP_Import {
	
	protected $import_filepath;
	
	function __construct() {
		$this->import_filepath = DATEBOOK_DIR . 'framework/sample/';
		$this->datebook_import_file();
	}
	
	function datebook_import_file() {

		global $importerError;
		
		if ( ! $importerError ) {
			$this->fetch_attachments = true;
			$this->datebook_process_import_file( $this->import_filepath . 'widgets.wie' );
		}
	}
	
	function datebook_process_import_file( $file ) {
		
		global $datebook_import_results, $wp_registered_sidebars;
		
		// Attempt to get the JSON feed
		$data = wp_remote_get($file);
		
		if(isset($data->errors['http_request_failed'][0]) && !empty($data->errors['http_request_failed'][0])){

			if(in_array('curl', get_loaded_extensions()) || function_exists('curl_init') !== false) {

				$ch = curl_init();
				curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_URL, $file);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
				$data = curl_exec($ch);
				curl_close($ch);

			}

			$allow_url_curl = (is_array($data) && !empty($data['body'])) ? 1 : 0;

			if($allow_url_curl == 0){
				include $file . '.php';
				$data = array('body' => $content);
			}

		}

		// Verify that the JSON feed returned something useful
		if (is_array($data) && !empty($data['body'])) {

			$data = json_decode($data['body'],true);

			do_action( 'datebook_before_import' );
			$data = apply_filters( 'datebook_import_data', $data );
		
			$available_widgets = $this->datebook_available_widgets();
		
			$widget_instances = array();
			foreach ( $available_widgets as $widget_data ) {
				$widget_instances[$widget_data['id_base']] = get_option( 'widget_' . $widget_data['id_base'] );
			}
		
			$results = array();
			if (is_array($data) && !empty($data)){
				foreach ($data as $sidebar_id => $widgets){
					if ( 'wp_inactive_widgets' == $sidebar_id ) {
						continue;
					}
			
					if ( isset( $wp_registered_sidebars[$sidebar_id] ) ) {
						$sidebar_available = true;
						$use_sidebar_id = $sidebar_id;
						$sidebar_message_type = 'success';
						$sidebar_message = '';
					} else {
						$sidebar_available = false;
						$use_sidebar_id = 'wp_inactive_widgets';
						$sidebar_message_type = 'error';
						$sidebar_message = esc_html__( 'Sidebar does not exist in theme (using Inactive)', 'datebook' );
					}

					$results[$sidebar_id]['name'] = ! empty( $wp_registered_sidebars[$sidebar_id]['name'] ) ? $wp_registered_sidebars[$sidebar_id]['name'] : $sidebar_id;
					$results[$sidebar_id]['message_type'] = $sidebar_message_type;
					$results[$sidebar_id]['message'] = $sidebar_message;
					$results[$sidebar_id]['widgets'] = array();

					foreach ( $widgets as $widget_instance_id => $widget ) {

						$fail = false;
						$id_base = preg_replace( '/-[0-9]+$/', '', $widget_instance_id );
						$instance_id_number = str_replace( $id_base . '-', '', $widget_instance_id );

						if ( ! $fail && ! isset( $available_widgets[$id_base] ) ) {
							$fail = true;
							$widget_message_type = 'error';
							$widget_message = esc_html__( 'Site does not support widget', 'datebook' );
						}

						$widget = apply_filters( 'datebook_widget_settings', $widget );
						$widget = json_decode( json_encode( $widget ), true );
						$widget = apply_filters( 'datebook_widget_settings_array', $widget );

						if ( ! $fail && isset( $widget_instances[$id_base] ) ) {
							$sidebars_widgets = get_option( 'sidebars_widgets' );
							$sidebar_widgets = isset( $sidebars_widgets[$use_sidebar_id] ) ? $sidebars_widgets[$use_sidebar_id] : array();
							$single_widget_instances = ! empty( $widget_instances[$id_base] ) ? $widget_instances[$id_base] : array();
							foreach ( $single_widget_instances as $check_id => $check_widget ) {
								if ( in_array( "$id_base-$check_id", $sidebar_widgets ) && (array) $widget == $check_widget ) {
									$fail = true;
									$widget_message_type = 'warning';
									$widget_message = esc_html__( 'Widget already exists', 'datebook' );
									break;
								}
							}
						}

						if ( ! $fail ) {
							$single_widget_instances = get_option( 'widget_' . $id_base );
							$single_widget_instances = ! empty( $single_widget_instances ) ? $single_widget_instances : array( '_multiwidget' => 1 );
							$single_widget_instances[] = $widget;
							end( $single_widget_instances );
							$new_instance_id_number = key( $single_widget_instances );

							if ( '0' === strval( $new_instance_id_number ) ) {
								$new_instance_id_number = 1;
								$single_widget_instances[$new_instance_id_number] = $single_widget_instances[0];
								unset( $single_widget_instances[0] );
							}

							if ( isset( $single_widget_instances['_multiwidget'] ) ) {
								$multiwidget = $single_widget_instances['_multiwidget'];
								unset( $single_widget_instances['_multiwidget'] );
								$single_widget_instances['_multiwidget'] = $multiwidget;
							}

							update_option( 'widget_' . $id_base, $single_widget_instances );

							$sidebars_widgets = get_option( 'sidebars_widgets' );
							$new_instance_id = $id_base . '-' . $new_instance_id_number;
							$sidebars_widgets[$use_sidebar_id][] = $new_instance_id;
							update_option( 'sidebars_widgets', $sidebars_widgets );

							$after_widget_import = array(
								'sidebar'           => $use_sidebar_id,
								'sidebar_old'       => $sidebar_id,
								'widget'            => $widget,
								'widget_type'       => $id_base,
								'widget_id'         => $new_instance_id,
								'widget_id_old'     => $widget_instance_id,
								'widget_id_num'     => $new_instance_id_number,
								'widget_id_num_old' => $instance_id_number
							);
							do_action( 'datebook_after_widget_import', $after_widget_import );

							if ( $sidebar_available ) {
								$widget_message_type = 'success';
								$widget_message = esc_html__( 'Imported', 'datebook' );
							} else {
								$widget_message_type = 'warning';
								$widget_message = esc_html__( 'Imported to Inactive', 'datebook' );
							}
						}

						$results[$sidebar_id]['widgets'][$widget_instance_id]['name'] = isset( $available_widgets[$id_base]['name'] ) ? $available_widgets[$id_base]['name'] : $id_base;
						$results[$sidebar_id]['widgets'][$widget_instance_id]['title'] = ! empty( $widget['title'] ) ? $widget['title'] : esc_html__( 'No Title', 'datebook' );
						$results[$sidebar_id]['widgets'][$widget_instance_id]['message_type'] = $widget_message_type;
						$results[$sidebar_id]['widgets'][$widget_instance_id]['message'] = $widget_message;
					}
				}
		
				do_action( 'datebook_after_import' );
				return apply_filters( 'datebook_import_results', $results );
			}
		}
	}
	
	function datebook_available_widgets() {
		global $wp_registered_widget_controls;

		$widget_controls = $wp_registered_widget_controls;
		$available_widgets = array();
		
		foreach ( $widget_controls as $widget ) {
			if ( ! empty( $widget['id_base'] ) && ! isset( $available_widgets[$widget['id_base']] ) ) {
				$available_widgets[$widget['id_base']]['id_base'] = $widget['id_base'];
				$available_widgets[$widget['id_base']]['name'] = $widget['name'];
			}
		}
		return apply_filters( 'datebook_available_widgets', $available_widgets );
	}

}
}