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

namespace AmbassadorHub\Consent\Admin;

use AmbassadorHub\Admin\AdminPage;
use AmbassadorHub\Admin\InlineAssets;
use AmbassadorHub\Donors\DonorsModule;

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

final class Menu {

	/** @var Consent_Records_List_Table|null */
	private static ?Consent_Records_List_Table $list_table = null;

	public static function init(): void {
		add_filter(
			'set_screen_option_ambh_consent_per_page',
			static function ( $_status, $_option, $value ) {
				return (int) $value;
			},
			10,
			3
		);

		add_action( 'admin_enqueue_scripts', array( self::class, 'enqueue_assets' ) );
	}

	/**
	 * Enqueue the page-specific CSS and JS for the Consent Records admin page.
	 *
	 * Hooked to admin_enqueue_scripts (rather than a load-{hook} action, since
	 * this page's submenu registration doesn't live in this file), 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 enqueue_assets(): void {
		if ( ! AdminPage::is_page( 'ambassadorhub-consent-records' ) ) {
			return;
		}

		InlineAssets::style(
			'.wp-list-table .column-status       { width: 90px; }
				.wp-list-table .column-channel      { width: 100px; }
				.wp-list-table .column-date         { width: 160px; }
				.wp-list-table .column-source       { width: 120px; }
				.wp-list-table .column-consent_text { width: 220px; }
				.wrap .wp-list-table td,
				.wrap .wp-list-table th { overflow: visible; }
				.ambh-consent-text-icon {
					position: relative;
					display: inline-block;
					margin-left: 4px;
					vertical-align: middle;
					cursor: pointer;
					color: #2271b1;
				}
				.ambh-consent-text-icon .dashicons {
					font-size: 15px;
					width: 15px;
					height: 15px;
					line-height: 1;
				}
				.ambh-consent-text-tooltip { display: none !important; }
				#ambh-global-consent-tooltip { display: none; position: fixed; background: #1d2327; color: #fff; padding: 6px 10px; border-radius: 4px; font-size: 12px; line-height: 1.5; white-space: pre-wrap; max-width: 360px; z-index: 99999; pointer-events: none; box-shadow: 0 2px 8px rgba(0,0,0,.35); }
				#ambh-global-consent-tooltip::after { content: \'\'; position: absolute; top: 100%; left: 50%; transform: translateX(-50%); border: 5px solid transparent; border-top-color: #1d2327; }'
		);

		InlineAssets::script(
			'jQuery(document).ready(function($) {
					if ( ! document.getElementById( \'ambh-global-consent-tooltip\' ) ) {
						var tip = document.createElement( \'div\' );
						tip.id = \'ambh-global-consent-tooltip\';
						document.body.appendChild( tip );
					}
					var tip = document.getElementById( \'ambh-global-consent-tooltip\' );
					$( document ).on( \'mouseover\', \'.ambh-consent-text-icon\', function () {
						var text = $( this ).find( \'.ambh-consent-text-tooltip\' ).text();
						if ( ! text ) return;
						tip.textContent = text;
						tip.style.display = \'block\';
						var r  = this.getBoundingClientRect();
						var tw = tip.offsetWidth;
						var left = r.left + r.width / 2 - tw / 2;
						left = Math.max( 8, Math.min( left, window.innerWidth - tw - 8 ) );
						tip.style.left = left + \'px\';
						tip.style.top  = ( r.top - tip.offsetHeight - 8 ) + \'px\';
					} );
					$( document ).on( \'mouseout\', \'.ambh-consent-text-icon\', function () {
						tip.style.display = \'none\';
					} );
				});'
		);
	}

	/**
	 * Register the Screen Options panel and prepare the list table.
	 *
	 * @return void
	 */
	public static function setup_screen(): void {
		add_screen_option(
			'per_page',
			array(
				'label'   => __( 'Consent Records', 'ambassadorhub' ),
				'default' => 20,
				'option'  => 'ambh_consent_per_page',
			)
		);

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$subject_type = isset( $_GET['subject_type'] ) ? sanitize_text_field( wp_unslash( $_GET['subject_type'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$subject_id = isset( $_GET['subject_id'] ) ? absint( $_GET['subject_id'] ) : 0;

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$current_tab  = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'all';
		$allowed_tabs = array( 'all', 'granted', 'revoked' );
		if ( ! in_array( $current_tab, $allowed_tabs, true ) ) {
			$current_tab = 'all';
		}

		$base_url = add_query_arg( 'page', 'ambassadorhub-consent-records', admin_url( 'admin.php' ) );
		if ( $subject_type ) {
			$base_url = add_query_arg( 'subject_type', $subject_type, $base_url );
		}
		if ( $subject_id ) {
			$base_url = add_query_arg( 'subject_id', $subject_id, $base_url );
		}

		self::$list_table = new Consent_Records_List_Table( $subject_type, $subject_id, $current_tab, $base_url );
		self::$list_table->prepare_items();
	}

	/**
	 * Render the header.
	 *
	 * @return void
	 */
	public static function render_header(): void {
		if ( ! current_user_can( 'ambh_manage_hub' ) ) {
			return;
		}

		if ( ! AdminPage::is_page( 'ambassadorhub-consent-records' ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$subject_type = isset( $_GET['subject_type'] ) ? sanitize_text_field( wp_unslash( $_GET['subject_type'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$subject_id = isset( $_GET['subject_id'] ) ? absint( $_GET['subject_id'] ) : 0;

		$header_title    = esc_html__( 'Consent Records', 'ambassadorhub' );
		$header_subtitle = esc_html__( 'View all consent records collected across the platform.', 'ambassadorhub' );

		if ( $subject_type && $subject_id ) {
			$subject_name = self::get_subject_display_name( $subject_type, $subject_id );
			if ( $subject_name ) {
				$header_title = esc_html(
					sprintf(
						/* translators: %s: subject display name */
						__( 'Consent Records for %s', 'ambassadorhub' ),
						$subject_name
					)
				);
			}

			$back_url = self::get_subject_back_url( $subject_type );
			if ( $back_url ) {
				$back_label      = 'wp_user' === $subject_type
					? esc_html__( 'All Ambassadors', 'ambassadorhub' )
					: esc_html__( 'All Donors', 'ambassadorhub' );
				$header_subtitle = '<a href="' . esc_url( $back_url ) . '">&larr; ' . $back_label . '</a>';
			}
		}

		AdminPage::header(
			$header_title,
			$header_subtitle
		);
	}

	/**
	 * Resolve a display name for a consent subject.
	 *
	 * @param string $subject_type Subject type (e.g. 'wp_user', 'donor').
	 * @param int    $subject_id   Subject ID.
	 * @return string Display name, or empty string if not found.
	 */
	private static function get_subject_display_name( string $subject_type, int $subject_id ): string {
		if ( 'wp_user' === $subject_type ) {
			$user = get_userdata( $subject_id );
			return $user ? $user->display_name : '';
		}

		if ( 'donor' === $subject_type ) {
			$donor = DonorsModule::get( $subject_id );
			return ( $donor && $donor->name ) ? $donor->name : '';
		}

		return '';
	}

	/**
	 * Return the admin list page URL to link back to for a given subject type.
	 *
	 * @param string $subject_type Subject type.
	 * @return string URL, or empty string for unknown types.
	 */
	private static function get_subject_back_url( string $subject_type ): string {
		if ( 'wp_user' === $subject_type ) {
			return admin_url( 'admin.php?page=ambassadorhub-ambassadors' );
		}

		if ( 'donor' === $subject_type ) {
			return admin_url( 'admin.php?page=ambassadorhub-donors' );
		}

		return '';
	}


	public static function render(): void {
		if ( ! current_user_can( 'ambh_manage_hub' ) ) {
			wp_die( esc_html__( 'Insufficient permissions', 'ambassadorhub' ) );
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$subject_type = isset( $_GET['subject_type'] ) ? sanitize_text_field( wp_unslash( $_GET['subject_type'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$subject_id = isset( $_GET['subject_id'] ) ? absint( $_GET['subject_id'] ) : 0;

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$current_tab  = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'all';
		$allowed_tabs = array( 'all', 'granted', 'revoked' );
		if ( ! in_array( $current_tab, $allowed_tabs, true ) ) {
			$current_tab = 'all';
		}

		?>
		<div class="wrap">

			<h1 class="hidden"></h1> <!-- Prevent admin notices being moved to the hidden h2 position -->

			<?php self::$list_table->views(); ?>

			<form method="get">
				<?php wp_nonce_field( 'ambh_consent_records_filter', 'ambh_consent_records_nonce' ); ?>
				<input type="hidden" name="page" value="ambassadorhub-consent-records">
				<?php if ( $subject_type ) : ?>
					<input type="hidden" name="subject_type" value="<?php echo esc_attr( $subject_type ); ?>">
				<?php endif; ?>
				<?php if ( $subject_id ) : ?>
					<input type="hidden" name="subject_id" value="<?php echo esc_attr( $subject_id ); ?>">
				<?php endif; ?>
				<?php if ( 'all' !== $current_tab ) : ?>
					<input type="hidden" name="tab" value="<?php echo esc_attr( $current_tab ); ?>">
				<?php endif; ?>
				<?php self::$list_table->search_box( __( 'Search Records', 'ambassadorhub' ), 'consent-record' ); ?>
				<?php self::$list_table->display(); ?>
			</form>

		</div>
		<?php
	}
}
