<?php
function init_filters()
{
	if (!is_admin()) {
		add_action('wp', 'init_public_filters');
		remove_filter('the_content', 'wpautop');
		remove_filter('the_content', 'wptexturize');
	} else {
		add_filter('upload_mimes', 'fgt_additional_mime_types', 100);
		add_filter('manage_fgt_header_posts_columns', 'fgt_add_additional_admin_columns');
		add_filter('manage_fgt_footer_posts_columns', 'fgt_add_additional_admin_columns');
		add_filter('manage_fgt_g_template_posts_columns', 'fgt_add_additional_admin_columns');
		add_filter('manage_fgt_p_template_posts_columns', 'fgt_add_additional_admin_columns');
		add_action('manage_fgt_header_posts_custom_column', 'fgt_add_header_additional_admin_columns_data', 10, 2);
		add_action('manage_fgt_footer_posts_custom_column', 'fgt_add_footer_additional_admin_columns_data', 10, 2);
		add_action('manage_fgt_g_template_posts_custom_column', 'fgt_add_g_template_additional_admin_columns_data', 10, 2);
		add_action('manage_fgt_p_template_posts_custom_column', 'fgt_add_p_template_additional_admin_columns_data', 10, 2);

		add_filter('post_row_actions', 'fgt_remove_row_actions_post', 10, 2);
		add_action('admin_head', 'fgt_trash_post');

		add_action('wp', 'fgt_check_option_permissions');

		add_theme_support('align-wide');
		add_action('admin_enqueue_scripts', 'fgt_enqueue_media');

		// Record theme stats on theme activation and deactivation
		add_action("after_switch_theme", "flo_pronto_register_product");
		add_action('switch_theme', 'flo_pronto_deregister_product', 1);

		add_action("admin_init", array('FLO_COMMON', 'maybe_deactivate_flo_updater'));
		add_action("after_switch_theme", array('FLO_COMMON', 'deactivate_flo_updater'));
	}
}

init_filters();


/*============ BOF record theme stats ============*/

/**
 *
 * Prepare the arguments for the API request to Flothemes.com
 *
 */
if (!function_exists('flo_pronto_get_stats_args')) {
	function flo_pronto_get_stats_args()
	{
		$result = array();
		$theme_data = wp_get_theme(); // get the current theme name

		// do the same thing one more time in case we are working with a child theme
		// to make sure we will get the parrent theme Name
		$theme_data = wp_get_theme($theme_data->Template);

		$result['product_name'] = $theme_data->Name;
		$result['domain_name'] = get_site_url();
		$result['api_url'] = "https://flothemes.com/wp-json/flo/v1/product/";
		//$result['api_url'] = "http://localhost/flocom/wp-json/flo/v1/product/";

		return $result;
	}
}

/**
 *
 * Send an request to the stats API on Flothemes.com
 * this method is used on theme activation, on theme deactivation and on License key activation.
 */
if (!function_exists('flo_pronto_stats_request')) {
	function flo_pronto_stats_request($method = 'POST', $activation_key = '')
	{
		$body_args = flo_pronto_get_stats_args();
		if (strlen(trim($activation_key))) {
			$body_args['activation_key'] = $activation_key;
		}

		$request_args = array(
	  'method' => $method,
	  'body' => $body_args
	);

		// because this code runs after the them was switched
		// if the theme is deactivated, then we should get the name
		// of the theme from the option we've created on activation
		if ($method == 'DELETE') {
			$request_args['body']['product_name'] = get_option('flo_theme_name');
		}

		$response = wp_remote_get($body_args['api_url'], $request_args);
	}
}
// when the theme is activated send and request with the theme name and domain URL

if (!function_exists('flo_pronto_register_product')) {
	function flo_pronto_register_product()
	{
		if (version_compare(phpversion(), '5.4.0', '>=')) {
			$theme_data = flo_pronto_get_stats_args();
			// add to an option the current theme name
			// it will be used when the theme is deactivated
			update_option('flo_theme_name', $theme_data['product_name']);

			// send the request to register the activation of this theme
			flo_pronto_stats_request('POST');
		}
	}
}

if (!function_exists('flo_pronto_deregister_product')) {
	function flo_pronto_deregister_product()
	{
		flo_pronto_stats_request('DELETE');
	}
}
/*============ EOF record theme stats ============*/

function fgt_check_option_permissions()
{
	$current_view = get_current_screen();
	$dev_mode = isset($_COOKIE["fgt_development_mode"]) && $_COOKIE["fgt_development_mode"] === 'active' ? TRUE : FALSE;

	if (!$dev_mode && isset($current_view->id) && $current_view->id === 'edit-fgt_template') {
		if (wp_redirect(admin_url() . 'admin.php?page=parent')) {
			exit;
		}
	}

	if (!$dev_mode && isset($current_view->id) && $current_view->id === 'edit-fgt_header') {
		if (wp_redirect(admin_url() . 'admin.php?page=parent')) {
			exit;
		}
	}

	if (!$dev_mode && isset($current_view->id) && $current_view->id === 'edit-fgt_footer') {
		if (wp_redirect(admin_url() . 'admin.php?page=parent')) {
			exit;
		}
	}
}

function init_public_filters()
{
	add_filter('body_class', 'flo_app_body_classes');
}

function flo_app_body_classes($classes)
{
	$classes[] = 'flextheme';

	if (is_search() || is_archive()) {
		return $classes;
	}

	global $post;

	if (isset($post->ID)) {
		$value = get_post_meta($post->ID, '_flothemes_sidebar_metabox_field', TRUE);
		$classes[] = $value ? 'flextheme_layout_' . $value : 'flextheme_layout_default';
	}

	return $classes;
}

