<?php
/**
 * Root Fundraiser Meta Boxes
 *
 * Meta boxes for depth-1 (root) fundraisers: end date, financial goal,
 * teams toggle, and fundraiser end-date toggle. Rendered only when the
 * fundraiser has no parent (post_parent === 0).
 *
 * @package AmbassadorHub\Fundraisers\Admin
 */

namespace AmbassadorHub\Fundraisers\Admin;

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

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

/**
 * Registers and renders meta boxes that are only relevant for root fundraisers.
 */
final class RootFundraiserMetaBoxes {

	private const NONCE_ACTION = 'ambh_root_fundraiser_meta';
	private const NONCE_FIELD  = '_ambh_root_fundraiser_nonce';

	public static function init(): void {
		add_action( 'add_meta_boxes_' . FundraisersModule::POST_TYPE, array( self::class, 'register' ) );
		add_action( 'save_post_' . FundraisersModule::POST_TYPE, array( self::class, 'save' ), 20 );
	}

	/**
	 * Register meta boxes — only for root fundraisers (post_parent === 0).
	 *
	 * @param \WP_Post $post Current post.
	 */
	public static function register( \WP_Post $post ): void {
		if ( 0 !== (int) $post->post_parent ) {
			return;
		}

		add_meta_box(
			'ambh_root_dates',
			__( 'Campaign Dates', 'ambassadorhub' ),
			array( self::class, 'render_dates' ),
			FundraisersModule::POST_TYPE,
			'side',
			'default'
		);

		add_meta_box(
			'ambh_root_financial_goal',
			__( 'Financial Goal', 'ambassadorhub' ),
			array( self::class, 'render_financial_goal' ),
			FundraisersModule::POST_TYPE,
			'side',
			'default'
		);

		add_meta_box(
			'ambh_root_nesting',
			__( 'Nesting Settings', 'ambassadorhub' ),
			array( self::class, 'render_nesting' ),
			FundraisersModule::POST_TYPE,
			'side',
			'default'
		);
	}

	// -------------------------------------------------------------------------
	// Render
	// -------------------------------------------------------------------------

	public static function render_dates( \WP_Post $post ): void {
		wp_nonce_field( self::NONCE_ACTION, self::NONCE_FIELD );

		$end_date_raw = (string) get_post_meta( $post->ID, FundraisersModule::META_END_DATE, true );
		$end_date_val = $end_date_raw ? DateTimeHelper::format_datetime_for_input( $end_date_raw ) : '';
		?>
		<p>
			<label for="ambh_root_end_date"><strong><?php esc_html_e( 'End Date', 'ambassadorhub' ); ?></strong></label><br>
			<input
				type="datetime-local"
				id="ambh_root_end_date"
				name="ambh_root_end_date"
				value="<?php echo esc_attr( $end_date_val ); ?>"
				style="width:100%"
			>
			<span class="description"><?php esc_html_e( 'Leave empty for no end date. All child fundraisers are capped to this date.', 'ambassadorhub' ); ?></span>
		</p>
		<?php
	}

	public static function render_financial_goal( \WP_Post $post ): void {
		$goal = (float) get_post_meta( $post->ID, FundraisersModule::META_FINANCIAL_GOAL, true );
		?>
		<p>
			<label for="ambh_root_financial_goal"><strong><?php esc_html_e( 'Overall Goal', 'ambassadorhub' ); ?></strong></label><br>
			<input
				type="text"
				inputmode="decimal"
				id="ambh_root_financial_goal"
				name="ambh_root_financial_goal"
				value="<?php echo esc_attr( FundraiserSettingsManager::format_amount_for_input( $goal ) ); ?>"
				class="ambh-currency-input"
				style="width:100%"
			>
			<?php FundraiserSettingsManager::enqueue_currency_input_assets(); ?>
			<span class="description"><?php esc_html_e( 'Total fundraising goal across all ambassadors. 0 = no goal.', 'ambassadorhub' ); ?></span>
		</p>
		<?php
	}

