<?php
/**
 * Accounts Admin Menu
 *
 * Registers a submenu to list Ambassadors in wp-admin.
 *
 * @package AmbassadorHub\Accounts\Admin
 */

namespace AmbassadorHub\Accounts\Admin;

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

use AmbassadorHub\Admin\AdminPage;
use AmbassadorHub\Admin\InlineAssets;
use AmbassadorHub\Accounts\EmailVerification;
use function add_submenu_page;
use function esc_html__;
use function sanitize_text_field;
use function current_user_can;
use function wp_die;
use function admin_url;
use function check_admin_referer;
use function wp_safe_redirect;
use function add_query_arg;

/**
 * Admin submenu for Accounts module.
 */
final class Menu {
	/** @var Ambassadors_List_Table|null */
	private static ?Ambassadors_List_Table $list_table = null;

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

		// Register after core admin menu exists to ensure correct parent linkage.
		add_action( 'ambh_admin_menu_registered', array( self::class, 'register_submenu' ), 20 );

		// Add the header & footer
		add_action( 'admin_notices', array( self::class, 'render_header' ), 1 );

		// Handle admin actions (resend verification email).
		add_action( 'admin_init', array( self::class, 'handle_admin_actions' ) );

		add_filter(
			'set_screen_option_ambh_ambassadors_per_page',
			static function ( $status, $option, $value ) {
				return (int) $value;
			},
			10,
			3
		);
	}

	/**
	 * Register the Ambassadors submenu under the core top-level menu.
	 *
	 * @return void
	 */
	public static function register_submenu(): void {
		$hook = add_submenu_page(
			'ambassadorhub',
			esc_html__( 'Ambassadors', 'ambassadorhub' ),
			esc_html__( 'Ambassadors', 'ambassadorhub' ),
			'ambh_manage_hub',
			'ambassadorhub-ambassadors',
			array( self::class, 'render_ambassadors_page' ),
			10
		);
		add_action( 'load-' . $hook, array( self::class, 'setup_screen' ) );
	}

	/**
	 * 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'   => __( 'Ambassadors', 'ambassadorhub' ),
				'default' => 20,
				'option'  => 'ambh_ambassadors_per_page',
			)
		);

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$current_tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'all';
		$base_url    = add_query_arg( 'page', 'ambassadorhub-ambassadors', admin_url( 'admin.php' ) );

		self::$list_table = new Ambassadors_List_Table( $current_tab, $base_url );
		self::$list_table->prepare_items();

		self::enqueue_assets();
	}

	/**
	 * Enqueue the custom-fields expand/collapse CSS and JS for this page.
	 *
	 * Hooked from setup_screen() (load-{hook}), 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
	 */
	private static function enqueue_assets(): void {
		InlineAssets::style(
			'.column-registered  { width: 220px; }
            .column-username    { width: 280px; }
            .column-email       { width: 320px; }
            .column-fundraisers { width: 100px; }

            /* Custom-fields expand row */
            .ambh-cf-details-row { display: none; }
            .ambh-cf-details-row.is-open { display: table-row; }
            .ambh-cf-details-cell { padding: 0 !important; background: #f6f7f7 !important; border-top: none !important; }
            .ambh-cf-details-inner { padding: 12px 12px 12px 20px; border-left: 3px solid #2271b1; margin: 0; }
            .ambh-cf-details-table { border-collapse: collapse; }
            .ambh-cf-details-table th { text-align: left; font-weight: 600; color: #646970; font-size: 12px; padding: 3px 20px 3px 0; width: 180px; vertical-align: top; }
            .ambh-cf-details-table td { padding: 3px 0; font-size: 13px; color: #1d2327; }
            .ambh-cf-check   { color: #46b450; font-weight: 600; }
            .ambh-cf-uncheck { color: #aaa; }
            .ambh-cf-empty   { color: #aaa; font-style: italic; }
            .ambh-cf-toggle.is-open { color: #d63638; }'
		);

		InlineAssets::script(
			"jQuery( document ).on( 'click', '.ambh-cf-toggle', function ( e ) {
                e.preventDefault();
                var id   = jQuery( this ).data( 'id' );
                var row  = jQuery( '#ambh-cf-row-' + id );
                var open = row.hasClass( 'is-open' );
                row.toggleClass( 'is-open', ! open );
                jQuery( this ).toggleClass( 'is-open', ! open );
                jQuery( this ).text( open ? " . wp_json_encode( __( 'Custom Fields', 'ambassadorhub' ) ) . ' : ' . wp_json_encode( __( 'Hide Fields', 'ambassadorhub' ) ) . ' );
            } );'
		);
	}

	/**
	 * Handle admin actions (resend verification email).
	 *
	 * @return void
	 */
	public static function handle_admin_actions(): void {
		// Check if this is a resend verification request.
		if ( ! isset( $_GET['page'], $_GET['action'], $_GET['user_id'] ) || 'ambassadorhub-ambassadors' !== $_GET['page'] || 'resend_verification' !== $_GET['action'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return;
		}

		$user_id = absint( $_GET['user_id'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		// Verify nonce and permissions.
		check_admin_referer( 'resend_verification_' . $user_id );

		if ( ! current_user_can( 'ambh_manage_hub' ) ) {
			wp_die( esc_html__( 'Insufficient permissions', 'ambassadorhub' ) );
		}

		// Resend verification email.
		$result = EmailVerification::send_verification_email( $user_id );

		// Redirect back to the unverified tab with success/error message.
		$redirect_url = add_query_arg(
			array(
				'page'    => 'ambassadorhub-ambassadors',
				'tab'     => 'unverified',
				'message' => $result ? 'resent' : 'error',
			),
			admin_url( 'admin.php' )
		);

		wp_safe_redirect( $redirect_url );
		exit;
	}

	public static function render_header(): void {

		$screen = get_current_screen();
		if ( ! $screen || 'ambassadorhub_page_ambassadorhub-ambassadors' !== $screen->id ) {
			return;
		}

		AdminPage::header(
			esc_html__( 'Ambassadors', 'ambassadorhub' ),
			esc_html__( 'Manage your ambassador accounts, view registration status, and resend verification emails.', 'ambassadorhub' )
		);
	}

	/**
	 * Render the Ambassadors list page.
	 *
	 * @return void
	 */
	public static function render_ambassadors_page(): void {

		if ( ! current_user_can( 'ambh_manage_hub' ) ) {
			wp_die( esc_html__( 'Insufficient permissions', 'ambassadorhub' ) );
		}

		// Display admin notices (below header, above table).
		if ( isset( $_GET['message'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$message = sanitize_text_field( wp_unslash( $_GET['message'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			echo '<div style="margin: 0 0 16px;">';
			if ( 'resent' === $message ) {
				echo '<div class="notice notice-success inline"><p>' . esc_html__( 'Verification email has been resent.', 'ambassadorhub' ) . '</p></div>';
			} elseif ( 'error' === $message ) {
				echo '<div class="notice notice-error inline"><p>' . esc_html__( 'Failed to resend verification email.', 'ambassadorhub' ) . '</p></div>';
			}
			echo '</div>';
		}

		?>
		<div class="wrap">
			<form method="get">
				<?php wp_nonce_field( 'ambh_ambassadors_search', 'ambh_ambassadors_nonce' ); ?>
				<input type="hidden" name="page" value="ambassadorhub-ambassadors">
				<?php
				self::$list_table->views();
				self::$list_table->search_box( esc_html__( 'Search ambassadors', 'ambassadorhub' ), 'ambassador' );
				self::$list_table->display();
				?>
			</form>
		</div>
		<?php
	}
}
