<?php
/**
 * Fundraiser Admin Menu
 *
 * Registers the styled header, footer, and shared CSS on the fundraiser
 * post-type list and edit screens — matching the Ambassador Core design.
 *
 * @package AmbassadorHub\Admin
 */

namespace AmbassadorHub\Fundraisers\Admin;

use AmbassadorHub\Admin\AdminPage;
use AmbassadorHub\Admin\InlineAssets;
use AmbassadorHub\Fundraisers\FundraisersModule;

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

/**
 * Registers admin-UI hooks for the `fundraiser` post type and its sub-menus.
 */
final class Menu {

	/**
	 * Custom admin page IDs belonging to ambassador-fundraiser.
	 *
	 * WordPress generates hooknames as: {admin_page_hooks[parent]}_page_{slug}
	 * admin_page_hooks['ambassadorhub'] = sanitize_title('Fundraiser') = 'fundraiser'
	 *
	 * @var string[]
	 */
	private const CUSTOM_SCREEN_IDS = array();

	/**
	 * Initialize admin menu hooks.
	 *
	 * @return void
	 */
	public static function init(): void {

		add_action( 'ambh_admin_menu_registered', array( self::class, 'register_menu' ), 30 );

		add_action( 'admin_notices', array( self::class, 'render_header' ), 1 );
		add_action( 'admin_enqueue_scripts', array( self::class, 'inject_list_styles' ) );

		// Register detail/stats meta boxes.
		Stats::init();
	}

	/**
	 * Register the hidden fundraiser detail/stats sub-page.
	 *
	 * Called via ambh_admin_menu_registered so the parent menu slug already exists.
	 *
	 * @return void
	 */
	public static function register_menu(): void {

		add_submenu_page(
			'ambassadorhub',
			__( 'Fundraisers', 'ambassadorhub' ),
			__( 'Fundraisers', 'ambassadorhub' ),
			'ambh_manage_hub',
			'edit.php?post_type=ambh_fundraiser',
			null,
			20
		);

		$hook_suffix = add_submenu_page(
			'', // hidden — no visible menu item.
			__( 'Fundraiser Detail', 'ambassadorhub' ),
			__( 'Fundraiser Detail', 'ambassadorhub' ),
			'ambh_manage_hub',
			FundraisersModule::STATS_PAGE_SLUG,
			array( self::class, 'render_stats_page' )
		);

		if ( $hook_suffix ) {
			add_action( 'load-' . $hook_suffix, array( self::class, 'set_stats_page_title' ) );
			add_action( 'load-' . $hook_suffix, array( self::class, 'enqueue_stats_page_assets' ) );
		}
	}

	/**
	 * Enqueue the postboxes-toggle JS for the fundraiser detail/stats page.
	 *
	 * Hooked from load-{hook} (register_menu()), which fires early enough for
	 * wp_add_inline_script() to still be picked up by admin_print_footer_scripts.
	 *
	 * @return void
	 */
	public static function enqueue_stats_page_assets(): void {
		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}

