<?php

/**
 * Sanaprassi functions and definitions.
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 * @package Sanaprassi
 *
 */

include_once get_template_directory() . '/sprssi_options.php';
include_once get_template_directory() . '/sprssi_settings.php';
include_once get_template_directory() . '/utilities.php';
include_once get_template_directory() . '/template_redirects.php';
include_once get_template_directory() . '/sanaprassi-update-utils.php';



// Adds theme support for post formats.
if (! function_exists('sanaprassi_post_format_setup')) :
	/**
	 * Adds theme support for post formats.
	 *
	 *
	 * @return void
	 */
	function sanaprassi_post_format_setup()
	{
		add_theme_support('post-formats', array('aside', 'audio', 'chat', 'gallery', 'image', 'link', 'quote', 'status', 'video'));
	}
endif;
add_action('after_setup_theme', 'sanaprassi_post_format_setup');

// Enqueues editor-style.css in the editors.
if (! function_exists('sanaprassi_editor_style')) :
	/**
	 * Enqueues editor-style.css in the editors.
	 *
	 *
	 * @return void
	 */
	function sanaprassi_editor_style()
	{
		add_editor_style('assets/css/editor-style.css');
	}
endif;
add_action('after_setup_theme', 'sanaprassi_editor_style');

// Enqueues style.css on the front.
if (! function_exists('sanaprassi_enqueue_styles')) :
	/**
	 * Enqueues style.css on the front.
	 *
	 *
	 * @return void
	 */
	function sanaprassi_enqueue_styles()
	{
		wp_enqueue_style(
			'sanaprassi-style',
			get_parent_theme_file_uri('style.css'),
			array(),
			wp_get_theme()->get('Version')
		);
	}
endif;
add_action('wp_enqueue_scripts', 'sanaprassi_enqueue_styles');

// Registers custom block styles.
if (! function_exists('sanaprassi_block_styles')) :
	/**
	 * Registers custom block styles.
	 *
	 *
	 * @return void
	 */
	function sanaprassi_block_styles()
	{
		register_block_style(
			'core/list',
			array(
				'name'         => 'checkmark-list',
				'label'        => __('Checkmark', 'sanaprassi'),
				'inline_style' => '
				ul.is-style-checkmark-list {
					list-style-type: "\2713";
				}

				ul.is-style-checkmark-list li {
					padding-inline-start: 1ch;
				}',
			)
		);
	}
endif;
add_action('init', 'sanaprassi_block_styles');

// Registers pattern categories.
if (! function_exists('sanaprassi_pattern_categories')) :
	/**
	 * Registers pattern categories.
	 *
	 *
	 * @return void
	 */
	function sanaprassi_pattern_categories()
	{

		register_block_pattern_category(
			'sanaprassi_page',
			array(
				'label'       => __('Pages', 'sanaprassi'),
				'description' => __('A collection of full page layouts.', 'sanaprassi'),
			)
		);

		register_block_pattern_category(
			'sanaprassi_post-format',
			array(
				'label'       => __('Post formats', 'sanaprassi'),
				'description' => __('A collection of post format patterns.', 'sanaprassi'),
			)
		);
	}
endif;
add_action('init', 'sanaprassi_pattern_categories');

// Registers block binding sources.
if (! function_exists('sanaprassi_register_block_bindings')) :
	/**
	 * Registers the post format block binding source.
	 *
	 *
	 * @return void
	 */
	function sanaprassi_register_block_bindings()
	{
		register_block_bindings_source(
			'sanaprassi/format',
			array(
				'label'              => _x('Post format name', 'Label for the block binding placeholder in the editor', 'sanaprassi'),
				'get_value_callback' => 'sanaprassi_format_binding',
			)
		);
	}
endif;
add_action('init', 'sanaprassi_register_block_bindings');







// Registers block binding callback function for the post format name.
if (! function_exists('sanaprassi_format_binding')) :
	/**
	 * Callback function for the post format name block binding source.
	 *
	 *
	 * @return string|void Post format name, or nothing if the format is 'standard'.
	 */
	function sanaprassi_format_binding()
	{
		$post_format_slug = get_post_format();

		if ($post_format_slug && 'standard' !== $post_format_slug) {
			return get_post_format_string($post_format_slug);
		}
	}
endif;


/* Disable tags, search, category, author archives */
function disable_unwanted_endpoints()
{
	if (is_tag() || is_search() || is_category() || is_author()) {
		wp_redirect(home_url(), 301);
		exit;
	}
}
add_action('template_redirect', 'disable_unwanted_endpoints');



