<?php

if ( ! class_exists( 'Kd_Import_Demo' ) ) {

	class Kd_Import_Demo {

		/**
		 * @var string
		 */
		public $dir_templates;

		/**
		 * @var array
		 */
		public $configs = array(

		);

		/**
		 * Kd_Import_Demo constructor.
		 *
		 * @param array $args
		 */
		public function __construct ( $args = array() ) {

			$this->configs = apply_filters( 'kd_support_import_configs', $this->configs );

			if ( ! empty( $args['dir_templates'] ) ) {
				$this->dir_templates = $args['dir_templates'];
			} else {
				$this->dir_templates = KD_SUPPORT_PATH . 'templates/';
			}

			add_action( 'wp_ajax_kd-import', array( $this, 'kd_import' ) );
		}

		/**
		 * Action Import Demo AJAX
		 */
		public function kd_import () {
			if ( isset( $_POST['name_file'] ) && ! empty( $_POST['name_file'] ) && file_exists( $this->dir_templates . 'data/' . $_POST['name_file'] . '.xml' ) ) {

				$error = false;

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

				/* Check require Importer */
				if ( class_exists( 'WP_Importer' ) ) {
					$importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';

					if ( file_exists( $importer ) ) {
						require_once( $importer );
					} else {
						$error = true;
					}
				}

				/* Check require WP Import */
				if ( ! class_exists( 'WP_Import' ) ) {
					$import = KD_SUPPORT_PATH . 'inc/class.wp-importer.php';
					if ( file_exists( $import ) ) {
						require_once( $import );
					} else {
						$error = true;
					}
				}

				/* Notice error */
				if ( $error ) {
					echo '<div class="alert-box alert-error">' .
					     '<strong>' . esc_html__( 'Error!', 'kendytheme' ) . '</strong>'
					     . esc_html__( 'The Auto importing script could not be loaded. Please use the Wordpress importer and import the XML file that is located in your themes folder manually.', 'kendytheme' ) .
					     '</div>';
					wp_die();
				}

				$wp_import = new WP_Import();

				do_action( 'kd_support_before_import_file', $wp_import, $this, $_POST['name_file'] );
				if ( ! isset( $_POST['item_last'] ) ) {
					$wp_import->fetch_attachments = true;
				} else {
					$wp_import->fetch_attachments = false;
				}
				$wp_import->import( $this->dir_templates . 'data/' . $_POST['name_file'] . '.xml' );

				/* Import Only Posts */
				if ( isset( $_POST['item_last'] ) ) {

					$this->update_theme_options();
					$this->set_widgets();

					$locations = array();

					foreach ( $this->configs['menus'] as $key => $value ) {
						$location  = $this->check_menu_exist( $value['menu_id'], $value['menu_name'] );
						$locations = array_merge( $locations, $location );
					}

					if ( ! empty( $locations ) ) {
						set_theme_mod( 'nav_menu_locations', $locations );
					}

					/* Settings Reading */
					update_option( 'posts_per_page', $this->configs['posts_per_pages'] );
					/* End Settings Reading */

					/* Remove post Hello World */
					$hello_world = get_page_by_title( 'Hello world!', OBJECT, 'post' );
					if ( ! empty( $hello_world ) ) {
						wp_delete_post( $hello_world->ID );
					}

					echo '<p class="import-done">' . esc_html__( 'Import successful. ', 'kendytheme' ) . '<a href="' . admin_url( '/' ) . '">' . esc_html__( 'Return to the Dashboard ', 'kendytheme' ) . '</a><span> | </span><a href="' . site_url( '/' ) . '">' . esc_html__( 'Visit Site', 'kendytheme' ) . '</a></p>';

					$callback = apply_filters('kd_after_import_all_done', '');
					if (!empty($callback) && is_array($callback)) {
						foreach ($callback as $func) {
							if (is_callable($func)) {
								call_user_func($func);
							}
						}

					}
				}
				wp_die();
			}
		}

		public function update_theme_options () {

			if ( empty( $this->configs['theme_option_data'] ) || empty( $this->configs['theme_options_name'] ) ) {
				return;
			}
			$kd_theme_options = @unserialize( $this->configs['theme_option_data'] );
			if ( ! $kd_theme_options ) {
				return;
			}
			do_action( 'kd_support_import_before_update_theme_options', $kd_theme_options, $this->configs['theme_options_name'] );
			update_option( $this->configs['theme_options_name'], $kd_theme_options );
			do_action( 'kd_support_import_after_update_theme_options', $kd_theme_options, $this->configs['theme_options_name'] );
		}

		public function set_widgets () {

			if ( empty( $this->configs['sidebar_widgets'] ) ) {
				return;
			}
			$kd_widgets = @unserialize( $this->configs['sidebar_widgets'] );
			if ( $kd_widgets == false ) {
				return;
			}

			do_action( 'kd_support_import_before_set_widgets', $kd_widgets );

			update_option( 'sidebars_widgets', $kd_widgets );

			if ( ! empty( $this->configs['widget_settings'] ) && is_array( $this->configs['widget_settings'] ) ) {
				foreach ( $this->configs['widget_settings'] as $key => $widget ) {
					update_option( $key, unserialize( $widget ) );
				}
			}

			do_action( 'kd_support_import_after_set_widgets', $kd_widgets );
		}

		public function check_menu_exist ( $menu_id, $menu_name ) {

			$theme_locations = get_nav_menu_locations();
			$menu_exist      = false;

			if ( $theme_locations && ! empty( $theme_locations ) ) {
				if ( array_key_exists( $menu_id, $theme_locations ) ) {
					$menu_exist = true;
				}
			}

			if ( $menu_exist ) {

				/* If menu already exist, reset menu */
				$term_id        = $theme_locations[ $menu_id ];
				$get_menu_items = wp_get_nav_menu_items( $term_id );

				if ( $get_menu_items && ! empty( $get_menu_items ) ) {
					foreach ( $get_menu_items as $control_menu_id ) {
						wp_delete_post( $control_menu_id->ID );
					}
				}
			}
			$location = $this->set_menu( $menu_id, $menu_name );

			return $location;

		}

		public function set_menu ( $menu_id, $menu_name ) {

			$created_menus = wp_get_nav_menus();
			$founded       = false;

			if ( ! empty( $created_menus ) ) {
				foreach ( $created_menus as $menu ) {

					if ( is_object( $menu ) ) {
						if ( $menu->name == $menu_name ) {
							/* If we have found a menu with the correct menu name apply the id to the menu location */
							$locations[ $menu_id ] = $menu->term_id;
							echo '<p class="success">' . esc_html__( 'Set default menu successfully!', 'kendytheme' ) . '</p>';
							$founded = true;

							return $locations;
						}
					}
				}
			}

			if ( ! $founded ) {
				echo '<p class="error">' . esc_html__( 'Can not set default menu!', 'kendytheme' ) . '</p>';

				return array();
			}

		}


	}

}