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

namespace AmbassadorHub\Donors\Admin;

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

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

/**
 * Registers the Donors submenu and renders the admin page.
 */
final class Menu {

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

	/**
	 * Initialize the menu hooks.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'ambh_admin_menu_registered', array( self::class, 'register_menu' ), 40 );
		add_action( 'admin_notices', array( self::class, 'render_header' ), 1 );
		add_filter(
			'set_screen_option_ambh_donors_per_page',
			static function ( $status, $option, $value ) {
				return (int) $value;
			},
			10,
			3
		);
	}

	/**
	 * Register the Donors submenu item.
	 *
	 * @return void
	 */
	public static function register_menu(): void {
		$hook = add_submenu_page(
			'ambassadorhub',
			__( 'Donors', 'ambassadorhub' ),
			__( 'Donors', 'ambassadorhub' ),
			'ambh_manage_hub',
			'ambassadorhub-donors',
			array( self::class, 'render_admin_page' ),
			31
		);
		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'   => __( 'Donors', 'ambassadorhub' ),
				'default' => 20,
				'option'  => 'ambh_donors_per_page',
			)
		);

		$base_url = add_query_arg( 'page', 'ambassadorhub-donors', admin_url( 'admin.php' ) );

		self::$list_table = new Donors_List_Table( $base_url );
		self::$list_table->process_bulk_action();
		self::$list_table->prepare_items();

		self::enqueue_assets();
	}

	/**
	 * Enqueue the page-specific CSS and JS for the Donors admin 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(
			'.required { color: #d63638; }
				.wp-list-table .column-donations  { width: 100px; }
				.wp-list-table .column-registered { width: 160px; }'
		);

		InlineAssets::script(
			'jQuery(document).ready(function($) {
					$(\'#toggle-add-donor-form\').on(\'click\', function() {
						$(\'#add-donor-form\').slideToggle();
					});
					$(\'#cancel-add-donor\').on(\'click\', function() {
						$(\'#add-donor-form\').slideUp();
						$(\'#add-donor-form form\')[0].reset();
					});
				});'
		);
	}

	/**
	 * Render the page header.
	 *
	 * @return void
	 */
	public static function render_header(): void {

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

		AdminPage::header(
			esc_html__( 'Donors', 'ambassadorhub' ),
			esc_html__( 'Manage donor profiles. Each donor can be linked to multiple donations.', 'ambassadorhub' ),
			'<button type="button" class="ambh-header__add-new" id="toggle-add-donor-form">' . esc_html__( '+ Add New', 'ambassadorhub' ) . '</button>'
		);
	}

	/**
	 * Render the donors admin page.
	 *
	 * @return void
	 */
	public static function render_admin_page(): void {
		if ( ! current_user_can( 'ambh_manage_hub' ) ) {
			wp_die( esc_html__( 'Insufficient permissions', 'ambassadorhub' ) );
		}

		// Notice from add-form submission or post-anonymise redirect.
		$message      = '';
		$message_type = '';

		if ( isset( $_POST['add_donor_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['add_donor_nonce'] ) ), 'add_donor' ) ) {
			$donor_data = array(
				'first_name' => sanitize_text_field( wp_unslash( $_POST['first_name'] ?? '' ) ),
				'last_name'  => sanitize_text_field( wp_unslash( $_POST['last_name'] ?? '' ) ),
				'email'      => sanitize_email( wp_unslash( $_POST['email'] ?? '' ) ),
			);

			$result       = DonorsModule::create( $donor_data );
			$message      = $result
				? __( 'Donor added successfully!', 'ambassadorhub' )
				: __( 'Failed to add donor.', 'ambassadorhub' );
			$message_type = $result ? 'success' : 'error';
		}

		if ( '' === $message && isset( $_GET['anonymised'] ) && wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ?? '' ) ), 'bulk-donors' ) ) {
			$anonymised_count = absint( $_GET['anonymised'] );
			if ( $anonymised_count > 0 ) {
				/* translators: %d: number of anonymised donors */
				$message      = sprintf( _n( '%d donor anonymised.', '%d donors anonymised.', $anonymised_count, 'ambassadorhub' ), $anonymised_count );
				$message_type = 'success';
			}
		}

		?>

			<?php if ( $message ) : ?>
				<div class="notice notice-<?php echo esc_attr( $message_type ); ?> is-dismissible">
					<p><?php echo esc_html( $message ); ?></p>
				</div>
			<?php endif; ?>

			<div class="wrap">

				<h1 class="hidden"></h1> <!-- Prevent admin notice moved to the (hidden) h2 position -->

				<div id="add-donor-form" style="display: none; margin: 20px 0; padding: 20px; background: #fff; border: 1px solid #ccd0d4;">
					<h2><?php esc_html_e( 'Add New Donor', 'ambassadorhub' ); ?></h2>
					<form method="post">
						<?php wp_nonce_field( 'add_donor', 'add_donor_nonce' ); ?>
						<table class="form-table">
							<tr>
								<th scope="row">
									<label for="first_name"><?php esc_html_e( 'First Name', 'ambassadorhub' ); ?> <span class="required">*</span></label>
								</th>
								<td>
									<input type="text" name="first_name" id="first_name" class="regular-text" required>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="last_name"><?php esc_html_e( 'Last Name', 'ambassadorhub' ); ?> <span class="required">*</span></label>
								</th>
								<td>
									<input type="text" name="last_name" id="last_name" class="regular-text" required>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="email"><?php esc_html_e( 'Email', 'ambassadorhub' ); ?> <span class="required">*</span></label>
								</th>
								<td>
									<input type="email" name="email" id="email" class="regular-text" required>
								</td>
							</tr>
						</table>
						<p class="submit">
							<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php echo esc_attr__( 'Add Donor', 'ambassadorhub' ); ?>">
							<button type="button" class="button" id="cancel-add-donor"><?php esc_html_e( 'Cancel', 'ambassadorhub' ); ?></button>
						</p>
					</form>
				</div>

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

				<form method="get">
					<?php wp_nonce_field( 'ambh_donors_search', 'ambh_donors_nonce' ); ?>
					<input type="hidden" name="page" value="ambassadorhub-donors">
					<?php
					if ( ! empty( $_GET['tab'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), 'bulk-donors' ) ) :
						?>
						<input type="hidden" name="tab" value="<?php echo esc_attr( sanitize_key( wp_unslash( $_GET['tab'] ) ) ); ?>">
						<input type="hidden" name="_wpnonce" value="<?php echo esc_attr( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ) ); ?>">
					<?php endif; ?>
					<?php self::$list_table->search_box( esc_html__( 'Search Donors', 'ambassadorhub' ), 'ambassadorhub-donors' ); ?>
					<?php self::$list_table->display(); ?>
				</form>

			</div>
		<?php
	}
}
