<?php
/**
 * TradeSchool Focus Mode
 *
 * Hides the WordPress admin sidebar while the user is on any TradeSchool
 * admin page, making the TradeSchool menu the primary navigation.
 *
 * Per-user opt-in (stored in user meta). Top WP admin bar stays visible so
 * Updates / profile / other plugins remain reachable. An "Exit to WordPress"
 * button is added to the admin bar and pinned at the top of the TS menu.
 *
 * @package TradeSchool_Manager
 * @since   1.10.38
 */

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

class TSMP_Focus_Mode {

	const META_KEY = 'tsm_focus_mode';

	public static function init() {
		add_action( 'admin_init',          array( __CLASS__, 'handle_toggle' ) );
		add_action( 'admin_bar_menu',      array( __CLASS__, 'admin_bar_node' ), 100 );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
		add_filter( 'admin_body_class',    array( __CLASS__, 'body_class' ) );
	}

	/** Per-user toggle. */
	public static function is_enabled( $user_id = 0 ) {
		$user_id = $user_id ?: get_current_user_id();
		if ( ! $user_id ) {
			return false;
		}
		// v1.14.0: default ON. User can opt-out via the toggle; opt-out is
		// stored as the literal "0" string, so we only treat unset/empty as default.
		$val = get_user_meta( $user_id, self::META_KEY, true );
		if ( '' === $val || null === $val ) {
			return true;
		}
		return (bool) $val;
	}

