<?php
/**
 * Fundraiser Attributes Meta Box
 *
 * Replaces the individual Owner / Target / Type / Teams / End Date side meta
 * boxes with a single WordPress Publish-style panel. Each attribute row shows
 * the current value with an inline "Edit" link that expands an input in place
 * — saving happens via the normal "Update" post form submit.
 *
 * @package AmbassadorHub\Fundraisers\Admin
 */

namespace AmbassadorHub\Fundraisers\Admin;

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

use AmbassadorHub\Admin\DateTimeHelper;
use AmbassadorHub\Fundraisers\FundraisersHelpers;
use AmbassadorHub\Fundraisers\FundraisersModule;
use AmbassadorHub\Fundraisers\Admin\Settings\SettingsManager as FundraiserSettingsManager;

/**
 * Registers and renders the consolidated fundraiser attributes meta box.
 */
final class FundraiserAttributesMetaBox {

	/**
	 * Register hooks.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'add_meta_boxes', array( self::class, 'register' ) );
		add_action( 'admin_enqueue_scripts', array( self::class, 'enqueue_assets' ) );
	}

	/**
	 * Register the meta box.
	 *
	 * @return void
	 */
	public static function register(): void {
		add_meta_box(
			'ambh-fundraiser-attributes',
			__( 'Fundraiser', 'ambassadorhub' ),
			array( self::class, 'render' ),
			FundraisersModule::POST_TYPE,
			'side',
			'default'
		);

		remove_meta_box( 'pageparentdiv', FundraisersModule::POST_TYPE, 'side' );
	}

	/**
	 * Enqueue assets on the fundraiser edit screen.
	 *
	 * @param string $hook_suffix Current admin page hook.
	 * @return void
	 */
	public static function enqueue_assets( string $hook_suffix ): void {
		if ( ! in_array( $hook_suffix, array( 'post.php', 'post-new.php' ), true ) ) {
			return;
		}

		$screen = get_current_screen();
		if ( ! $screen || FundraisersModule::POST_TYPE !== $screen->post_type ) {
			return;
		}

		$base = plugins_url( 'Admin/assets/', dirname( __DIR__ ) . '/FundraisersModule.php' );

		wp_enqueue_style( 'ambh-fundraiser-admin', $base . 'admin.css', array(), '1.0' );
		wp_enqueue_script(
			'ambh-fundraiser-attributes',
			$base . 'js/fundraiser-attributes.js',
			array( 'ambh-currency-input' ),
			'1.0',
			true
		);

		FundraiserSettingsManager::enqueue_currency_input_assets();
		wp_enqueue_style( 'ambh-admin' );
	}

	// -------------------------------------------------------------------------
	// Rendering
	// -------------------------------------------------------------------------

