<?php
/**
 * Hide Page Title  -  per-page checkbox to suppress the H1/page title on the
 * front-end. Useful when a page uses a shortcode (e.g. [tsm_teacher_portal])
 * that already renders its own heading and the theme's built-in "<h1>page
 * title</h1>" wastes vertical space.
 *
 * Feature is admin-gated via the "Hide Page Title" toggle on the Advanced
 * settings tab so existing sites are unaffected until the school admin
 * activates it.
 *
 * @package TradeSchoolManager
 * @since   1.19.9
 */

if ( ! defined( 'ABSPATH' ) ) { exit; }

class TSM_Page_Title_Hider {

	const OPTION    = 'tsm_page_title_hider_active';
	const META_KEY  = '_tsm_hide_page_title';

	public static function is_active() {
		return (bool) get_option( self::OPTION, 0 );
	}

	public static function init() {
		// Always register the meta so existing per-page settings survive a
		// temporary toggle-off; only the front-end filter is gated.
		add_action( 'init',                array( __CLASS__, 'register_meta' ) );
		add_action( 'add_meta_boxes_page', array( __CLASS__, 'add_classic_metabox' ) );
		add_action( 'save_post_page',      array( __CLASS__, 'save_classic_metabox' ), 10, 2 );
		add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'enqueue_block_editor' ) );

		if ( self::is_active() ) {
			add_filter( 'the_title',     array( __CLASS__, 'maybe_hide_title' ), 10, 2 );
			add_filter( 'body_class',    array( __CLASS__, 'body_class' ) );
			add_action( 'wp_enqueue_scripts', array( __CLASS__, 'maybe_enqueue_css' ), 20 );
		}
	}

	public static function register_meta() {
		register_post_meta( 'page', self::META_KEY, array(
			'show_in_rest'  => true,
			'single'        => true,
			'type'          => 'boolean',
			'default'       => false,
			'auth_callback' => function() { return current_user_can( 'edit_pages' ); },
		) );
	}

	/* -------------------- Classic editor metabox -------------------- */

	public static function add_classic_metabox() {
		add_meta_box(
			'tsm_hide_page_title',
			__( 'Page Title Display', 'tradeschool-manager' ),
			array( __CLASS__, 'render_classic_metabox' ),
			'page',
			'side',
			'default'
		);
	}

	public static function render_classic_metabox( $post ) {
		$hidden = (bool) get_post_meta( $post->ID, self::META_KEY, true );
		wp_nonce_field( 'tsm_hide_page_title_' . $post->ID, 'tsm_hide_page_title_nonce' );
		?>
		<p>
			<label>
				<input type="checkbox" name="tsm_hide_page_title" value="1" <?php checked( $hidden ); ?>>
				<?php esc_html_e( 'Hide the page title on the live page', 'tradeschool-manager' ); ?>
			</label>
		</p>
		<p class="description">
			<?php if ( ! self::is_active() ) : ?>
				<em><?php esc_html_e( 'This feature is currently disabled in TradeSchool -> Settings -> Advanced. Your setting will be saved, but the title will still show on the front-end until the feature is activated.', 'tradeschool-manager' ); ?></em>
			<?php else : ?>
				<?php esc_html_e( 'Useful for pages that already include their own heading (e.g. portal shortcodes).', 'tradeschool-manager' ); ?>
			<?php endif; ?>
		</p>
		<?php
	}

	public static function save_classic_metabox( $post_id, $post ) {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; }
		if ( wp_is_post_revision( $post_id ) ) { return; }
		if ( empty( $_POST['tsm_hide_page_title_nonce'] ) ) { return; }
		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tsm_hide_page_title_nonce'] ) ), 'tsm_hide_page_title_' . $post_id ) ) { return; }
		if ( ! current_user_can( 'edit_page', $post_id ) ) { return; }
		// Only act when our metabox was actually rendered (block editor will
		// usually skip this nonce and rely on REST meta instead).
		if ( ! isset( $_POST['tsm_hide_page_title_nonce'] ) ) { return; }

		$val = ! empty( $_POST['tsm_hide_page_title'] );
		update_post_meta( $post_id, self::META_KEY, $val ? 1 : 0 );
	}

	/* -------------------- Block editor sidebar panel -------------------- */

	public static function enqueue_block_editor() {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || 'page' !== $screen->post_type ) { return; }

		$handle = 'tsm-hide-page-title';
		wp_register_script(
			$handle,
			'',
			array( 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data', 'wp-i18n' ),
			defined( 'TSM_VERSION' ) ? TSM_VERSION : '1',
			true
		);

		$js = "( function( wp ) {\n"
			. "\tif ( ! wp || ! wp.plugins || ! wp.editPost ) { return; }\n"
			. "\tvar el = wp.element.createElement;\n"
			. "\tvar __ = wp.i18n.__;\n"
			. "\tvar PluginDocumentSettingPanel = wp.editPost.PluginDocumentSettingPanel;\n"
			. "\tvar CheckboxControl = wp.components.CheckboxControl;\n"
			. "\tvar useSelect = wp.data.useSelect;\n"
			. "\tvar useDispatch = wp.data.useDispatch;\n"
			. "\tfunction Panel() {\n"
			. "\t\tvar value = useSelect( function( select ) {\n"
			. "\t\t\tvar meta = select( 'core/editor' ).getEditedPostAttribute( 'meta' ) || {};\n"
			. "\t\t\treturn !! meta._tsm_hide_page_title;\n"
			. "\t\t}, [] );\n"
			. "\t\tvar editPost = useDispatch( 'core/editor' ).editPost;\n"
			. "\t\treturn el(\n"
			. "\t\t\tPluginDocumentSettingPanel,\n"
			. "\t\t\t{ name: 'tsm-hide-page-title', title: __( 'Page Title Display', 'tradeschool-manager' ), className: 'tsm-hide-page-title' },\n"
			. "\t\t\tel( CheckboxControl, {\n"
			. "\t\t\t\tlabel: __( 'Hide page title on the live page', 'tradeschool-manager' ),\n"
			. "\t\t\t\tchecked: value,\n"
			. "\t\t\t\tonChange: function( v ) { editPost( { meta: { _tsm_hide_page_title: !! v } } ); }\n"
			. "\t\t\t} ),\n"
			. "\t\t\tel( 'p', { style: { fontSize: '12px', color: '#646970', margin: '8px 0 0' } },\n"
			. "\t\t\t\t__( 'Useful for pages that already render their own heading (e.g. portal shortcodes).', 'tradeschool-manager' )\n"
			. "\t\t\t)\n"
			. "\t\t);\n"
			. "\t}\n"
			. "\twp.plugins.registerPlugin( 'tsm-hide-page-title', { render: Panel, icon: null } );\n"
			. "} )( window.wp );\n";
		wp_add_inline_script( $handle, $js );
		wp_enqueue_script( $handle );
	}

	/* -------------------- Front-end filter -------------------- */

	public static function maybe_hide_title( $title, $post_id = 0 ) {
		if ( is_admin() || ! $post_id ) { return $title; }
		// Only suppress the page H1 inside the main query for the singular page,
		// so navigation menus / widgets / related-posts lists keep their titles.
		if ( ! is_singular( 'page' ) ) { return $title; }
		if ( ! in_the_loop() || ! is_main_query() ) { return $title; }
		$queried = get_queried_object_id();
		if ( (int) $post_id !== (int) $queried ) { return $title; }
		if ( get_post_meta( $post_id, self::META_KEY, true ) ) {
			return '';
		}
		return $title;
	}

	public static function body_class( $classes ) {
		if ( is_singular( 'page' ) ) {
			$id = get_queried_object_id();
			if ( $id && get_post_meta( $id, self::META_KEY, true ) ) {
				$classes[] = 'tsm-hide-page-title';
			}
		}
		return $classes;
	}

	/**
	 * Belt-and-suspenders: some themes render the title via a template tag that
	 * doesn't pipe through the_title filter (e.g. block themes, custom hero
	 * templates). When the meta is set, also hide common page-title selectors
	 * via inline CSS scoped to the body class.
	 */
	public static function maybe_enqueue_css() {
		if ( ! is_singular( 'page' ) ) { return; }
		$id = get_queried_object_id();
		if ( ! $id || ! get_post_meta( $id, self::META_KEY, true ) ) { return; }

		$handle = 'tsm-hide-page-title-css';
		wp_register_style( $handle, false, array(), defined( 'TSM_VERSION' ) ? TSM_VERSION : '1' );
		wp_enqueue_style( $handle );
		wp_add_inline_style(
			$handle,
			'.tsm-hide-page-title .entry-title,'
			. '.tsm-hide-page-title .page-title,'
			. '.tsm-hide-page-title .wp-block-post-title,'
			. '.tsm-hide-page-title header.entry-header > h1,'
			. '.tsm-hide-page-title h1.entry-title,'
			. '.tsm-hide-page-title .elementor-page-title{display:none !important;}'
		);
	}
}
