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

namespace AmbassadorHub\Donations\Admin;

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

use AmbassadorHub\Admin\AdminPage;
use AmbassadorHub\Admin\InlineAssets;
use AmbassadorHub\Donations\DonationsModule;
use AmbassadorHub\Donors\DonorsModule;
use AmbassadorHub\Fundraisers\Admin\Settings\SettingsManager as FundraiserSettingsManager;

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

	/** @var Donations_List_Table|null */
	private static ?Donations_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' ), 50 );
		add_action( 'admin_notices', array( self::class, 'render_header' ), 1 );
		add_filter(
			'set_screen_option_ambh_donations_per_page',
			static function ( $status, $option, $value ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed
				return (int) $value;
			},
			10,
			3
		);
	}

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

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$filter_donor_id = isset( $_GET['donor_id'] ) ? absint( $_GET['donor_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', 'completed', 'pending', 'failed' );
		if ( ! in_array( $current_tab, $allowed_tabs, true ) ) {
			$current_tab = 'all';
		}

		$base_url = add_query_arg( 'page', 'ambassadorhub-donations', admin_url( 'admin.php' ) );
		if ( $filter_donor_id ) {
			$base_url = add_query_arg( 'donor_id', $filter_donor_id, $base_url );
		}

		self::$list_table = new Donations_List_Table( $filter_donor_id, $current_tab, $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 Donations 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(
			'.ambh-filter-chip { display: inline-flex; align-items: center; gap: 6px; margin: 0 8px 0 0; padding: 3px 10px; background: #f0f6fc; border: 1px solid #72aee6; border-radius: 12px; font-size: 13px; vertical-align: middle; }
				.ambh-filter-chip__clear { color: #646970; text-decoration: none; font-size: 11px; line-height: 1; }
				.ambh-filter-chip__clear:hover { color: #d63638; }
				.required { color: #d63638; }
				.wp-list-table .column-campaign { width: 200px; }
				.wp-list-table .column-amount   { width: 120px; text-align: right; }
				.wp-list-table .column-status   { width: 120px; }
				.wp-list-table .column-date     { width: 160px; }
				.wrap .wp-list-table td,
				.wrap .wp-list-table th { overflow: visible; }
				.ambh-donation-comment-icon {
					position: relative;
					display: inline-block;
					margin-left: 5px;
					vertical-align: middle;
					cursor: pointer;
					color: #2271b1;
				}
				.ambh-donation-comment-icon .dashicons {
					font-size: 16px;
					width: 16px;
					height: 16px;
					line-height: 1;
				}
				.ambh-donation-comment-tooltip { display: none !important; }
				#ambh-global-comment-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-comment-tooltip::after { content: \'\'; position: absolute; top: 100%; left: 50%; transform: translateX(-50%); border: 5px solid transparent; border-top-color: #1d2327; }

				/* 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).ready(function($) {
					// Body-level tooltip for donation comments (escapes table overflow clipping).
					if ( ! document.getElementById( \'ambh-global-comment-tooltip\' ) ) {
						var tip = document.createElement( \'div\' );
						tip.id = \'ambh-global-comment-tooltip\';
						document.body.appendChild( tip );
					}
					var tip = document.getElementById( \'ambh-global-comment-tooltip\' );
					$( document ).on( \'mouseover\', \'.ambh-donation-comment-icon\', function () {
						var text = $( this ).find( \'.ambh-donation-comment-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-donation-comment-icon\', function () {
						tip.style.display = \'none\';
					} );

					$(\'#toggle-add-donation-form\').on(\'click\', function() {
						$(\'#add-donation-form\').slideToggle();
					});
					$(\'#cancel-add-donation\').on(\'click\', function() {
						$(\'#add-donation-form\').slideUp();
						$(\'#add-donation-form form\')[0].reset();
					});
					// Show/hide new donor fields based on donor selector.
					$(\'#donor_id_select\').on(\'change\', function() {
						if ( $(this).val() === \'0\' ) {
							$(\'#new-donor-fields\').show();
						} else {
							$(\'#new-donor-fields\').hide();
						}
					}).trigger(\'change\');

					// When campaign filter changes, reset fundraiser filter and submit.
					$(\'#filter-by-campaign\').on(\'change\', function() {
						$(\'#filter-by-fundraiser\').val(\'0\');
					});

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

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

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

		$filter_donor_id = isset( $_GET['donor_id'] ) ? absint( $_GET['donor_id'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only filter for admin list display; no state-change performed.
		$filter_donor    = $filter_donor_id ? DonorsModule::get( $filter_donor_id ) : null;

		$header_title = ( $filter_donor && $filter_donor->name )
			? esc_html( sprintf( /* translators: %s: donor name */ __( 'Donations by %s', 'ambassadorhub' ), $filter_donor->name ) )
			: esc_html__( 'Donations', 'ambassadorhub' );

		$header_subtitle = $filter_donor
			? '<a href="' . esc_url( admin_url( 'admin.php?page=ambassadorhub-donors' ) ) . '">&larr; ' . esc_html__( 'All Donors', 'ambassadorhub' ) . '</a>'
			: esc_html__( 'Overview of all donations made through fundraiser pages.', 'ambassadorhub' );

		AdminPage::header(
			$header_title,
			$header_subtitle,
			'<button type="button" class="ambh-header__add-new" id="toggle-add-donation-form">' . esc_html__( '+ Add New', 'ambassadorhub' ) . '</button>'
		);
	}

	/**
	 * Render the donations 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' ) );
		}

		// Optional donor_id filter (from Donors admin page link — no nonce needed for read-only filters).
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$filter_donor_id = isset( $_GET['donor_id'] ) ? absint( $_GET['donor_id'] ) : 0;

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

		// Handle form submission.
		$message      = '';
		$message_type = '';
		if ( isset( $_POST['add_donation_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['add_donation_nonce'] ) ), 'add_donation' ) ) {
			$donor_id      = intval( wp_unslash( $_POST['donor_id'] ?? 0 ) );
			$donation_data = array(
				'fundraiser_id'    => intval( wp_unslash( $_POST['fundraiser_id'] ?? 0 ) ),
				'donor_id'         => $donor_id ? $donor_id : null,
				'donor_first_name' => sanitize_text_field( wp_unslash( $_POST['donor_first_name'] ?? '' ) ),
				'donor_last_name'  => sanitize_text_field( wp_unslash( $_POST['donor_last_name'] ?? '' ) ),
				'donor_email'      => sanitize_email( wp_unslash( $_POST['donor_email'] ?? '' ) ),
				'amount'           => FundraiserSettingsManager::normalize_amount( sanitize_text_field( wp_unslash( $_POST['amount'] ?? '' ) ) ),
				'currency'         => sanitize_text_field( wp_unslash( $_POST['currency'] ?? 'EUR' ) ),
				'status'           => sanitize_text_field( wp_unslash( $_POST['status'] ?? 'completed' ) ),
				'transaction_id'   => sanitize_text_field( wp_unslash( $_POST['transaction_id'] ?? '' ) ),
				'notes'            => sanitize_textarea_field( wp_unslash( $_POST['notes'] ?? '' ) ),
				'message'          => sanitize_textarea_field( wp_unslash( $_POST['message'] ?? '' ) ),
			);

			$result = DonationsModule::create( $donation_data );

			if ( $result ) {
				$message      = __( 'Donation added successfully!', 'ambassadorhub' );
				$message_type = 'success';
			} else {
				$message      = __( 'Failed to add donation.', 'ambassadorhub' );
				$message_type = 'error';
			}
		}

		?>

		<?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> <!-- Make sure admin notices are not moved to the hidden h2 -->

			<div id="add-donation-form" style="display: none; margin: 20px 0; padding: 20px; background: #fff; border: 1px solid #ccd0d4;">
				<h2><?php esc_html_e( 'Add New Donation', 'ambassadorhub' ); ?></h2>
				<form method="post">
					<?php wp_nonce_field( 'add_donation', 'add_donation_nonce' ); ?>
					<table class="form-table">
						<tr>
							<th scope="row"><label for="fundraiser_id"><?php esc_html_e( 'Fundraiser', 'ambassadorhub' ); ?></label></th>
							<td>
								<?php
								$fundraisers = get_posts(
									array(
										'post_type'      => 'fundraiser',
										'posts_per_page' => -1,
										'orderby'        => 'title',
										'order'          => 'ASC',
										'post_status'    => 'publish',
									)
								);
								?>
								<select name="fundraiser_id" id="fundraiser_id" class="regular-text">
									<option value="0"><?php esc_html_e( '-- Select Fundraiser --', 'ambassadorhub' ); ?></option>
									<?php foreach ( $fundraisers as $fundraiser ) : ?>
										<option value="<?php echo esc_attr( $fundraiser->ID ); ?>"><?php echo esc_html( $fundraiser->post_title ); ?></option>
									<?php endforeach; ?>
								</select>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="donor_id"><?php esc_html_e( 'Donor', 'ambassadorhub' ); ?></label></th>
							<td>
								<?php
								$all_donors = DonorsModule::get_all(
									array(
										'limit'   => 500,
										'orderby' => 'name',
										'order'   => 'ASC',
									)
								);
								?>
								<select name="donor_id" id="donor_id_select" class="regular-text">
									<option value="0"><?php esc_html_e( '-- New donor (fill in below) --', 'ambassadorhub' ); ?></option>
									<?php foreach ( $all_donors as $d ) : ?>
										<option value="<?php echo esc_attr( $d->id ); ?>" <?php selected( $filter_donor_id, $d->id ); ?>>
											<?php echo esc_html( $d->name . ' (' . $d->email . ')' ); ?>
										</option>
									<?php endforeach; ?>
								</select>
								<p class="description"><?php esc_html_e( 'Select an existing donor, or choose "New donor" to create one inline.', 'ambassadorhub' ); ?></p>
							</td>
						</tr>
					</table>

					<div id="new-donor-fields">
						<h3 style="margin: 10px 0 5px;"><?php esc_html_e( 'New Donor Details', 'ambassadorhub' ); ?></h3>
						<table class="form-table">
							<tr>
								<th scope="row"><label for="donor_first_name"><?php esc_html_e( 'First Name', 'ambassadorhub' ); ?></label></th>
								<td><input type="text" name="donor_first_name" id="donor_first_name" class="regular-text"></td>
							</tr>
							<tr>
								<th scope="row"><label for="donor_last_name"><?php esc_html_e( 'Last Name', 'ambassadorhub' ); ?></label></th>
								<td><input type="text" name="donor_last_name" id="donor_last_name" class="regular-text"></td>
							</tr>
							<tr>
								<th scope="row"><label for="donor_email"><?php esc_html_e( 'Email', 'ambassadorhub' ); ?></label></th>
								<td><input type="email" name="donor_email" id="donor_email" class="regular-text"></td>
							</tr>
						</table>
					</div>

					<table class="form-table">
						<tr>
							<th scope="row"><label for="amount"><?php esc_html_e( 'Amount', 'ambassadorhub' ); ?> <span class="required">*</span></label></th>
							<td>
							<input type="text" inputmode="decimal" name="amount" id="amount" class="regular-text ambh-currency-input" required>
							<?php FundraiserSettingsManager::enqueue_currency_input_assets(); ?>
						</td>
						</tr>
						<tr>
							<th scope="row"><label for="currency"><?php esc_html_e( 'Currency', 'ambassadorhub' ); ?></label></th>
							<td>
								<select name="currency" id="currency" class="regular-text">
									<option value="EUR">EUR</option>
									<option value="USD">USD</option>
									<option value="GBP">GBP</option>
								</select>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="status"><?php esc_html_e( 'Status', 'ambassadorhub' ); ?></label></th>
							<td>
								<select name="status" id="status" class="regular-text">
									<option value="completed"><?php esc_html_e( 'Completed', 'ambassadorhub' ); ?></option>
									<option value="pending"><?php esc_html_e( 'Pending', 'ambassadorhub' ); ?></option>
									<option value="failed"><?php esc_html_e( 'Failed', 'ambassadorhub' ); ?></option>
								</select>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="transaction_id"><?php esc_html_e( 'Transaction ID', 'ambassadorhub' ); ?></label></th>
							<td><input type="text" name="transaction_id" id="transaction_id" class="regular-text"></td>
						</tr>
						<tr>
							<th scope="row"><label for="notes"><?php esc_html_e( 'Notes (Internal)', 'ambassadorhub' ); ?></label></th>
							<td>
								<textarea name="notes" id="notes" class="large-text" rows="3"></textarea>
								<p class="description"><?php esc_html_e( 'Internal notes, not visible to donors.', 'ambassadorhub' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="message"><?php esc_html_e( 'Message (Public)', 'ambassadorhub' ); ?></label></th>
							<td>
								<textarea name="message" id="message" class="large-text" rows="3"></textarea>
								<p class="description"><?php esc_html_e( 'Public message visible to donors and on the website.', 'ambassadorhub' ); ?></p>
							</td>
						</tr>
					</table>

					<p class="submit">
						<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php echo esc_attr__( 'Add Donation', 'ambassadorhub' ); ?>">
						<button type="button" class="button" id="cancel-add-donation"><?php esc_html_e( 'Cancel', 'ambassadorhub' ); ?></button>
					</p>
				</form>
			</div>

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

			<form method="get">
				<?php wp_nonce_field( 'ambh_donations_filter', 'ambh_donations_nonce' ); ?>
				<input type="hidden" name="page" value="ambassadorhub-donations">
				<?php if ( $filter_donor_id ) : ?>
					<input type="hidden" name="donor_id" value="<?php echo esc_attr( $filter_donor_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 Donations', 'ambassadorhub' ), 'donation' ); ?>
			<?php self::$list_table->display(); ?>
			</form>

		</div>

		<?php
	}
}