		InlineAssets::script(
			"jQuery(function(\$){\n\t\t\t\t\tpostboxes.add_postbox_toggles(\"" . esc_js( $screen->id ) . "\");\n\t\t\t\t});"
		);
	}

	/**
	 * Set the global $title for the detail page before admin-header.php renders.
	 *
	 * @return void
	 */
	public static function set_stats_page_title(): void {
		global $title;

		$post_id = isset( $_GET['post_id'] ) ? absint( $_GET['post_id'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( $post_id > 0 ) {
			$fundraiser_title = get_the_title( $post_id );
			if ( $fundraiser_title ) {
				$title = sprintf( // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- intentionally setting the page title global for admin-header.php, matching core's own pattern for custom admin pages.
					/* translators: %s: fundraiser title */
					__( 'Fundraiser "%s"', 'ambassadorhub' ),
					$fundraiser_title
				);
				return;
			}
		}

		$title = __( 'Fundraiser Detail', 'ambassadorhub' ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- intentionally setting the page title global for admin-header.php, matching core's own pattern for custom admin pages.
	}

	/**
	 * Render the detail/stats page for a specific fundraiser.
	 *
	 * @return void
	 */
	public static function render_stats_page(): void {
		$post_id = isset( $_GET['post_id'] ) ? absint( $_GET['post_id'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only GET parameter for detail page display.
		if ( ! $post_id ) {
			wp_die( 'Missing post_id.' );
		}

		$post = get_post( $post_id );
		if ( ! $post || FundraisersModule::POST_TYPE !== $post->post_type ) {
			wp_die( 'Invalid fundraiser.' );
		}

		if ( ! current_user_can( 'ambh_manage_hub' ) ) {
			wp_die( 'You do not have permission to view this.' );
		}

		$screen = get_current_screen();

		// Enable meta box UI behaviours (collapse / drag / order).
		wp_enqueue_script( 'postbox' );

		// Trigger registration hooks so add_meta_box() calls can target this screen.
		do_action( 'add_meta_boxes', $screen->id, $post );
		do_action( 'add_meta_boxes_' . $post->post_type, $post ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- invoking core WordPress hook pattern.

		$edit_link = admin_url( 'post.php?post=' . $post_id . '&action=edit' );
		?>
		<div class="wrap">
			<h1 class="wp-heading-inline"><?php echo esc_html( get_the_title( $post ) ); ?></h1>
			<a class="page-title-action" href="<?php echo esc_url( $edit_link ); ?>"><?php esc_html_e( 'Edit', 'ambassadorhub' ); ?></a>
			<hr class="wp-header-end">

			<?php // Form is only to satisfy core meta box JS (we are NOT saving). ?>
			<form method="post" action="">
				<?php
				wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
				wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
				?>
				<div id="poststuff">
					<div id="post-body" class="metabox-holder columns-1">
						<div id="postbox-container-2" class="postbox-container">
							<?php
							do_meta_boxes( $screen->id, 'normal', $post );
							do_meta_boxes( $screen->id, 'advanced', $post );
							?>
						</div>
					</div>
					<br class="clear" />
				</div>
			</form>
		</div>
		<?php
	}

	/**
	 * Return true when the current screen belongs to the fundraiser plugin.
	 *
	 * @return bool
	 */
	private static function is_fundraiser_screen(): bool {
		$screen = get_current_screen();
		if ( ! $screen ) {
			return false;
		}
		if ( FundraisersModule::POST_TYPE === $screen->post_type ) {
			return true;
		}
		return in_array( $screen->id, self::CUSTOM_SCREEN_IDS, true );
	}

	/**
	 * Enqueue inline CSS/JS to hide native WordPress headings and constrain layout.
	 *
	 * Hooked on 'admin_enqueue_scripts' (init()), which fires early enough for
	 * wp_add_inline_style()/wp_add_inline_script() to still be picked up by
	 * admin_print_styles/admin_print_footer_scripts.
	 *
	 * @return void
	 */
	public static function inject_list_styles(): void {
		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : '';

		// Fundraiser post-type list screen.
		if ( FundraisersModule::POST_TYPE === $screen->post_type && 'edit' === $screen->base ) {
			InlineAssets::style(
				'.column-root_fundraiser  { width: 220px; }
				.column-owner           { width: 180px; }
				.column-target          { width: 100px; }
				.column-donations_total { width: 100px; }
				.column-end_date        { width: 110px; }
				/* Team fundraiser icon — injected via JS after any leading dash characters to preserve nesting visualisation */
				.ambh-team-icon {
					font-family: dashicons;
					display: inline-block;
					font-style: normal;
					font-weight: normal;
					-webkit-font-smoothing: antialiased;
					color: #2271b1;
					margin-right: 5px;
					font-size: 16px;
					vertical-align: text-bottom;
				}
				.ambh-team-icon::before { content: "\f307"; }'
			);

			InlineAssets::script(
				"document.addEventListener( 'DOMContentLoaded', function () {
					document.querySelectorAll( '.ambh-is-team .row-title' ).forEach( function ( link ) {
						var icon = document.createElement( 'span' );
						icon.className = 'ambh-team-icon';
						// Insert after any leading em-dash characters so nesting indentation is preserved.
						// WordPress puts dashes + title in one text node (e.g. \"— — Title\"), so split it.
						var firstNode = link.firstChild;
						if ( firstNode && firstNode.nodeType === Node.TEXT_NODE && firstNode.textContent.indexOf( '—' ) === 0 ) {
							var match = firstNode.textContent.match( /^[—\\s]+/ );
							var dashText  = match ? match[0] : '';
							var titleText = firstNode.textContent.slice( dashText.length );
							firstNode.textContent = dashText;
							firstNode.after( icon );
							icon.after( document.createTextNode( titleText ) );
						} else {
							link.prepend( icon );
						}
					} );
				} );"
			);

			return;
		}
	}

	/**
	 * Render the styled dark header.
	 *
	 * @return void
	 */
	public static function render_header(): void {
		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : '';

		// Fundraiser stats page header.
		if ( FundraisersModule::STATS_PAGE_SLUG === $page ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$post_id    = isset( $_GET['post_id'] ) ? absint( $_GET['post_id'] ) : 0;
			$page_title = $post_id ? get_the_title( $post_id ) : __( 'Fundraiser Detail', 'ambassadorhub' );
			$edit_link  = $post_id ? admin_url( 'post.php?post=' . $post_id . '&action=edit' ) : '';

			// --- Build breadcrumb from post_parent chain ---
			$crumbs = array();

			if ( $post_id ) {
				$post = get_post( $post_id );

				// Ancestor fundraiser crumbs (top → bottom, excluding current).
				if ( $post ) {
					$ancestors = array_reverse( get_post_ancestors( $post ) ); // top-down order.
					foreach ( $ancestors as $ancestor_id ) {
						$ancestor_url      = add_query_arg(
							array(
								'page'    => FundraisersModule::STATS_PAGE_SLUG,
								'post_id' => $ancestor_id,
							),
							admin_url( 'admin.php' )
						);
						$ancestor_frontend = get_permalink( $ancestor_id );
						$ext_icon          = $ancestor_frontend ? ' <a href="' . esc_url( $ancestor_frontend ) . '" target="_blank" rel="noopener noreferrer" title="' . esc_attr__( 'View frontend', 'ambassadorhub' ) . '" style="color: inherit; opacity: 0.5; text-decoration: none; vertical-align: middle;"><span class="dashicons dashicons-external" style="font-size: 13px; width: 13px; height: 13px;"></span></a>' : '';
						$crumbs[]          = '<a href="' . esc_url( $ancestor_url ) . '" style="color: inherit; opacity: 0.75; text-decoration: underline;">' . esc_html( get_the_title( $ancestor_id ) ) . '</a>' . $ext_icon;
					}
				}

				// Current fundraiser (not linked) with external link icon.
				$current_frontend = get_permalink( $post_id );
				$ext_icon         = $current_frontend ? ' <a href="' . esc_url( $current_frontend ) . '" target="_blank" rel="noopener noreferrer" title="' . esc_attr__( 'View frontend', 'ambassadorhub' ) . '" style="color: inherit; opacity: 0.5; text-decoration: none; vertical-align: middle;"><span class="dashicons dashicons-external" style="font-size: 13px; width: 13px; height: 13px;"></span></a>' : '';
				$crumbs[]         = '<span style="opacity: 0.95;">' . esc_html( $page_title ) . '</span>' . $ext_icon;
			}

			$breadcrumb_html = implode( ' <span style="opacity: 0.5; margin: 0 4px;">›</span> ', $crumbs );
			AdminPage::header(
				esc_html( $page_title ),
				$breadcrumb_html ? wp_kses(
					$breadcrumb_html,
					array(
						'a'    => array(
							'href'   => array(),
							'style'  => array(),
							'target' => array(),
							'rel'    => array(),
							'title'  => array(),
						),
						'span' => array(
							'style' => array(),
							'class' => array(),
						),
					)
				) : '',
				$edit_link ? '<a href="' . esc_url( $edit_link ) . '" class="ambh-header__add-new">' . esc_html__( 'Edit Fundraiser', 'ambassadorhub' ) . '</a>' : ''
			);
			return;
		}

		// Fundraiser post-type list screen.
		if ( FundraisersModule::POST_TYPE === $screen->post_type && 'edit' === $screen->base ) {
			$add_new_url = admin_url( 'post-new.php?post_type=' . FundraisersModule::POST_TYPE );
			// translators: Subtitle shown in the Fundraisers admin header.
			AdminPage::header(
				esc_html__( 'Fundraisers', 'ambassadorhub' ),
				esc_html__( 'Create and manage peer-to-peer fundraiser pages.', 'ambassadorhub' ),
				'<a href="' . esc_url( $add_new_url ) . '" class="ambh-header__add-new">' . esc_html__( '+ Add New', 'ambassadorhub' ) . '</a>'
			);
			return;
		}
	}
}