	/**
	 * Render the meta box.
	 *
	 * @param \WP_Post $post Current post.
	 * @return void
	 */
	public static function render( \WP_Post $post ): void {
		// All nonces in one place — the save handler in MetaBoxes::save_fundraiser_meta() checks each.
		wp_nonce_field( 'fundraiser_meta_nonce', 'fundraiser_meta_nonce' );
		wp_nonce_field( 'fundraiser_is_team_nonce', 'fundraiser_is_team_nonce' );
		wp_nonce_field( 'fundraiser_teams_nonce', 'fundraiser_teams_nonce' );
		wp_nonce_field( 'fundraiser_dates_nonce', 'fundraiser_dates_nonce' );

		// Gather current values.
		$owner_id     = (int) $post->post_author;
		$target       = (float) get_post_meta( $post->ID, '_ambh_target_amount', true );
		$is_team      = get_post_meta( $post->ID, FundraisersModule::META_IS_TEAM, true ) === '1';
		$allow_nested = get_post_meta( $post->ID, FundraisersModule::META_ALLOW_NESTED, true ) === '1';
		$is_root      = ( 0 === (int) $post->post_parent );

		// Root context for conditional logic.
		$root_id           = FundraisersHelpers::get_root_fundraiser_id( $post->ID );
		$root_allows_teams = $root_id > 0 && FundraisersHelpers::root_allows_teams( $root_id );

		// End date shown for non-root fundraisers when root allows custom end dates.
		$show_end_date = ! $is_root
			&& $root_id > 0
			&& get_post_meta( $root_id, FundraisersModule::META_FUNDRAISER_END_DATE_ENABLED, true ) === '1';

		// Users list.
		$users = get_users(
			array(
				'orderby' => 'display_name',
				'order'   => 'ASC',
			)
		);

		$parent_id = (int) $post->post_parent;

		// Resolve display labels.
		$owner_name = '—';
		foreach ( $users as $u ) {
			if ( (int) $u->ID === $owner_id ) {
				$owner_name = $u->display_name;
				break;
			}
		}

		$parent_name = $parent_id > 0 ? get_the_title( $parent_id ) : '—';

		$currency       = FundraiserSettingsManager::get_currency_symbol();
		$target_display = $target > 0 ? FundraiserSettingsManager::format_currency( $target ) : '—';
		$type_display   = $is_team
			? __( 'Team', 'ambassadorhub' )
			: __( 'Individual', 'ambassadorhub' );
		$nested_display = $allow_nested
			? __( 'Allowed', 'ambassadorhub' )
			: __( 'Not allowed', 'ambassadorhub' );

		// End date.
		$end_gmt       = (string) get_post_meta( $post->ID, FundraisersModule::META_END_DATE, true );
		$end_display   = $end_gmt
			? date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $end_gmt ) )
			: '—';
		$end_input_val = $end_gmt ? DateTimeHelper::format_datetime_for_input( $end_gmt ) : '';
		$root_end_gmt  = $root_id > 0 ? (string) get_post_meta( $root_id, '_ambh_end_date', true ) : '';
		$end_max       = $root_end_gmt ? DateTimeHelper::format_datetime_for_input( $root_end_gmt ) : '';

		?>
		<div class="ambh-fundraiser-attrs">

			<?php
			// ---- Parent fundraiser ----
			self::row(
				'parent',
				'dashicons-admin-page',
				__( 'Parent', 'ambassadorhub' ),
				$parent_name,
				function () use ( $post, $parent_id ) {
					$dropdown = wp_dropdown_pages(
						array(
							// wp_dropdown_pages() only echoes when its own 'echo' arg is
							// truthy; that's explicitly set to 0 below, so it returns
							// markup instead — escaped via wp_kses_post() where it's
							// actually output.
							'post_type'         => FundraisersModule::POST_TYPE, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
							'exclude_tree'      => $post->ID, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
							'selected'          => $parent_id, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
							'name'              => 'post_parent',
							'class'             => 'ambh-attr-input',
							'show_option_none'  => esc_html__( '— No parent —', 'ambassadorhub' ),
							'option_none_value' => '0',
							'sort_column'       => 'post_title',
							'post_status'       => array( 'publish', 'draft', 'pending' ),
							'echo'              => 0,
						)
					);
					echo wp_kses_post( str_replace( '<select ', '<select style="width:100%;" ', $dropdown ) );
				},
				array( 'input_type' => 'select' )
			);

			// ---- Owner ----
			self::row(
				'owner',
				'dashicons-admin-users',
				__( 'Owner', 'ambassadorhub' ),
				$owner_name,
				function () use ( $users, $owner_id ) {
					echo '<select name="post_author_override" class="ambh-attr-input" style="width:100%;">';
					foreach ( $users as $u ) {
						printf(
							'<option value="%d"%s>%s (%s)</option>',
							(int) $u->ID,
							selected( $owner_id, $u->ID, false ),
							esc_html( $u->display_name ),
							esc_html( $u->user_email )
						);
					}
					echo '</select>';
				},
				array( 'input_type' => 'select' )
			);

			// ---- Target Amount ----
			self::row(
				'target',
				'dashicons-chart-line',
				__( 'Target', 'ambassadorhub' ),
				$target_display,
				function () use ( $target, $currency ) {
					echo '<input type="text" inputmode="decimal" name="target_amount" class="ambh-attr-input ambh-currency-input"'
						. ' value="' . esc_attr( FundraiserSettingsManager::format_amount_for_input( $target ) ) . '"'
						. ' style="width:100%;"'
						. ' data-currency="' . esc_attr( $currency ) . '">';
				},
				array(
					'input_type' => 'number',
					'currency'   => $currency,
				)
			);

			// ---- Fundraiser Type ----
			self::row(
				'type',
				'dashicons-groups',
				__( 'Type', 'ambassadorhub' ),
				$type_display,
				function () use ( $is_team ) {
					?>
					<label>
						<input type="checkbox" name="_ambh_is_team" class="ambh-attr-input" value="1" <?php checked( $is_team ); ?>>
						<?php esc_html_e( 'Team fundraiser', 'ambassadorhub' ); ?>
					</label>
					<?php
				},
				array(
					'input_type'      => 'checkbox',
					'checked_label'   => __( 'Team', 'ambassadorhub' ),
					'unchecked_label' => __( 'Individual', 'ambassadorhub' ),
				)
			);

			// ---- Sub-teams (shown when root allows teams; hidden until type is team) ----
		if ( $root_allows_teams ) {
			self::row(
				'nested',
				'dashicons-networking',
				__( 'Sub-teams', 'ambassadorhub' ),
				$nested_display,
				function () use ( $allow_nested ) {
					?>
						<label>
							<input type="checkbox" name="_ambh_allow_nested_team" class="ambh-attr-input" value="1" <?php checked( $allow_nested ); ?>>
						<?php esc_html_e( 'Allow sub-teams', 'ambassadorhub' ); ?>
						</label>
						<?php
				},
				array(
					'input_type'      => 'checkbox',
					'checked_label'   => __( 'Allowed', 'ambassadorhub' ),
					'unchecked_label' => __( 'Not allowed', 'ambassadorhub' ),
					'hidden'          => ! $is_team,
				)
			);
		}

			// ---- End Date (conditional) ----
		if ( $show_end_date ) {
			self::row(
				'end-date',
				'dashicons-calendar-alt',
				__( 'End date', 'ambassadorhub' ),
				$end_display,
				function () use ( $end_input_val, $end_max ) {
					echo '<input type="datetime-local" name="_ambh_end_date" class="ambh-attr-input"'
						. ' value="' . esc_attr( $end_input_val ) . '"'
						. ( $end_max ? ' max="' . esc_attr( $end_max ) . '"' : '' )
						. ' style="width:100%;">';
				},
				array( 'input_type' => 'datetime' )
			);
		}
		?>

		</div>
		<?php
	}

	/**
	 * Render a single Publish-style attribute row.
	 *
	 * @param string   $id              Unique slug used for the row's HTML id.
	 * @param string   $icon            Dashicons CSS class.
	 * @param string   $label           Row label.
	 * @param string   $display_value   Human-readable current value.
	 * @param callable $editor_callback Outputs the inline editing control(s).
	 * @param array    $options {
	 *     @type string $input_type      'select'|'number'|'checkbox'|'datetime'
	 *     @type string $checked_label   Label when checkbox is checked.
	 *     @type string $unchecked_label Label when checkbox is unchecked.
	 *     @type string $currency        Currency symbol for number inputs.
	 * }
	 * @return void
	 */
	private static function row(
		string $id,
		string $icon,
		string $label,
		string $display_value,
		callable $editor_callback,
		array $options = array()
	): void {
		$input_type       = $options['input_type'] ?? 'text';
		$checked_label    = $options['checked_label'] ?? '';
		$unchecked_label  = $options['unchecked_label'] ?? '';
		$currency         = $options['currency'] ?? '';
		$initially_hidden = ! empty( $options['hidden'] );
		?>
		<div class="ambh-attr-row"
			id="ambh-attr-<?php echo esc_attr( $id ); ?>"
			data-input-type="<?php echo esc_attr( $input_type ); ?>"
			<?php
			if ( $checked_label ) :
				?>
				data-checked-label="<?php echo esc_attr( $checked_label ); ?>"<?php endif; ?>
			<?php
			if ( $unchecked_label ) :
				?>
				data-unchecked-label="<?php echo esc_attr( $unchecked_label ); ?>"<?php endif; ?>
			<?php
			if ( $currency ) :
				?>
				data-currency="<?php echo esc_attr( $currency ); ?>"<?php endif; ?>
			<?php
			if ( $initially_hidden ) :
				?>
				hidden<?php endif; ?>
		>
			<div class="ambh-attr-display">
				<span class="dashicons <?php echo esc_attr( $icon ); ?> ambh-attr-icon"></span>
				<span class="ambh-attr-label-text"><?php echo esc_html( $label ); ?>:</span>
				<span class="ambh-attr-value"><?php echo esc_html( $display_value ); ?></span>
				<a href="#" class="ambh-attr-edit-link"><?php esc_html_e( 'Edit', 'ambassadorhub' ); ?></a>
			</div>
			<div class="ambh-attr-editor" hidden>
				<?php $editor_callback(); ?>
				<p class="ambh-attr-actions">
					<a href="#" class="button button-small ambh-attr-ok"><?php esc_html_e( 'OK', 'ambassadorhub' ); ?></a>
					<a href="#" class="ambh-attr-cancel"><?php esc_html_e( 'Cancel', 'ambassadorhub' ); ?></a>
				</p>
			</div>
		</div>
		<?php
	}
}