// Disable comments
add_action('admin_init', function () {
	// Remove comments menu
	remove_menu_page('edit-comments.php');
	// Disable support for comments and trackbacks in post types
	foreach (get_post_types() as $post_type) {
		if (post_type_supports($post_type, 'comments')) {
			remove_post_type_support($post_type, 'comments');
			remove_post_type_support($post_type, 'trackbacks');
		}
	}
});


if (! function_exists('dashboard_redirect')) :
	function dashboard_redirect()
	{
		wp_redirect(admin_url('edit.php?post_type=page'));
	}
endif;
add_action('load-index.php', 'dashboard_redirect');

if (! function_exists('login_redirect')) :
	function login_redirect($redirect_to, $request, $user)
	{
		return admin_url('edit.php?post_type=page');
	}
endif;
add_filter('login_redirect', 'login_redirect', 10, 3);

if (! function_exists('remove_menus')) :
	function remove_menus()
	{
		// https://developer.wordpress.org/reference/functions/remove_submenu_page/
		global $menu;
		$restricted = array(__('Dashboard'), __('Comments'), __('Tools'), __('Posts'));
		if (eval_option(sprssi_options::$allow_posts)) {
			$restricted = array(__('Dashboard'), __('Comments'), __('Tools'));
		}
		if (eval_option(sprssi_options::$debug_mode)) {
			$restricted = array();
		}
		//$restricted = array(__('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins'));
		end($menu);
		while (prev($menu)) {
			$value = explode(' ', $menu[key($menu)][0]);
			if (in_array($value[0] != NULL ? $value[0] : '', $restricted)) {
				unset($menu[key($menu)]);
			}
		}
		if (! eval_option(sprssi_options::$debug_mode)) {
			remove_submenu_page('options-general.php', 'options-privacy.php');
			remove_submenu_page('options-general.php', 'options-permalink.php');
			remove_submenu_page('options-general.php', 'options-discussion.php');
			remove_submenu_page('options-general.php', 'options-writing.php');
			remove_submenu_page('options-general.php', 'options-reading.php');
			remove_submenu_page('options-general.php', 'options-general.php');
			// We add the custom-settings.php from this dir to the submenu as alternative version for options-general.php
		}
	}
endif;
add_action('admin_menu', 'remove_menus');


if (! function_exists('add_custom_settings_submenu')) :
	function add_custom_settings_submenu()
	{

		if (! function_exists('custom_settings_content_page')) :
			function custom_settings_content_page()
			{
				// Include the custom settings page content
				include_once dirname(__FILE__) . '/custom-settings.php';
			}
		endif;
		add_submenu_page('options-general.php', __('General Settings', 'sanaprassi'), __('General Settings', 'sanaprassi'), 'administrator', get_template_directory() . '/custom-settings.php', 'custom_settings_content_page', 1);
		// We include the wp-admin/update-code.php as a submenu item for maintenance tasks (so not a template directory but the actual core file)
		add_submenu_page('options-general.php', __('Update', 'sanaprassi'), __('Update', 'sanaprassi'), 'administrator', 'update-core.php');
		// Add update menu item under options-general.php
	}
endif;
add_action('admin_menu', 'add_custom_settings_submenu');


// Redirect the dashboard page wp icon to pages list
/* <a class="ab-item" role="menuitem" aria-expanded="false" href="http://localhost:8888/wp-admin/about.php"><span class="ab-icon" aria-hidden="true"></span><span class="screen-reader-text">About WordPress</span></a> */
if (! function_exists('custom_admin_bar_menu')) :
	function custom_admin_bar_menu($wp_admin_bar)
	{
		$args = array(
			'id'    => 'wp-logo',
			'title' => '<span class="ab-icon" aria-hidden="true"></span><span class="screen-reader-text">' . __('Dashboard') . '</span>',
			'href'  => admin_url('edit.php?post_type=page'),
			'meta'  => array(
				'class' => 'ab-item',
				'title' => __('Dashboard'),
			),
		);
		$wp_admin_bar->add_node($args);
	}
endif;
add_action('admin_bar_menu', 'custom_admin_bar_menu', 999);


// Remove new>post from admin bar

