<?php

/**
 * The file that defines the core plugin class
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 *
 * @link       https://www.facebook.com/nikita.flo.735
 * @since      1.0.0
 *
 * @package    FLO_INIT_INITIAL_THEME_DATA
 */

/**
 * The core plugin class.
 *
 * This is used to define internationalization, admin-specific hooks, and
 * public-facing site hooks.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.
 *
 * @since      1.0.0
 * @package    FLO_INIT_INITIAL_THEME_DATA
 * @author     Nichita Sinitin <nikita@flosites.net>
 */
class FLO_INIT_INITIAL_THEME_DATA
{
	/**
	 * The unique identifier of this plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $theme_name    The string used to uniquely identify this plugin.
	 */
	protected $theme_name;

	/**
	 * The current version of the plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $version    The current version of the plugin.
	 */
	protected $version;

	/**
	 * Define the core functionality of the plugin.
	 *
	 * Set the plugin name and the plugin version that can be used throughout the plugin.
	 * Load the dependencies, define the locale, and set the hooks for the admin area and
	 * the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */

	/* This is default array with all theme headers.To add new header , add to this array. */
	public $default_theme_headers = array('header-a', 'header-b', 'header-c', 'header-d', 'header-e', 'header-f');

	public function __construct()
	{	
		add_action('after_switch_theme', array($this, 'fgt_set_initial_data'));
		add_action('after_switch_theme', array($this, 'maybe_deactivate_classic_editor'));
		add_action('after_setup_theme', array($this, 'fgt_set_initial_data'));
		add_action('after_setup_theme', array($this, 'maybe_deactivate_classic_editor'));
		add_action('wp_ajax_import_missing_headers', array($this, 'import_missing_headers'));

		add_action('upgrader_process_complete', array($this, 'upgrade_theme_defaults'), 10, 2);
		add_action('admin_init', array($this, 'update_default_headers'));
	}

	private function fgt_create_default_headers()
	{
		$default_headers = [];

		$headers = get_posts(array(
			'numberposts' => -1,
			'post_type'   => 'fgt_header',
			'fields'      => 'ids',
			'meta_query' => array(
				array(
					'key' => '_flothemes_global_header_metabox_field',
					'value' => 'on',
					'compare' => '=',
				)
			)
		));

		if (!isset($headers[0])) {
			foreach ($this->default_theme_headers as $key => $header) {
				include dirname(__FILE__) . '/initial-data/' . $header . '.php';

				$placeholder_image = 'https://flo-gutenberg-theme.s3.amazonaws.com/placeholder-image.jpg';
				$content = wp_slash($data['content']);
				$content = preg_replace('(https://demo.*?jpg)', $placeholder_image, $content);

				$post_data = array(
					'post_title'    => $data['title'],
					'post_content'  => $content,
					'post_status'   => 'publish',
					'post_type'		=> 'fgt_header'
				);


				$post_id = wp_insert_post($post_data);

				$header_data = array(
					'id'		=> $header,
					'name'		=> $data['title'],
					'image'		=> 'https://flothemes-dashboard-images.s3-us-west-2.amazonaws.com/gutenberg-theme/' . $header . '.png',
					'edit_id'	=> $post_id
				);

				if (isset($data['global']) && $data['global'] === TRUE) {
					update_post_meta($post_id, '_flothemes_global_header_metabox_field', 'on');
				}

				$default_headers[] = $header_data;
			}

			update_option('default_headers', json_encode($default_headers));
		}
	}
	/**
	 * This action should be used to import missing headers for early beta testers, can be removed in the future
	 */
	public function import_missing_headers()
	{
		// Bail if we don't have proper permissions
		if (!current_user_can('manage_options') || !isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'fgt-nonce')) {
			die('Busted');
		}

		$entries = array("header-d", "header-e", "header-f");

		$default_installed_headers = json_decode(get_option('default_headers'));

		$header_names = [];

		foreach ($default_installed_headers as $installed_header) {
			$header_name = $installed_header->name;

			array_push($header_names, $header_name);
		}

		if (array_search('Header D', $header_names) && array_search('Header E', $header_names) && array_search('Header F', $header_names)) {
			echo json_encode("All Headers already present");

			wp_die();
		}