	public static function render_nesting( \WP_Post $post ): void {
		$teams_enabled         = get_post_meta( $post->ID, FundraisersModule::META_TEAMS_ENABLED, true ) === '1';
		$end_date_enabled      = get_post_meta( $post->ID, FundraisersModule::META_FUNDRAISER_END_DATE_ENABLED, true ) === '1';
		$accepts_donations_val = get_post_meta( $post->ID, FundraisersModule::META_ACCEPTS_DONATIONS, true );
		$accepts_donations     = '' === $accepts_donations_val || '1' === $accepts_donations_val;
		?>
		<p>
			<label>
				<input
					type="checkbox"
					name="ambh_root_accepts_donations"
					value="1"
					<?php checked( $accepts_donations ); ?>
				>
				<?php esc_html_e( 'Accept donations', 'ambassadorhub' ); ?>
			</label><br>
			<span class="description"><?php esc_html_e( 'When unchecked, no donation form is shown for this fundraiser. Use when the fundraiser acts as a category.', 'ambassadorhub' ); ?></span>
		</p>
		<p>
			<label>
				<input
					type="checkbox"
					name="ambh_root_teams_enabled"
					value="1"
					<?php checked( $teams_enabled ); ?>
				>
				<?php esc_html_e( 'Enable teams', 'ambassadorhub' ); ?>
			</label><br>
			<span class="description"><?php esc_html_e( 'Allow ambassadors to create team fundraisers under this root.', 'ambassadorhub' ); ?></span>
		</p>
		<p>
			<label>
				<input
					type="checkbox"
					name="ambh_root_fundraiser_end_date_enabled"
					value="1"
					<?php checked( $end_date_enabled ); ?>
				>
				<?php esc_html_e( 'Allow ambassadors to set an end date', 'ambassadorhub' ); ?>
			</label><br>
			<span class="description"><?php esc_html_e( 'When enabled, ambassadors can optionally set an end date on their own fundraisers (capped by the root end date above).', 'ambassadorhub' ); ?></span>
		</p>
		<?php
	}

	// -------------------------------------------------------------------------
	// Save
	// -------------------------------------------------------------------------

	public static function save( int $post_id ): void {
		if ( ! isset( $_POST[ self::NONCE_FIELD ] ) ) {
			return;
		}
		if ( ! wp_verify_nonce( sanitize_key( $_POST[ self::NONCE_FIELD ] ), self::NONCE_ACTION ) ) {
			return;
		}
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		$post = get_post( $post_id );
		if ( ! $post || 0 !== (int) $post->post_parent ) {
			return;
		}

		// End date.
		if ( isset( $_POST['ambh_root_end_date'] ) && '' !== $_POST['ambh_root_end_date'] ) {
			$end_date_gmt = DateTimeHelper::convert_datetime_to_gmt( sanitize_text_field( wp_unslash( $_POST['ambh_root_end_date'] ) ) );
			update_post_meta( $post_id, FundraisersModule::META_END_DATE, $end_date_gmt );
		} else {
			delete_post_meta( $post_id, FundraisersModule::META_END_DATE );
		}

		// Financial goal.
		if ( isset( $_POST['ambh_root_financial_goal'] ) ) {
			$goal = max( 0.0, FundraiserSettingsManager::normalize_amount( sanitize_text_field( wp_unslash( $_POST['ambh_root_financial_goal'] ) ) ) );
			update_post_meta( $post_id, FundraisersModule::META_FINANCIAL_GOAL, $goal );
		}

		// Accepts donations.
		update_post_meta(
			$post_id,
			FundraisersModule::META_ACCEPTS_DONATIONS,
			isset( $_POST['ambh_root_accepts_donations'] ) ? '1' : '0'
		);

		// Teams enabled.
		update_post_meta(
			$post_id,
			FundraisersModule::META_TEAMS_ENABLED,
			isset( $_POST['ambh_root_teams_enabled'] ) ? '1' : '0'
		);

		// Fundraiser end date enabled.
		update_post_meta(
			$post_id,
			FundraisersModule::META_FUNDRAISER_END_DATE_ENABLED,
			isset( $_POST['ambh_root_fundraiser_end_date_enabled'] ) ? '1' : '0'
		);
	}
}
