<?php
/**
 * Campaign Meta Boxes
 *
 * @package AmbassadorHub\Campaigns\Admin
 */

namespace AmbassadorHub\Campaigns\Admin;

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

use AmbassadorHub\Admin\DateTimeHelper;
use AmbassadorHub\Campaigns\CampaignsModule;
use AmbassadorHub\Fundraisers\Admin\Settings\SettingsManager;

/**
 * Manages meta boxes on the campaign edit screen.
 */
final class MetaBoxes {

	/**
	 * Initialize meta box hooks.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'save_post_' . CampaignsModule::POST_TYPE, array( self::class, 'save_campaign_dates_meta_box' ) );
		add_action( 'save_post_' . CampaignsModule::POST_TYPE, array( self::class, 'save_campaign_financial_goal_meta_box' ) );
	}

	/**
	 * Render the Campaign Dates meta box.
	 *
	 * @param \WP_Post $post Current post.
	 * @return void
	 */
	public static function render_campaign_dates_meta_box( \WP_Post $post ): void {
		// Start date uses the post's publish date (stored as GMT).
		$start_date = $post->post_date_gmt;
		$end_date   = get_post_meta( $post->ID, '_ambh_end_date', true );

		$start_datetime = $start_date ? DateTimeHelper::format_datetime_for_input( $start_date ) : '';
		$end_datetime   = $end_date ? DateTimeHelper::format_datetime_for_input( $end_date ) : '';

		wp_nonce_field( 'campaign_dates_nonce', 'campaign_dates_nonce' );
		?>
		<div class="campaign-dates" style="display: flex; flex-direction: column; gap: 15px;">
			<p style="margin: 0;">
				<label for="campaign_start_date" style="display: block; margin-bottom: 5px; font-weight: 600;">
					<?php echo esc_html__( 'Start Date & Time', 'ambassadorhub' ); ?>
				</label>
				<input
					type="datetime-local"
					id="campaign_start_date"
					name="campaign_start_date"
					value="<?php echo esc_attr( $start_datetime ); ?>"
					style="width: 100%; padding: 6px 8px; border: 1px solid #ddd; border-radius: 4px;"
				>
				<small style="color: #666; display: block; margin-top: 4px;">
					<?php echo esc_html__( 'Select a start date if you want to schedule the campaign. Leave blank to start immediately.', 'ambassadorhub' ); ?>
				</small>
			</p>
			<p style="margin: 0;">
				<label for="campaign_end_date" style="display: block; margin-bottom: 5px; font-weight: 600;">
					<?php echo esc_html__( 'End Date & Time', 'ambassadorhub' ); ?>
				</label>
				<input
					type="datetime-local"
					id="campaign_end_date"
					name="campaign_end_date"
					value="<?php echo esc_attr( $end_datetime ); ?>"
					style="width: 100%; padding: 6px 8px; border: 1px solid #ddd; border-radius: 4px;"
				>
				<small style="color: #666; display: block; margin-top: 4px;">
					<?php echo esc_html__( 'Select an end date to automatically end the campaign. Leave blank to end manually.', 'ambassadorhub' ); ?>
				</small>
			</p>
		</div>
		<?php
	}

	/**
	 * Render the Financial Goal meta box.
	 *
	 * @param \WP_Post $post Current post.
	 * @return void
	 */
	public static function render_campaign_financial_goal_meta_box( \WP_Post $post ): void {
		$goal = (float) get_post_meta( $post->ID, '_ambh_financial_goal', true );
		wp_nonce_field( 'campaign_financial_goal_nonce', 'campaign_financial_goal_nonce' );
		?>
		<p style="margin: 0;">
			<label for="ambh_financial_goal" style="display: block; margin-bottom: 5px; font-weight: 600;">
				<?php /* translators: %s: currency symbol */ ?>
				<?php echo esc_html( sprintf( __( 'Financial Goal (%s)', 'ambassadorhub' ), SettingsManager::get_currency_symbol() ) ); ?>
			</label>
			<input
				type="text"
				inputmode="decimal"
				id="ambh_financial_goal"
				name="ambh_financial_goal"
				value="<?php echo esc_attr( SettingsManager::format_amount_for_input( $goal ) ); ?>"
				class="ambh-currency-input"
				style="width: 100%;"
			/>
			<?php SettingsManager::enqueue_currency_input_assets(); ?>
			<small style="color: #666; display: block; margin-top: 4px;">
				<?php esc_html_e( 'Set a target amount for this campaign. Leave blank for no goal.', 'ambassadorhub' ); ?>
			</small>
		</p>
		<?php
	}

	/**
	 * Save the financial goal from the meta box.
	 *
	 * @param int $post_id Post ID.
	 * @return void
	 */
	public static function save_campaign_financial_goal_meta_box( int $post_id ): void {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		if ( ! isset( $_POST['campaign_financial_goal_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['campaign_financial_goal_nonce'] ) ), 'campaign_financial_goal_nonce' ) ) {
			return;
		}

		if ( array_key_exists( 'ambh_financial_goal', $_POST ) ) {
			$goal = SettingsManager::normalize_amount( sanitize_text_field( wp_unslash( $_POST['ambh_financial_goal'] ) ) );
			if ( $goal > 0 ) {
				update_post_meta( $post_id, '_ambh_financial_goal', $goal );
			} else {
				delete_post_meta( $post_id, '_ambh_financial_goal' );
			}
		}
	}

	/**
	 * Save campaign dates from the meta box.
	 *
	 * @param int $post_id Post ID.
	 * @return void
	 */
	public static function save_campaign_dates_meta_box( int $post_id ): void {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		if ( ! isset( $_POST['campaign_dates_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['campaign_dates_nonce'] ) ), 'campaign_dates_nonce' ) ) {
			return;
		}

		// Update start date via the post's publish date.
		if ( array_key_exists( 'campaign_start_date', $_POST ) ) {
			$start_date = sanitize_text_field( wp_unslash( $_POST['campaign_start_date'] ) );
			$gmt_start  = DateTimeHelper::convert_datetime_to_gmt( $start_date );
			if ( $gmt_start ) {
				$post        = get_post( $post_id );
				$current_gmt = $post ? $post->post_date_gmt : '';

				if ( $current_gmt !== $gmt_start ) {
					// Temporarily remove this hook to avoid infinite recursion.
					remove_action( 'save_post_' . CampaignsModule::POST_TYPE, array( self::class, 'save_campaign_dates_meta_box' ) );

					wp_update_post(
						array(
							'ID'            => $post_id,
							'post_date'     => DateTimeHelper::convert_gmt_to_local( $gmt_start ),
							'post_date_gmt' => $gmt_start,
						)
					);

					add_action( 'save_post_' . CampaignsModule::POST_TYPE, array( self::class, 'save_campaign_dates_meta_box' ) );
				}
			}
		}

		// Update end date as post meta.
		if ( array_key_exists( 'campaign_end_date', $_POST ) ) {
			$end_date = sanitize_text_field( wp_unslash( $_POST['campaign_end_date'] ) );
			$gmt_end  = DateTimeHelper::convert_datetime_to_gmt( $end_date );
			if ( $gmt_end ) {
				update_post_meta( $post_id, '_ambh_end_date', $gmt_end );
			}
		}
	}
}
