<?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_OPTIONS_PAGE_LOADER
 */

/**
 * 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_OPTIONS_PAGE_LOADER
 * @author     Nichita Sinitin <nikita@flosites.net>
 */
class FLO_OPTIONS_PAGE_LOADER
{
	/**
	 * 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
	 */
	public function __construct()
	{
		if (defined('FLEX_GUTENBERG_THEME_VERSION')) {
			$this->version = FLEX_GUTENBERG_THEME_VERSION;
		} else {
			$this->version = '1.0.0';
		}

		$this->fgt_global_options = array(
			'default_headers' => array(
				'default'	=> '',
				'label'		=> 'Default Headers'
			),
			'default_footers' => array(
				'default'	=> '',
				'label'		=> 'Default Footers'
			),
			'default_g_templates' => array(
				'default'	=> '',
				'label'		=> 'Default Gallery Templates'
			),
			'default_p_templates' => array(
				'default'	=> '',
				'label'		=> 'Default Post Templates'
			),
			'fgt_templates_array' => array(
				'default' => json_encode(
					array(
						'archive' 			=> FALSE,
						'page_404'			=> FALSE,
						'global_post'		=> FALSE,
						'global_gallery'	=> FALSE,
						'search'			=> FALSE,
					)
				),
				'label' => 'FGT Templates'
			),
			'fgt_copyright_area' => array(
				'default' => json_encode(
					array(
						'copyrightsNotice' => "Copyrights ©Flothemes 2019  |  All rights Reserved",
						'copyrightsNoticeFont' => "third_level/caption",
						'copyrightsBackgroundColor' => "scheme_1/background/default",
						'copyrightsElementsColor' => "scheme_1/text/default",
						'copyrightsDisplayScrollToTop' => TRUE,
						'copyrightsScrollToTopLabel' => "Back to Top",
						'copyrightsScrollToTopFont' => "third_level/caption",
					)
				),
				'label' => 'FGT Copyright'
			),
			'fgt_options' => array(
				'default' => json_encode(
					array(
						"trackingCode" => "",
						"disableFadingDesktop" => TRUE,
						"disableFadingTablet" => TRUE,
						"disableFadingMobile" => TRUE,
						"disablePreviewYourSite" => FALSE,
						"enableLazyLoad" => FALSE,

						"enableSitePreloader" => FALSE,
						"preloaderUseText" => FALSE,
						"preloaderLottie" => FALSE,
						"preloaderLottieFile" => "false",
						"preloaderBackgroundColor" => "scheme_1/background/default",
						"preloaderText" => "Welcome",
						"preloaderCustomImage" => "false",
						"preloaderColorText" => "scheme_1/text/default",
						"preloaderTextFont" => "second_level/subtitle_1",
						"preloaderDesktopSize" => 450,
						"preloaderMobileSize" => 190,
						"siteBackgroundColor" => "scheme_1/background/default",
						"siteColor" => "scheme_1/text/default",
						"contentWidth" => 800,
						"postImageMarginBottom" => 10,
						"linkFormat" => array(
							'bold' => FALSE,
							'italic' => FALSE,
							'underline' => TRUE
						),
						"flexLinkFormat" => array(
							'bold' => FALSE,
							'italic' => FALSE,
							'underline' => TRUE
						),
						'linkColor' => '#0047FF',
						'flexLinkColor' => '#0047FF',
						"styleFlexLinks" => FALSE,
						"styleContentLinks" => TRUE,
						"changeContentLinksColor" => FALSE,
						"changeFlexLinksColor" => FALSE,

						"cssCode" => "",
						"jsCode" => "",

						"genericFontH1" => "title_1/large",
						"genericFontH2" => "title_1/medium",
						"genericFontH3" => "title_1/small",
						"genericFontH4" => "title_1/xsmall",
						"genericFontH5" => "second_level/subtitle_2",
						"genericFontH6" => "second_level/subtitle_1",
						"genericFontParagraph" => "second_level/paragraph",
						"genericFontParagraphLink" => "second_level/paragraph",
						"genericFontPullQuote" => "second_level/quote",
						"genericFontPreformatted" => "second_level/paragraph",

						"formsFieldColor" => "scheme_1/text/default",
						"formsFieldLabelFont" => "second_level/subtitle_1",
						"formsFieldFont" => "second_level/subtitle_2",
						"formsFieldBorderStyle" => "bordered",
						"formsCheckboxLabelFont" => "third_level/caption",
						"formsButtonFont" => "third_level/primary_cta",
						"formsDefaultButtonScheme" => "scheme_1",

						"widgetsTitleFont" => "second_level/subtitle_1",
						"widgetsTitleColor" => "scheme_1/text/default",
						"widgetsContentFont" => "third_level/caption",
						"widgetsContentColor" => "scheme_1/text/default",
						"widgetsBackgroundColor" => "scheme_1/background/default",

						"copyrightsAreaShow" => TRUE,
						"copyrightsShowIcon" => TRUE,
						"copyrightsNotice" => "Copyrights ©Flothemes 2019  |  All rights Reserved",
						"copyrightsNoticeFont" => "third_level/caption",
						"copyrightsBackgroundColor" => "scheme_1/background/default",
						"copyrightsElementsColor" => "scheme_1/text/default",
						"copyrightsDisplayScrollToTop" => TRUE,
						"copyrightsScrollToTopLabel" => "Back to Top",
						"copyrightsScrollToTopFont" => "third_level/caption",
					)
				),
				'label' => 'FGT OPTIONS'
			),
		);

		$this->flo_add_fgt_options_fields();

		add_action('admin_enqueue_scripts', array($this, 'flo_fgt_localize_options_data'));
		add_action('admin_enqueue_scripts', array($this, 'flo_fgt_localize_data'));

		// Init ajax actions
		add_action('wp_ajax_set_as_global', array($this, 'set_as_global_callback'));
		add_action('wp_ajax_fgt_duplicate', array($this, 'duplicate_callback'));
		add_action('wp_ajax_fgt_delete', array($this, 'delete_callback'));
		add_action('wp_ajax_fgt_reset', array($this, 'reset_callback'));
		add_action('wp_ajax_save_fgt_options', array($this, 'save_fgt_options_callback'));
		add_action('wp_ajax_set_sticky', array($this, 'set_sticky_callback'));
	}