function fgt_remove_row_actions_post($actions, $post)
{
	global $post;

	if (!isset($post)) {
		return;
	}
	$default_headers = json_decode(get_option('default_headers'), TRUE);
	$default_footers = json_decode(get_option('default_footers'), TRUE);
	$templates = json_decode(get_option('fgt_templates_array'), TRUE);

	if ($post->post_type === 'fgt_template' || $post->post_type === 'fgt_p_template' || $post->post_type === 'fgt_g_template' && $templates && isset($post->ID)) {
		foreach ($templates as $key => $value) {
			$undelitable_IDs[] = $value;
		}
	}

	if ($post->post_type === 'fgt_footer' || $post->post_type === 'fgt_header' && isset($post->ID)) {
		foreach ($default_headers as $key => $value) {
			$undelitable_IDs[] = $value['edit_id'];
		}
		foreach ($default_footers as $key => $value) {
			$undelitable_IDs[] = $value['edit_id'];
		}
	}

	if (isset($undelitable_IDs) && in_array($post->ID, $undelitable_IDs)) {
		unset($actions['trash']);
		unset($actions['inline hide-if-no-js']);
	}

	return $actions;
}

function fgt_trash_post()
{
	global $post;

	if (!isset($post)) {
		return;
	}

	$default_headers = json_decode(get_option('default_headers'), TRUE);
	$default_footers = json_decode(get_option('default_footers'), TRUE);
	$templates = json_decode(get_option('fgt_templates_array'), TRUE);
	$rules = ['fgt_header', 'fgt_footer', 'fgt_template', 'fgt_p_template', 'fgt_g_template'];

	if ($post->post_type === 'fgt_template' || $post->post_type === 'fgt_p_template' || $post->post_type === 'fgt_g_template' && $templates && isset($post->ID)) {
		foreach ($templates as $key => $value) {
			$undelitable_IDs[] = $value;
		}

		if (in_array($post->ID, $undelitable_IDs)) { ?>
      <style>
        .components-panel__body.edit-post-post-status {
          display: none;
        }
      </style>
    <?php }
	}

	if ($post->post_type === 'fgt_footer' || $post->post_type === 'fgt_header' && isset($post->ID)) {
		foreach ($default_headers as $key => $value) {
			$undelitable_IDs[] = $value['edit_id'];
		}
		foreach ($default_footers as $key => $value) {
			$undelitable_IDs[] = $value['edit_id'];
		}
	}

	if (in_array($post->post_type, $rules) && in_array($post->ID, $undelitable_IDs)) { ?>
    <style>
      .components-panel__body.edit-post-post-status {
        display: none;
      }

      .editor-post-save-draft,
      .edit-post-post-visibility,
      .edit-post-post-schedule,
      .edit-post-post-schedule+.components-panel__row,
      .editor-post-switch-to-draft,
      .editor-post-publish-panel__prepublish {
        display: none;
      }
    </style>
<?php }
}

function fgt_add_header_additional_admin_columns_data($column, $post_id)
{
	if ('is_global' === $column) {
		$is_global = get_post_meta($post_id, '_flothemes_global_header_metabox_field', TRUE);

		if (!$is_global) {
			_e('');
		} else {
			echo 'Global Header';
		}
	}
}

function fgt_add_additional_admin_columns($columns)
{
	$columns = array(
	'cb' => $columns['cb'],
	'title' => __('Title'),
	'is_global' => __('Global', 'flothemes'),
  );

	return $columns;
}


function fgt_add_footer_additional_admin_columns_data($column, $post_id)
{
	if ('is_global' === $column) {
		$is_global = get_post_meta($post_id, '_flothemes_global_footer_metabox_field', TRUE);

		if (!$is_global) {
			_e('');
		} else {
			echo 'Global Footer';
		}
	}
}

function fgt_add_g_template_additional_admin_columns_data($column, $post_id)
{
	if ('is_global' === $column) {
		$is_global = get_post_meta($post_id, '_flothemes_global_g_template_metabox_field', TRUE);

		if (!$is_global) {
			_e('');
		} else {
			echo 'Global Gallery Template';
		}
	}
}

function fgt_add_p_template_additional_admin_columns_data($column, $post_id)
{
	if ('is_global' === $column) {
		$is_global = get_post_meta($post_id, '_flothemes_global_p_template_metabox_field', TRUE);

		if (!$is_global) {
			_e('');
		} else {
			echo 'Global Post Template';
		}
	}
}

function fgt_additional_mime_types($mimes)
{
	$mimes['ico'] = 'image/x-icon';
	$mimes['ttf'] = 'font/ttf';
	$mimes['otf'] = 'font/otf';
	$mimes['woff'] = 'application/font-woff';
	$mimes['svg'] = 'image/svg+xml';
	// $mimes['svg'] = 'image/svg';
	$mimes['json'] = 'text/plain';

	return $mimes;
}

/**
 * Add support for media uploader
 */
function fgt_enqueue_media()
{
	wp_enqueue_media();
}

/**
 * format text from old classic editors and wrap in p tags
 */
function pronto_formatter($content)
{
	$new_content = '';
	$pattern_full = '{(\[raw\].*?\[/raw\])}is';
	$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
	$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

	foreach ($pieces as $piece) {
		if (preg_match($pattern_contents, $piece, $matches)) {
			$new_content .= $matches[1];
		} else {
			$new_content .= wptexturize(wpautop($piece));
		}
	}
	return $new_content;
}