		foreach ($entries as $key => $entrie) {
			include dirname(__FILE__) . '/initial-data/' . $entrie . '.php';
			$placeholder_image = 'https://flo-gutenberg-theme.s3.amazonaws.com/placeholder-image.jpg';
			$content = wp_slash($data['content']);
			$content = preg_replace('(https://demo.*?jpg)', $placeholder_image, $content);

			$post_data = array(
				'post_title'    => $data['title'],
				'post_content'  => $content,
				'post_status'   => 'publish',
				'post_type'		=> 'fgt_header'
			);

			$post_id = wp_insert_post($post_data);

			$header_data = array(
				'id'		=> $entrie,
				'name'		=> $data['title'],
				'image'		=> 'https://flothemes-dashboard-images.s3-us-west-2.amazonaws.com/gutenberg-theme/' . $entrie . '.png',
				'edit_id'	=> $post_id
			);

			if (isset($data['global']) && $data['global'] === TRUE) {
				update_post_meta($post_id, '_flothemes_global_header_metabox_field', 'on');
			}

			$missing_headers[] = $header_data;
		}

		$default_installed_headers = array_merge($default_installed_headers, $missing_headers);

		update_option('default_headers', json_encode($default_installed_headers));

		echo json_encode(array(
			'message'	=> 'Headers Imported',
		));