	public static function register_flo_main_options_page()
	{
		add_action('admin_menu', function () {
			require('wp-logo-image.php');
			add_menu_page(
				'Flotheme',
				'Flotheme',
				'administrator',
				'parent',
				function () {
					echo '<div id="fgt-options-page-container" class="fgt-options-page-container"></div>';
				},
				$wp_logo_image
			);
		});
	}

	public static function register_wp_options_page($args)
	{
		add_action('admin_menu', function () use ($args) {
			flo_option_page_initialization($args);
		});

		if (!function_exists('flo_option_page_initialization')) {
			function flo_option_page_initialization($args)
			{
				add_submenu_page('parent', $args['page_title'], $args['menu_title'], $args['capabilities'], $args['menu_slug'], function () {
				}, $args['position']);
			}
		}
	}

	public function flo_add_fgt_options_fields()
	{
		foreach ($this->fgt_global_options as $key => $value) {
			add_option($key, $value['default']);
			register_setting('fgt_options_group', $key);
		}
	}

	public function flo_fgt_localize_options_data()
	{
		$options_data = [
			'site_url' => site_url(),
			'admin_url' => admin_url(),
			'theme_name' => strtolower(wp_get_theme()->Name),
			'global_sk'	=> get_option('flex_active_stylekit_name')
		];

		foreach ($this->fgt_global_options as $key => $value) {
			$options_data[$key] = get_option($key) ? get_option($key) : $value['default'];
		}

		$headers = get_posts(array(
			'numberposts' 	=> -1,
			'post_type'   	=> 'fgt_header',
			'suppress_filters' => TRUE,
		));

		$sticky_headers = get_posts(array(
			'numberposts' => -1,
			'post_type'   => 'fgt_header',
			'fields'      => 'ids',
			'meta_query' => array(
				array(
					'key' => '_flothemes_sticky_header_metabox_field',
					'value' => 'true',
					'compare' => '=',
				)
			)
		));

		$footers = get_posts(array(
			'numberposts' 	=> -1,
			'post_type'   	=> 'fgt_footer',
			'suppress_filters' => TRUE,
		));

		$gallery_templates = get_posts(array(
			'numberposts' 	=> -1,
			'post_type'   	=> 'fgt_g_template',
			'suppress_filters' => TRUE,
		));

		$post_templates = get_posts(array(
			'numberposts' 	=> -1,
			'post_type'   	=> 'fgt_p_template',
			'suppress_filters' => TRUE,
		));

		$global_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($global_headers[0])) {
			$options_data['global_header'] = $global_headers[0];
		}