if (! function_exists('remove_new_post_from_admin_bar')) :
	function remove_new_post_from_admin_bar($wp_admin_bar)
	{
		if (get_option(sprssi_options::$allow_posts) === '0') {
			$wp_admin_bar->remove_node('new-post');
		}
		$wp_admin_bar->remove_node('comments');
		$wp_admin_bar->remove_menu('site-editor');
	}
endif;
add_action('admin_bar_menu', 'remove_new_post_from_admin_bar', 999);


// Adjust admin bar button with a plus to direct to new page creation instead of post
/* <a class="ab-item" role="menuitem" aria-expanded="false" href="https://www.karkkonen.fi/wp-admin/post-new.php"><span class="ab-icon" aria-hidden="true"></span><span class="ab-label">New</span></a> */
if (! function_exists('custom_new_content_admin_bar_menu')) :
	function custom_new_content_admin_bar_menu($wp_admin_bar)
	{
		$args = array(
			'id'    => 'new-content',
			'title' => '<span class="ab-icon" aria-hidden="true"></span><span class="ab-label">' . __('New') . '</span>',
			'href'  => admin_url('post-new.php?post_type=page'),
			'meta'  => array(
				'class' => 'ab-item',
				'title' => __('Create New Page'),
			),
		);
		$wp_admin_bar->add_node($args);
	}
endif;
add_action('admin_bar_menu', 'custom_new_content_admin_bar_menu', 998);




// Set custom css
if (! function_exists('custom_admin_css')) :
	function custom_admin_css()
	{
		return '
/* ==START OF CUSTOM CSS SANAPRÄSSI== */
		
wp-site-blocks > *, wp-site-blocks > *::before, wp-site-blocks > *::after {
box-sizing: border-box !important;
max-width: 100% ;
}

.is-layout-constrained > :where(:not(.alignleft):not(.alignright):not(.alignfull)) { 
margin-left: unset !important;
margin-right: unset !important;
}

h1, h2, h3, h4, h5, h6, p, span, a, *[aria-label="List text"], ul > li {
max-width: min(50ch, 100%) !important;
}

.wp-block-button__link.wp-element-button {
white-space: nowrap;
text-align: center;
min-width: fit-content !important;
}

.imgs > figure {
max-width: 100% !important;
}

.imgs > figure {
overflow: hidden !important;
}

a {
word-break: break-all !important;
} 



.max-w {
max-width: min(1200px, 95%);
margin-left: auto !important;
margin-right: auto !important;
}

.max-w-nocenter {
max-width: min(1200px, 95%);
}

.max-w-col {
max-width: min(1200px, 95%);
margin-left: auto !important;
margin-right: auto !important;
}


@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}

.fade-content {
animation: fadeIn 0.3s ease-in-out;
}

.wp-block-post-content {
animation: fadeIn 0.3s ease-in-out;
}



.relative {
position: relative;
}

.absolute {
position: absolute;
}


a, button {
transition: text-shadow 0.1s;
}

:where(.wp-site-blocks *:focus) {
outline: none !important;
border: none !important;
}



m-0 {
margin-left: 0 !important;
margin-right: 0 !important;
}

.hehku > * {
  z-index: 1;
text-shadow:
    0 0 8px rgba(255, 193, 113, 0.2);
/*  white-space: nowrap;*/
  word-break: initial;
}
	
p > a {
font-size: inherit !important;
}
		

/* ==END OF CUSTOM CSS== */
			
		';
	}