		wp_die();
	}


	/**
	 * This functions update new headers for users
	 */
	public function update_default_headers()
	{
		$check_updates = json_decode(get_option('pronto_updated'));

		if (is_object($check_updates) && $check_updates->header) {
			$default_installed_headers = json_decode(get_option('default_headers'));

			$installed_headers = [];
			$inserted_headers = [];
			foreach ($default_installed_headers as $installed_header) {
				array_push($installed_headers, $installed_header->id);
			}

			$missed_headers = array_diff($this->default_theme_headers, $installed_headers);


			if ($missed_headers) {
				foreach ($missed_headers as $key => $header) {
					include dirname(__FILE__) . '/initial-data/' . $header . '.php';
					$placeholder_image = 'https://flo-gutenberg-theme.s3.amazonaws.com/placeholder-image.jpg';
					$content = wp_slash($data['content']);
					$content = preg_replace('(https://demo.*?jpg)', $placeholder_image, $content);

					$post_data = array(
						'post_title'    => $data['title'],
						'post_content'  => $content,
						'post_status'   => 'publish',
						'post_type'		=> 'fgt_header'
					);


					$post_id = wp_insert_post($post_data);

					$header_data = array(
						'id'		=> $header,
						'name'		=> $data['title'],
						'image'		=> 'https://flothemes-dashboard-images.s3-us-west-2.amazonaws.com/gutenberg-theme/' . $header . '.png',
						'edit_id'	=> $post_id
					);

					if (isset($data['global']) && $data['global'] === TRUE) {
						update_post_meta($post_id, '_flothemes_global_header_metabox_field', 'on');
					}

					$inserted_headers[] = $header_data;
				}


				$default_installed_headers = array_merge($default_installed_headers, $inserted_headers);

				update_option('default_headers', json_encode($default_installed_headers));
			}

			update_option('pronto_updated', json_encode(array('header' => FALSE, 'footer' => $check_updates->footer, 'templates' => $check_updates->templates)));
		}
	}

	private function fgt_create_default_footers()
	{
		$default_footers = [];

		$footers = get_posts(array(
			'numberposts' => -1,
			'post_type'   => 'fgt_footer',
			'fields'      => 'ids',
			'meta_query' => array(
				array(
					'key' => '_flothemes_global_footer_metabox_field',
					'value' => 'on',
					'compare' => '=',
				)
			)
		));

		if (!isset($footers[0])) {
			$entries = array('footer-a', 'footer-b', 'footer-c');

			foreach ($entries as $key => $entrie) {
				include dirname(__FILE__) . '/initial-data/' . $entrie . '.php';

				$post_data = array(
					'post_title'    => $data['title'],
					'post_content'  => wp_slash($data['content']),
					'post_status'   => 'publish',
					'post_type'		=> 'fgt_footer'
				);

				$post_id = wp_insert_post($post_data);

				$footer_data = array(
					'id'		=> $entrie,
					'name'		=> $data['title'],
					'image'		=> 'https://flothemes-dashboard-images.s3-us-west-2.amazonaws.com/gutenberg-theme/' . $entrie . '.png',
					'edit_id'	=> $post_id
				);

				if (isset($data['global']) && $data['global'] === TRUE) {
					update_post_meta($post_id, '_flothemes_global_footer_metabox_field', 'on');
				}

				$default_footers[] = $footer_data;
			}

			update_option('default_footers', json_encode($default_footers));
		}
	}

	private function fgt_create_default_templates($data, $templates, $entrie)
	{
		$post_data = array(
			'post_title'    => $data['title'],
			'post_content'  => wp_slash($data['content']),
			'post_status'   => 'publish',
			'post_type'		=> 'fgt_template'
		);

		if ($entrie === 'global_post' || $entrie === 'global_post_b') {
			$post_data['post_type'] = 'fgt_p_template';
		}

		if ($entrie === 'global_gallery' || $entrie === 'global_gallery_b') {
			$post_data['post_type'] = 'fgt_g_template';
		}

		$post_id = wp_insert_post($post_data);
		$templates = json_decode($templates, TRUE);
		$templates[$entrie] = $post_id;

		if ($entrie === 'global_gallery' || $entrie === 'global_gallery_b') {
			$prev_data = get_option('default_g_templates');
			$new_data = $prev_data === '' ? [] : json_decode($prev_data);

			$global_g_data = array(
				'id'		=> $entrie,
				'name'		=> $data['title'],
				'image'		=> 'https://flo-gutenberg-theme.s3.amazonaws.com/' . $entrie . '.jpg',
				'edit_id'	=> $post_id
			);

			if (isset($data['global']) && $data['global'] === TRUE) {
				update_post_meta($post_id, '_flothemes_global_g_template_metabox_field', 'on');
			}

			$new_data[] = $global_g_data;

			update_option('default_g_templates', json_encode($new_data));
		}

		if ($entrie === 'global_post' || $entrie === 'global_post_b') {
			$prev_data = get_option('default_p_templates');
			$new_data = $prev_data === '' ? [] : json_decode($prev_data);

			$global_p_data = array(
				'id'		=> $entrie,
				'name'		=> $data['title'],
				'image'		=> 'https://flo-gutenberg-theme.s3.amazonaws.com/' . $entrie . '.jpg',
				'edit_id'	=> $post_id
			);


			if (isset($data['global']) && $data['global'] === TRUE) {
				update_post_meta($post_id, '_flothemes_global_p_template_metabox_field', 'on');
			}

			$new_data[] = $global_p_data;

			update_option('default_p_templates', json_encode($new_data));
		}

		return json_encode($templates);
	}

	public function fgt_set_initial_data()
	{
		$templates = get_option('fgt_templates_array');

		if (!$templates || $templates === '{"archive":false,"page_404":false,"global_post":false,"global_gallery":false,"search":false}') {
			$entries = array('global_post', 'global_post_b', 'global_gallery', 'global_gallery_b', 'page_404', 'archive', 'search');

			foreach ($entries as $key => $entrie) {
				include dirname(__FILE__) . '/initial-data/' . $entrie . '.layout.php';
				$templates = $this->fgt_create_default_templates($data, $templates, $entrie);
			}

			update_option('fgt_templates_array', $templates);
		}

		$this->fgt_create_default_headers();
		$this->fgt_create_default_footers();
	}


	/*Deactivate Classic Editor plugin if it is activated*/
	public function maybe_deactivate_classic_editor()
	{
		// this should make the 'is_plugin_active' function available
		include_once(ABSPATH . 'wp-admin/includes/plugin.php');

		if (function_exists('is_plugin_active')) {
			if (is_plugin_active('classic-editor/classic-editor.php')) {
				deactivate_plugins('classic-editor/classic-editor.php');

				// reload the current page to avoid warnings
				//header("Location: ".$_SERVER['REQUEST_URI']);
			}
		}

		if (function_exists('is_plugin_active_for_network')) {
			if (is_plugin_active_for_network('classic-editor/classic-editor.php')) {
				deactivate_plugins('classic-editor/classic-editor.php');
			}
		}
	}

	public function upgrade_theme_defaults($upgrader_object, $options)
	{
		if (($options['action'] == 'update' || $options['action'] == 'install')  && $options['type'] == 'theme') {
			if ($upgrader_object->new_theme_data['Name'] == 'Pronto') {

				//	now it works only for header. footer and templates we will use later
				update_option('pronto_updated', json_encode(array('header' => TRUE, 'footer' => TRUE, 'templates' => TRUE)));
			}
		}
	}
}

new FLO_INIT_INITIAL_THEME_DATA();
