<?php

/**
 * Class TX_Importer.
 *
 */
class TX_Importer extends TX_Admin_Sub_Page {
	/**
	 * @var string
	 */
	public $key_page = 'importer';

	/**
	 * @var string
	 */
	public static $key_option_demo_installed = 'tx_importer_demo_installed';

	/**
	 * Get key demo installed.
	 *
	 * @return bool|string
	 */
	public static function get_key_demo_installed() {
		$option = get_option( self::$key_option_demo_installed );

		if ( empty( $option ) ) {
			return false;
		}

		return $option;
	}

	/**
	 * Update key demo installed.
	 *
	 * @param string|bool $demo
	 *
	 * @return bool
	 */
	public static function update_key_demo_installed( $demo = '' ) {
		return update_option( self::$key_option_demo_installed, $demo );
	}

	/**
	 * Get packages import.
	 *
	 * @return array
	 */
	public static function get_import_packages() {
		$packages = array(
			'main_content'  => array(
				'title'       => esc_attr__( 'Main Content', 'edumodo' ),
				'description' => esc_attr__( 'Import posts, pages, comments, menus, custom fields, terms and custom posts.', 'edumodo' ),
			),
			'homepage'  => array(
				'title'       => esc_attr__( 'Homepage Displays', 'edumodo' ),
				'description' => esc_attr__( 'Home page and blog page in menu setting', 'edumodo' ),
			),
			'media'         => array(
				'title'       => esc_attr__( 'Media File', 'edumodo' ),
				'description' => esc_attr__( 'Download media files.', 'edumodo' ),
				'required'    => 'main_content',
			),
			'theme_options' => array(
				'title'       => esc_attr__( 'Edumodo Options', 'edumodo' ),
				'description' => esc_attr__( 'Import theme options and rewrite all current settings.', 'edumodo' ),
			),
			// 'customizer' => array(
			// 	'title'       => esc_attr__( 'Customizer', 'edumodo' ),
			// 	'description' => esc_attr__( 'Import customizer and rewrite all current settings.', 'edumodo' ),
			// ),
			'widget'       => array(
				'title'       => esc_attr__( 'Widgets', 'edumodo' ),
				'description' => esc_attr__( 'Import widgets data.', 'edumodo' ),
			),
			'revslider'     => array(
				'title'       => esc_attr__( 'Slider Revolution', 'edumodo' ),
				'description' => esc_attr__( 'Import Slider Revolution.', 'edumodo' ),
			),
		);

		return apply_filters( 'tx_wizard_importer_packages', $packages );
	}

	/**
	 * Get demo data.
	 *
	 * @return array
	 */
	public static function get_demo_data() {

		$THEME_URI  = get_template_directory_uri();
		$THEME_PATH = get_template_directory();

		$file_demo_data = $THEME_PATH . '/inc/data/demos.php';
		if ( ! file_exists( $file_demo_data ) ) {
			return array();
		}

		$demo_data = include $file_demo_data;

		if ( ! is_array( $demo_data ) ) {
			return array();
		}

		$base_uri_demo_data  = apply_filters( 'tx_wizard_importer_base_uri_demo_data', $THEME_URI . '/inc/data/demos/' );
		$base_path_demo_data = $THEME_PATH . '/inc/data/demos/';

		foreach ( $demo_data as $key => $demo ) {
			$demo_data[ $key ]['key']        = $key;
			$demo_data[ $key ]['screenshot'] = $base_uri_demo_data . $key . '/screenshot.jpg';
			if ( isset( $demo['thumbnail_url'] ) ) {
				$demo_data[ $key ]['screenshot'] = $demo['thumbnail_url'];
			}
			$demo_data[ $key ]['dir'] = $base_path_demo_data . $key;

			$plugins_require = isset( $demo['plugins_required'] ) ? $demo['plugins_required'] : false;
			if ( ! $plugins_require ) {
				continue;
			}

			if ( ! is_array( $plugins_require ) ) {
				continue;
			}

			$plugins_required_ = array();

			$plugins_require_all = TX_Plugins_Manager::get_slug_plugins_require_all();
			$plugins_require     = array_merge( $plugins_require_all, $plugins_require );
			$plugins_require     = array_unique( $plugins_require );

			foreach ( $plugins_require as $slug ) {
				$plugin = TX_Plugins_Manager::get_plugin_by_slug( $slug );

				if ( ! $plugin ) {
					continue;
				}

				if ( $plugin->get_status() === 'active' ) {
					continue;
				}

				array_push( $plugins_required_, $plugin->to_array() );
			}

			$demo_data[ $key ]['plugins_required'] = $plugins_required_;
		}

		return $demo_data;
	}

	/**
	 * TX_Importer constructor.
	 */
	protected function __construct() {
		parent::__construct();

		$this->init_hooks();
	}

	/**
	 * Get arguments for template.
	 *
	 * @return array
	 */
	protected function get_template_args() {
		$demo_data = self::get_demo_data();

		return array(
			'$demo_data'      => $demo_data,
			'$demo_installed' => self::get_key_demo_installed(),
		);
	}