endif;
if (! function_exists('custom_admin_css_enqueue')) :
	function custom_admin_css_enqueue()
	{
		if (! current_user_can('edit_theme_options')) {
			return;
		}
		if (eval_option(sprssi_options::$custom_css_set)) {
			_log_to_console('Custom admin CSS already set, skipping.');
			return;
		}


		// If the active theme is a block theme (has theme.json), use Global Styles.
		if (function_exists('wp_theme_has_theme_json') && wp_theme_has_theme_json()) { // WP 6.2+
			$css = custom_admin_css();
			$id = WP_Theme_JSON_Resolver::get_user_global_styles_post_id(); // gets/creates the correct CPT ID
			_log_to_console('Fetching existing global styles, post ID: ' . $id);
			if ($id) {
				$current_custom_style = new WP_REST_Request('GET', '/wp/v2/global-styles/' . $id);
				$response = rest_do_request($current_custom_style);
				$existing_styles = '';
				if (! is_wp_error($response) && $response->get_status() >= 200 && $response->get_status() < 300) {
					$existing_styles = $response->get_data();
					_log_to_console('Fetched existing global styles successfully.');
					_log_to_console($existing_styles);
				}
				$request = new WP_REST_Request('POST', '/wp/v2/global-styles/' . $id);
				// Set params directly. No json_encode needed for $css.
				$request->set_param('id', $id);
				$request->set_param('styles', array('css' => $css));
				_log_to_console('Setting custom admin CSS via Global Styles, post ID: ' . $id);

				$response = rest_do_request($request);
				update_option(sprssi_options::$custom_css_set, '1');
				if (! is_wp_error($response) && $response->get_status() >= 200 && $response->get_status() < 300) {
					_log_to_console('Custom admin CSS set successfully via Global Styles.');
					// Clear theme.json/global styles cache so changes show up immediately.
					if (function_exists('wp_clean_theme_json_cache')) {
						wp_clean_theme_json_cache();
						_log_to_console('Cleared theme.json cache.');
					} else {
						if (method_exists('WP_Theme_JSON_Resolver', 'clean_cached_data')) {
							WP_Theme_JSON_Resolver::clean_cached_data();
							_log_to_console('Cleared WP_Theme_JSON_Resolver cache.');
						}
					}
				}
			}
		} else {
			// Classic theme: seed Customizer Additional CSS instead.
			$r = wp_update_custom_css_post(custom_admin_css());
			if (! is_wp_error($r)) {
				update_option(sprssi_options::$custom_css_set, 1);
			}
		}
	}
endif;
add_action('admin_head', 'custom_admin_css_enqueue');





// Redirect the user to site-editor (aka site-editor.php?p=%2Fpage&postId=6&canvas=edit) instead of (post.php?post=6&action=edit) when editing pages
if (! function_exists('redirect_page_edit_to_site_editor')) :
	function redirect_page_edit_to_site_editor()
	{
		$post_id = isset($_GET['post']) ? intval($_GET['post']) : 0;
		if ($post_id) {
			$post = get_post($post_id);
			if ($post && $post->post_type === 'page') {
				$site_editor_url = admin_url('site-editor.php?p=%2Fpage&postId=' . $post_id . '&canvas=edit');
				wp_redirect($site_editor_url);
				exit;
			}
		}
	}
endif;
add_action('load-post.php', 'redirect_page_edit_to_site_editor');

// Rewrite the edit-link text to "Edit with Site Editor"
if (! function_exists('rewrite_edit_post_link_to_site_editor')) :
	function rewrite_edit_post_link_to_site_editor($link, $post_id, $context)
	{
		$post = get_post($post_id);
		if ($post && $post->post_type === 'page') {
			$site_editor_url = admin_url('site-editor.php?p=%2Fpage&postId=' . $post_id . '&canvas=edit');
			return $site_editor_url;
		}
		return $link;
	}
endif;
add_filter('get_edit_post_link', 'rewrite_edit_post_link_to_site_editor', 10, 3);





// For editor css ease

if (! function_exists('wp_blocks_fullwidth')) :
	function wp_blocks_fullwidth()
	{
		echo '<style>
			.interface-complementary-area .edit-site-global-styles-sidebar {
							min-width: 100% !important;
			}

			.interface-complementary-area__fill {
				width: auto !important;
				max-width: 33vw !important;
				
				@media all and (min-width: 1000px) {
				
				max-width: 25vw !important;
				}
				
				& p {
				font-size: 0.8rem;
				
				}
			}
			
			#inspector-textarea-control-0 {
			font-size: 0.8rem !important;
			overflow-x: scroll !important;
			overflow-wrap: anywhere !important;
			white-space: nowrap !important;
			line-height: 0.9rem !important;
			}

			.interface-complementary-area.edit-site-global-styles-sidebar {
							min-width: 100% !important;
							width: 30% !important;
							max-width: 30% !important;
			}
				@media (min-width: 782px) {
 		   .editor-sidebar {
        	width: 100% !important;
    		}
		}

        /*.wp-block {
            max-width: unset;
			}*/
</style>';
	};
endif;
add_action('admin_head', 'wp_blocks_fullwidth');


/* Disable all commenting endpoints
 * This will remove all REST API endpoints related to comments and prevent any interaction with comments via the REST API.
 */
add_filter('rest_endpoints', function ($endpoints) {
	$endpointsToRemove = [
		'comments',
		'/wp/v2/comments',
		'/wp/v2/comments/(?P<id>[\d]+)',
	];

	foreach ($endpointsToRemove as $endpoint) {
		if (isset($endpoints[$endpoint])) {
			unset($endpoints[$endpoint]);
		}
	}

	return $endpoints;
});