		$global_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($global_footers[0])) {
			$options_data['global_footer'] = $global_footers[0];
		}

		$global_g_templates = get_posts(array(
			'numberposts' => -1,
			'post_type'   => 'fgt_g_template',
			'fields'      => 'ids',
			'meta_query' => array(
				array(
					'key' => '_flothemes_global_g_template_metabox_field',
					'value' => 'on',
					'compare' => '=',
				)
			)
		));

		if (isset($global_g_templates[0])) {
			$options_data['global_g_template'] = $global_g_templates[0];
		}

		$global_p_templates = get_posts(array(
			'numberposts' => -1,
			'post_type'   => 'fgt_p_template',
			'fields'      => 'ids',
			'meta_query' => array(
				array(
					'key' => '_flothemes_global_p_template_metabox_field',
					'value' => 'on',
					'compare' => '=',
				)
			)
		));

		if (isset($global_p_templates[0])) {
			$options_data['global_p_template'] = $global_p_templates[0];
		}

		$options_data['headers'] = fgt_reduce_fields($headers);
		$options_data['sticky_headers'] = fgt_reduce_fields($sticky_headers);
		$options_data['footers'] = fgt_reduce_fields($footers);
		$options_data['gallery_templates'] = fgt_reduce_fields($gallery_templates);
		$options_data['post_templates'] = fgt_reduce_fields($post_templates);

		/*$templates_path = dirname(dirname(dirname(__FILE__))) . '/admin/templates/manifest.json';
		$templates = json_decode(file_get_contents($templates_path, true), true)['templates'][0];
		$options_data['templates'] = $templates;
		$options_data['template_directory_uri'] = get_template_directory_uri();*/

		$flo_credits_plugin_activated = in_array(
			'flo-footer-credits/flo_footer_credits.php',
			apply_filters('active_plugins', get_option('active_plugins'))
		) || is_plugin_active_for_network('flo-footer-credits/flo_footer_credits.php');
		$options_data['flo_credits_plugin_activated'] = $flo_credits_plugin_activated;
		$options_data['active_plugins'] = get_option('active_plugins');

		wp_localize_script('flo-admin', 'fgt_options_data', $options_data);
	}

	public function flo_fgt_localize_data()
	{
		$data = [
			'adminUrl' => get_admin_url(),
			'themeUrl' => get_template_directory_uri(),
			'fgtNonce' => wp_create_nonce('fgt-nonce')
		];

		wp_localize_script('flo-admin', 'fgtData', $data);
	}

	public function reset_callback()
	{
		// 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');
		}

		$post_id = $_POST['id'];
		$edit_id = $_POST['edit_id'];

		$templates_path = dirname(dirname(__FILE__)) . '/initial-data/' . $post_id . '.php';
		$reserve_templates_path = dirname(dirname(__FILE__)) . '/initial-data/' . $post_id . '.layout.php';

		if (!file_exists($templates_path)) {
			$templates_path = $reserve_templates_path;
		}

		if (file_exists($templates_path)) {
			include $templates_path;

			$post_data = array(
				'ID'		=> $edit_id,
				'post_title'    => $data['title'],
				'post_content'  => wp_slash($data['content']),
			);

			$post_id = wp_update_post($post_data);

			echo json_encode(array(
				'edit_id'  => $edit_id,
				'post_id'	=> $post_id,
				'message'	=> $post_id . ' reset'
			));
		} else {
			echo json_encode(array(
				'message'	=> 'File not found'
			));
		}

		wp_die();
	}

	public function delete_callback()
	{
		// 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');
		}

		$post_id = $_POST['id'];

		wp_delete_post($post_id, TRUE);

		echo json_encode(array(
			'message'	=> $post_id . ' deleted'
		));

		wp_die();
	}

	public function duplicate_callback()
	{

		// 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');
		}

		$post_id = $_POST['id'];
		$post_type = $_POST['post_type'];

		$post = get_post($post_id);

		$args = array(
			'comment_status' => $post->comment_status,
			'ping_status'    => $post->ping_status,
			'post_author'    => $new_post_author,
			'post_content'   => wp_slash($post->post_content),
			'post_excerpt'   => $post->post_excerpt,
			'post_name'      => $post->post_name,
			'post_parent'    => $post->post_parent,
			'post_password'  => $post->post_password,
			'post_status'    => 'publish',
			'post_title'     => $post->post_title . ' ( Copy )',
			'post_type'      => $post->post_type,
			'to_ping'        => $post->to_ping,
			'menu_order'     => $post->menu_order
		);

		$new_post_id = wp_insert_post($args);
		$new_post = get_post($new_post_id);

		echo json_encode(array(
			'type'  => $post_type,
			'post'	=> $new_post,
			'message'	=> $post_type . ' duplicated'
		));

		wp_die();
	}

	public function set_as_global_callback()
	{

		// 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');
		}

		$post_id = $_POST['id'];
		$post_type = $_POST['post_type'];

		$result = get_posts(array(
			'numberposts' 	=> -1,
			'post_type'   	=> 'fgt_' . $post_type,
			'fields'      	=> 'ids',
			'suppress_filters' => TRUE,
			'meta_query' 	=> array(
				array(
					'key' 		=> '_flothemes_global_' . $post_type . '_metabox_field',
					'value' 	=> 'on',
					'compare' 	=> '=',
				)
			)
		));

		foreach ($result as $key => $value) {
			update_post_meta($value, '_flothemes_global_' . $post_type . '_metabox_field', '');
		}

		update_post_meta($post_id, '_flothemes_global_' . $post_type . '_metabox_field', 'on');

		if ($post_type === 'g_template' || $post_type === 'p_template') {
			$templates = json_decode(get_option('fgt_templates_array'), TRUE);

			if ($post_type === 'g_template') {
				$templates['global_gallery'] = $post_id;
			} else {
				$templates['global_post'] = $post_id;
			}

			update_option('fgt_templates_array', json_encode($templates));
		}


		echo json_encode(array(
			'type'  => $post_type,
			'id'	=> $post_id,
			'message'	=> 'Set as global'
		));

		wp_die();
	}

	public function save_fgt_options_callback()
	{
		// 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');
		}

		$options_value = json_decode(html_entity_decode(stripslashes($_POST['optionsValue'])), TRUE);

		foreach ($options_value as $key => $value) {
			update_option($key, $value);
		}

		$result = array(
			'response' => 'Option Updated'
		);

		echo json_encode($result);

		wp_die();
	}

	public function set_sticky_callback()
	{

		// 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');
		}

		$post_id = $_POST['id'];
		$value = $_POST['value']; // 'true' or ''

		update_post_meta($post_id, '_flothemes_sticky_header_metabox_field', $value);

		echo json_encode(array(
			'message'	=> 'Set Sticky',
			'id'	=> $post_id,
			'newValue' => $value
		));

		wp_die();
	}
}

$options_page_loader = new FLO_OPTIONS_PAGE_LOADER();
$options_page_loader::register_flo_main_options_page();