	/** Are we on a TradeSchool admin page? */
	public static function is_tsm_page() {
		if ( ! is_admin() ) {
			return false;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only page detection from $_GET['page']; no state change.
		$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		if ( '' === $page ) {
			return false;
		}
		return ( 0 === strpos( $page, 'tsm-' ) ) || ( 0 === strpos( $page, 'tsmp-' ) );
	}

	/** True only when focus mode should be applied right now. */
	public static function is_active() {
		return self::is_enabled() && self::is_tsm_page();
	}

	/** Handle ?tsm_focus=on|off toggle links. */
	public static function handle_toggle() {
		if ( ! isset( $_GET['tsm_focus'] ) || ! is_user_logged_in() ) {
			return;
		}
		check_admin_referer( 'tsm_focus_toggle' );

		$val = sanitize_text_field( wp_unslash( $_GET['tsm_focus'] ) );
		update_user_meta( get_current_user_id(), self::META_KEY, ( 'on' === $val ) ? 1 : 0 );

		$redirect = isset( $_GET['redirect_to'] )
			? esc_url_raw( wp_unslash( $_GET['redirect_to'] ) )
			: admin_url( 'admin.php?page=tsm-dashboard' );

		// If turning off, default to WP dashboard.
		if ( 'off' === $val && ! isset( $_GET['redirect_to'] ) ) {
			$redirect = admin_url( 'index.php' );
		}
		wp_safe_redirect( $redirect );
		exit;
	}

	public static function body_class( $classes ) {
		if ( self::is_active() ) {
			$classes .= ' tsm-focus-mode';
		}
		return $classes;
	}

	/** Toggle in the admin bar (always visible to logged-in admins). */
	public static function admin_bar_node( $wp_admin_bar ) {
		if ( ! current_user_can( 'manage_options' ) && ! current_user_can( 'edit_posts' ) ) {
			return;
		}
		$enabled = self::is_enabled();
		$label   = $enabled
			? '<> ' . __( 'Exit TradeSchool Focus', 'tradeschool-manager' )
			: '<> ' . __( 'TradeSchool Focus Mode', 'tradeschool-manager' );

		$url = wp_nonce_url(
			add_query_arg( 'tsm_focus', $enabled ? 'off' : 'on', admin_url() ),
			'tsm_focus_toggle'
		);

		$wp_admin_bar->add_node( array(
			'id'    => 'tsm-focus-toggle',
			'title' => $label,
			'href'  => $url,
			'meta'  => array( 'title' => __( 'Toggle TradeSchool focus mode (hide WP sidebar)', 'tradeschool-manager' ) ),
		) );
	}

	public static function enqueue_assets() {
		if ( ! self::is_active() ) {
			return;
		}

		$style_handle = 'tsm-focus-mode';
		wp_register_style( $style_handle, false, array(), defined( 'TSM_VERSION' ) ? TSM_VERSION : '1' );
		wp_enqueue_style( $style_handle );
		wp_add_inline_style(
			$style_handle,
			'
			body.tsm-focus-mode #adminmenumain,
			body.tsm-focus-mode #adminmenuwrap,
			body.tsm-focus-mode #adminmenuback { display: none !important; }
			body.tsm-focus-mode #wpcontent,
			body.tsm-focus-mode #wpfooter { margin-left: 0 !important; }
			body.tsm-focus-mode.auto-fold #wpcontent,
			body.tsm-focus-mode.auto-fold #wpfooter { margin-left: 0 !important; }
			body.tsm-focus-mode #wpbody-content { padding-top: 0; }

			/* Pinned exit bar above page content */
			.tsm-focus-exitbar {
				display: flex; align-items: center; justify-content: space-between;
				gap: 12px; padding: 10px 16px; margin: 0 0 16px;
				background: #1f2937; color: #f9fafb;
				border-radius: 0 0 8px 8px;
				box-shadow: 0 2px 6px rgba(0,0,0,.15);
				font-size: 13px;
			}
			.tsm-focus-exitbar .tsm-focus-brand { font-weight: 600; letter-spacing: .3px; }
			.tsm-focus-exitbar .tsm-focus-brand .dashicons { vertical-align: middle; margin-right: 6px; color: #60a5fa; }
			.tsm-focus-exitbar a.tsm-focus-exit {
				display: inline-flex; align-items: center; gap: 6px;
				background: #2563eb; color: #fff !important;
				padding: 6px 12px; border-radius: 6px;
				text-decoration: none; font-weight: 600;
			}
			.tsm-focus-exitbar a.tsm-focus-exit:hover { background: #1d4ed8; }
			.tsm-focus-exitbar a.tsm-focus-exit .dashicons { font-size: 16px; height: 16px; width: 16px; }
			'
		);

		$exit_url = wp_nonce_url(
			add_query_arg(
				array(
					'tsm_focus'   => 'off',
					'redirect_to' => rawurlencode( admin_url( 'index.php' ) ),
				),
				admin_url()
			),
			'tsm_focus_toggle'
		);

		$script_handle = 'tsm-focus-mode';
		wp_register_script( $script_handle, false, array(), defined( 'TSM_VERSION' ) ? TSM_VERSION : '1', true );
		wp_enqueue_script( $script_handle );
		$exit_url_js = wp_json_encode( esc_url( $exit_url ) );
		$title_js    = wp_json_encode( __( 'Return to WordPress dashboard and show the WP menu', 'tradeschool-manager' ) );
		$label_js    = wp_json_encode( __( 'Exit to WordPress', 'tradeschool-manager' ) );
		wp_add_inline_script(
			$script_handle,
			"(function(){\n"
			. "\tvar host = document.getElementById('wpbody-content');\n"
			. "\tif (!host) { return; }\n"
			. "\tvar bar = document.createElement('div');\n"
			. "\tbar.className = 'tsm-focus-exitbar';\n"
			. "\tvar brand = document.createElement('span');\n"
			. "\tbrand.className = 'tsm-focus-brand';\n"
			. "\tvar brandIcon = document.createElement('span');\n"
			. "\tbrandIcon.className = 'dashicons dashicons-welcome-learn-more';\n"
			. "\tbrand.appendChild(brandIcon);\n"
			. "\tbrand.appendChild(document.createTextNode('TradeSchool Manager  -  Focus Mode'));\n"
			. "\tvar link = document.createElement('a');\n"
			. "\tlink.className = 'tsm-focus-exit';\n"
			. "\tlink.href = {$exit_url_js};\n"
			. "\tlink.title = {$title_js};\n"
			. "\tvar exitIcon = document.createElement('span');\n"
			. "\texitIcon.className = 'dashicons dashicons-exit';\n"
			. "\tlink.appendChild(exitIcon);\n"
			. "\tlink.appendChild(document.createTextNode({$label_js}));\n"
			. "\tbar.appendChild(brand);\n"
			. "\tbar.appendChild(link);\n"
			. "\thost.insertBefore(bar, host.firstChild);\n"
			. "})();\n"
		);
	}
}

TSMP_Focus_Mode::init();