/* Disable ALL REST API endpoints unless authenticated */
add_filter('rest_authentication_errors', function ($result) {
	// If a previous authentication check was applied,
	// pass that result along without modification.
	if (true === $result || is_wp_error($result)) {
		return $result;
	}

	// No authentication has been performed yet.
	// Return an error if user is not logged in.
	if (! is_user_logged_in()) {
		return new WP_Error(
			'rest_not_logged_in',
			__('You are not currently logged in.'),
			array('status' => 401)
		);
	}
	// Our custom authentication check should have no effect
	// on logged-in requests
	return $result;
});


if (! function_exists('delete_post_if_exists')) :
	function delete_post_if_exists($post_title, $post_type = 'page')
	{
		$query = new WP_Query(array(
			'post_type'      => $post_type,
			'title'          => $post_title,
		));
		if ($query->have_posts()) {
			while ($query->have_posts()) {
				$query->the_post();
				wp_delete_post(get_the_ID(), true);
			}
			wp_reset_postdata();
		}
	}
endif;

// Set default content on first run
if (! function_exists('set_default_content')) :
	function set_default_content()
	{

		if (eval_option(sprssi_options::$settings_set)) {
			return;
		}



		update_option('show_on_front', 'page'); // Set front page to static page
		update_option('page_for_posts', -1); // Unset posts page
		update_option('default_post_format', 0); // Unset posts page
		update_option('ping_sites', ''); // Disable pingbacks

		update_option('default_comment_status', 'closed'); // Disable comments by default
		update_option('default_ping_status', 'closed'); // Disable pingbacks by default
		update_option('users_can_register', false); // Disable user registration
		update_option('time_format', 'H:i'); // Set time format (24h)
		update_option('date_format', 'd.m.Y'); // Set date format (dd.mm.yyyy)
		update_option('start_of_week', 1); // Set start of week to Monday
		update_option('permalink_structure', '/%postname%/'); // Set permalink structure to post name

		update_option(sprssi_options::$settings_set, "1");
	}
endif;
add_action('admin_init', 'set_default_content');




if (! function_exists('front_page_setup')) :
	function front_page_setup()
	{
		if (eval_option(sprssi_options::$front_page_setup_done)) {
			return;
		}
		$front_page_id = get_option('page_on_front');
		if (! $front_page_id) {
			// Create a new page
			$front_page = array(
				'post_title'   => 'Home',
				'post_content' => '',
				'post_status'  => 'publish',
				'post_type'    => 'page',
			);
			$front_page_id = wp_insert_post($front_page);
			// Set the new page as the front page
			update_option('page_on_front', $front_page_id);
			update_option(sprssi_options::$front_page_setup_done, "1");
		}
	}
endif;
add_action('admin_init', 'front_page_setup');





if (! function_exists('sanaprassi_allowed_block_types')) :
	function sanaprassi_allowed_block_types($allowed_blocks, $post)
	{
		$allowed = array(
			'core/paragraph',
			'core/heading',
			'core/list',
			'core/quote',
			'core/code',
			'core/details',
			'core/preformatted',
			'core/pullquote',
			'core/table',
			'core/verse',

			'core/image',
			'core/gallery',
			'core/audio',
			'core/cover',
			'core/file',
			'core/media-text',
			'core/video',

			'core/buttons',
			'core/button',
			'core/columns',
			'core/column',
			'core/group',
			'core/row',
			'core/stack',

			'core/grid',
			/* 'core/more', */
			/* 'core/page-break', */
			'core/separator',
			'core/spacer',

			/* 'core/archives', */
			'core/calendar',
			'core/html',
			'core/page-list',
			'core/social-links',

			'core/navigation',
			'core/site-logo',
			'core/site-title',
			'core/site-tagline',
			'core/title',
			'core/featured-image',

			'core/embed',

			// Allow patterns as normal
			'core/block'
		);
		if (eval_option(sprssi_options::$allow_posts)) {
			// Append post-related blocks if allowed
			$allowed[] = 'core/post-content';
			$allowed[] = 'core/post-title';
			$allowed[] = 'core/post-excerpt';
			$allowed[] = 'core/post-featured-image';
			$allowed[] = 'core/query';
		}
		return $allowed;
	};
endif;
add_filter('allowed_block_types_all', 'sanaprassi_allowed_block_types', 10, 2);
add_filter('should_load_remote_block_patterns', '__return_false');