	/**
	 * Init hooks.
	 */
	private function init_hooks() {
		add_action( 'txw_after_dashboard_wrapper', array( $this, 'add_modal_import' ) );
		add_action( 'txw_after_dashboard_wrapper', array( $this, 'add_modal_uninstall_demo' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'wp_ajax_tx_importer', array( $this, 'handle_ajax' ) );
		add_action( 'wp_ajax_tx_importer_uninstall', array( $this, 'handle_ajax_uninstall' ) );
		add_filter( 'tx_dashboard_sub_pages', array( $this, 'add_sub_page' ) );
		add_action( 'admin_init', array( $this, 'reset_import_demo' ) );
		add_filter( 'tx_importer_memory_limit', array( $this, 'memory_limit_importer' ) );
		add_action( 'admin_action_tx_importer_demo_data', array( $this, 'show_current_demo_data' ) );
	}


	/**
	 * Show current demo data.
	 */
	public function show_current_demo_data() {
		if ( ! current_user_can( 'administrator' ) ) {
			return;
		}

		$current = TX_Importer_AJAX::get_current_demo_data();
		print_r( $current );
	}

	/**
	 * Set memory limit for importer.
	 *
	 * @param $current
	 *
	 * @return string
	 */
	public function memory_limit_importer( $current ) {
		$current_limit_int = wp_convert_hr_to_bytes( $current );

		if ( $current_limit_int > 268435456 ) {
			return $current;
		}

		return '256M';
	}

	/**
	 * Reset config import demo.
	 */
	public function reset_import_demo() {
		if ( ! $this->is_myself() ) {
			return;
		}

		$detect = isset( $_GET['reset-importer'] );
		if ( ! $detect ) {
			return;
		}

		delete_option( 'tx_importer_posts_pp' );
		delete_option( 'tx_importer_attachments_pp' );
	}

	/**
	 * Add sub page.
	 *
	 * @param $sub_pages
	 *
	 * @return mixed
	 */
	public function add_sub_page( $sub_pages ) {
		$sub_pages['importer'] = array(
			'title' => __( 'Import Demo', 'edumodo' ),
		);

		return $sub_pages;
	}

	/**
	 * Enqueue scripts.
	 *
	 */
	public function enqueue_scripts() {
		if ( ! $this->is_myself() ) {
			return;
		}

		wp_enqueue_script( 'tx-importer', TX_WIZARD_ADMIN_URI . '/assets/js/importer.js', array( 'wp-util', 'jquery', 'backbone', 'underscore' ), TX_WIZARD_VERSION );

		$this->localize_script();
	}

	/**
	 * Add modal importer.
	 */
	public function add_modal_import() {
		if ( ! $this->is_myself() ) {
			return;
		}

		TX_Dashboard::get_template( 'partials/importer-modal.php' );
	}

	/**
	 * Add modal uninstall demo.
	 */
	public function add_modal_uninstall_demo() {
		if ( ! $this->is_myself() ) {
			return;
		}

		TX_Dashboard::get_template( 'partials/importer-uninstall-modal.php' );
	}

	/**
	 * Handle ajax import demo.
	 */
	public function handle_ajax() {
		if ( function_exists( 'wp_raise_memory_limit' ) ) {
			wp_raise_memory_limit( 'tx_importer' );
		}

		$importer_ajax = new TX_Importer_AJAX();
		$importer_ajax->handle_ajax();
	}

	/**
	 * Handle ajax uninstall demo.
	 */
	public function handle_ajax_uninstall() {
		if ( function_exists( 'wp_raise_memory_limit' ) ) {
			wp_raise_memory_limit( 'tx_importer' );
		}

		$importer_ajax = new TX_Importer_AJAX();
		$importer_ajax->handle_ajax_uninstall();
	}

	/**
	 * Localize script.
	 */
	public function localize_script() {
		$demos = self::get_demo_data();
		$nonce = wp_create_nonce( 'tx-importer' );

		wp_localize_script( 'tx-importer', 'tx_importer_data', array(
			'nonce'                => $nonce,
			'url_ajax'             => admin_url( 'admin-ajax.php' ),
			'admin_ajax_action'    => admin_url( 'admin-ajax.php' ),
			'admin_ajax_uninstall' => admin_url( 'admin-ajax.php' ),
			'details_error'        => array(
				'title'     => __( 'The import demo content failed!', 'edumodo' ),
				'try_again' => __( 'Import failed. The system will automatically adjust some configurations. Please give it one more try. Good luck!', 'edumodo' ),
				'code'      => array(
					'request' => '#001_REQUEST_ERROR',
					'server'  => '#002_SERVER_ERROR',
				),
			),
			'uninstall_successful' => __( 'Uninstall demo content successful :]', 'edumodo' ),
			'uninstall_failed'     => __( 'Uninstall demo content failed. Please try again :]', 'edumodo' ),
			'confirm_close'        => __( 'Do you really want to close?', 'edumodo' ),
			'something_went_wrong' => __( 'Some thing went wrong. Please try again :]', 'edumodo' ),
		) );

		wp_localize_script( 'tx-importer', 'tx_importer', array(
			'demos'     => $demos,
			'installed' => self::get_key_demo_installed(),
		) );
	}
}
