<?php
/**
 * Automations Admin Menu
 *
 * @package AmbassadorHub\Automations\Admin
 */

namespace AmbassadorHub\Campaigns\Admin;

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

use AmbassadorHub\Admin\AdminPage;
use AmbassadorHub\Admin\Charts\ChartRenderer;
use AmbassadorHub\Admin\InlineAssets;
use AmbassadorHub\Campaigns\CampaignsModule;

/**
 * Registers the Automations admin submenu and page.
 */
final class Menu {
	/**
	 * Initialize admin menu hooks for Campaigns.
	 *
	 * @return void
	 */
	public static function init(): void {

		// Hook after the core admin menu is registered so parent slug exists.
		add_action( 'ambh_admin_menu_registered', array( self::class, 'register_menu' ), 10 );

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

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

	/**
	 * Register the Automations submenu page.
	 *
	 * @return void
	 */
	public static function register_menu(): void {
		add_submenu_page(
			'ambassadorhub',
			__( 'Campaigns', 'ambassadorhub' ),
			__( 'Campaigns', 'ambassadorhub' ),
			'ambh_manage_hub',
			'edit.php?post_type=ambh_campaign',
			null,
			20
		);

		$hook_suffix = add_submenu_page(
			'', // hidden — no visible menu item.
			__( 'Campaign Detail', 'ambassadorhub' ),
			__( 'Campaign Detail', 'ambassadorhub' ),
			'ambh_manage_hub',
			CampaignsModule::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_assets' ) );
		}
	}

	/**
	 * Enqueue the postbox-toggle JS for the campaign detail/stats page.
	 *
	 * Hooked from load-{hook_suffix}, 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_assets(): void {
		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}

		InlineAssets::script(
			'jQuery(function($){
				postboxes.add_postbox_toggles("' . esc_js( $screen->id ) . '");
			});'
		);
	}

	/**
	 * 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 ) {
			$campaign_title = get_the_title( $post_id );
			if ( $campaign_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: campaign title */
					__( 'Campaign "%s"', 'ambassadorhub' ),
					$campaign_title
				);
				return;
			}
		}

		$title = __( 'Campaign 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 campaign.
	 *
	 * @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 || CampaignsModule::POST_TYPE !== $post->post_type ) {
			wp_die( 'Invalid campaign.' );
		}

		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
	}

	/**
	 * Render the styled header block on the campaigns list screen and stats page.
	 *
	 * @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'] ) : '';

		// Campaign stats page header.
		if ( CampaignsModule::STATS_PAGE_SLUG === $page ) {

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$post_id    = isset( $_GET['post_id'] ) ? absint( $_GET['post_id'] ) : 0;
			$back_url   = admin_url( 'edit.php?post_type=' . CampaignsModule::POST_TYPE );
			$page_title = $post_id ? get_the_title( $post_id ) : __( 'Campaign Detail', 'ambassadorhub' );
			$edit_link  = $post_id ? admin_url( 'post.php?post=' . $post_id . '&action=edit' ) : '';

			AdminPage::header(
				esc_html( $page_title ),
				'<a href="' . esc_url( $back_url ) . '" style="color: inherit; text-decoration: underline; opacity: 0.8;">' . esc_html__( '← All Campaigns', 'ambassadorhub' ) . '</a>',
				$edit_link ? '<a href="' . esc_url( $edit_link ) . '" class="ambh-header__add-new">' . esc_html__( 'Edit Fundraiser', 'ambassadorhub' ) . '</a>' : ''
			);

			return;
		}

		// Campaigns list screen.
		if ( CampaignsModule::POST_TYPE !== $screen->post_type || 'edit' !== $screen->base ) {
			return;
		}

		$add_new_url = admin_url( 'post-new.php?post_type=' . CampaignsModule::POST_TYPE );

		AdminPage::header(
			esc_html__( 'Campaigns', 'ambassadorhub' ),
			esc_html__( 'Create and manage your ambassador campaigns.', 'ambassadorhub' ),
			'<a href="' . esc_url( $add_new_url ) . '" class="ambh-header__add-new">' . esc_html__( '+ Add New', 'ambassadorhub' ) . '</a>'
		);
	}
}