if (! function_exists('remove_preset_plugins')) :
	function remove_preset_plugins()
	{
		require_once(ABSPATH . 'wp-admin/includes/plugin.php');
		require_once(ABSPATH . 'wp-admin/includes/file.php');
		if (file_exists(WP_PLUGIN_DIR . '/hello.php')) :
			delete_plugins(array('hello.php'));
		endif;
		if (file_exists(WP_PLUGIN_DIR . '/akismet/akismet.php')) :
			delete_plugins(array('akismet/akismet.php'));
		endif;
	}
endif;


if (! function_exists('cleanup_bloat')) :
	function cleanup_bloat()
	{
		if (eval_option(sprssi_options::$default_content_deleted)) {
			return;
		}
		// Delete default "Sample Page"
		delete_post_if_exists('Sample Page', 'page');
		//delete_post_if_exists('Privacy Policy', 'page');
		// Delete default "Hello world!" post
		delete_post_if_exists('Hello world!', 'post');

		// Set the template for the front page to "Index"
		$front_page_id = get_option('page_on_front');
		if ($front_page_id) {
			update_post_meta($front_page_id, '_wp_page_template', 'index');
		}
		// Remove preset plugins
		remove_preset_plugins();
		update_option(sprssi_options::$default_content_deleted, "1");
	}
endif;
add_action('admin_init', 'cleanup_bloat');



// Echo .htaccess rules to root directory if not present to handle cases with wp-json
/* api-fetch.js?ver=52446bd41c30bc419a05:712  POST http://localhost:8888/wp-json/wp/v2/pages/3?_locale=user 404 (Not Found)
api-fetch.js?ver=52446bd41c30bc419a05:712  GET http://localhost:8888/wp-json/wp/v2/pages/1?context=edit&_locale=user 404 (Not Found) etc... */
if (! function_exists('ensure_htaccess_rules')) :
	function ensure_htaccess_rules()
	{
		if (eval_option(sprssi_options::$htaccess_rules_added)) {
			return;
		}
		$htaccess_path = ABSPATH . '.htaccess';
		$required_rules = "# BEGIN Sanaprassi Theme Rules
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END Sanaprassi Theme Rules
";

		if (file_exists($htaccess_path)) {
			$old_htaccess_content = file_get_contents($htaccess_path);

			// Create a copy of the old .htaccess file as backup
			$backup_path = ABSPATH . 'backup.htaccess_' . date('Ymd_His');
			file_put_contents($backup_path, $old_htaccess_content);
		}
			// Create .htaccess with the required rules
		file_put_contents($htaccess_path, $required_rules);
	}
	update_option(sprssi_options::$htaccess_rules_added, "1");

endif;
add_action('admin_init', 'ensure_htaccess_rules');





if (! function_exists('hide_template_switcher_in_site_editor')) :
	function hide_template_switcher_in_site_editor()
	{
		if (get_option(sprssi_options::$debug_mode) === '1') {
			$hide_str = 'opacity: 0.5;color: red !important;';
		} else {
			$hide_str = 'display: none !important;';
		}
		echo '<style>
		/* Hide unneeded settings in site editor */
		div.components-flex.components-h-stack.editor-post-panel__row:has(>div.editor-post-panel__row-control > div > button[aria-label="Template options"]),
		div.components-flex.components-h-stack.editor-post-panel__row:has(>div.editor-post-panel__row-control > div > button[aria-label="Change discussion options"]) {
			' . $hide_str . '
		}
		

		div:has(>button#template-navigation-item) {
			' . $hide_str . '
		}

		div:has(>button#template-navigation-item) > * {
			' . $hide_str . '
		}
	</style>
	
	<script>
		// Remove div[data-value="Add new post"] 
		/*document.addEventListener("DOMContentLoaded", function() {
			const observer = new MutationObserver(function(mutations) {
				mutations.forEach(function(mutation) {
					mutation.addedNodes.forEach(function(addedNode) {
						if (addedNode.nodeType === Node.ELEMENT_NODE) {
							const newPostOption = addedNode.querySelector(\'div[data-value="Add new post"]\');
							if (newPostOption) {
								newPostOption.remove();
							}
						}
					});
				});
			});

			observer.observe(document.body, { childList: true, subtree: true });
		});*/
	</script>
	';
	};
endif;
add_action('admin_head', 'hide_template_switcher_in_site_editor');
