<?php
/**
 * Campaign Step (now: Create first fundraiser)
 *
 * Suggests creating the first root fundraiser. This is an optional step.
 *
 * @package AmbassadorHub\Admin\Wizard\Steps
 */

namespace AmbassadorHub\Admin\Wizard\Steps;

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

use AmbassadorHub\Admin\Wizard\AbstractWizardStep;
use AmbassadorHub\Admin\Wizard\SetupWizard;
use AmbassadorHub\Fundraisers\FundraisersModule;

/**
 * Wizard step for creating the first root fundraiser.
 */
final class CampaignStep extends AbstractWizardStep {

	/**
	 * {@inheritdoc}
	 */
	public function get_id(): string {
		return 'campaign';
	}

	/**
	 * {@inheritdoc}
	 */
	public function get_title(): string {
		return __( 'Create your first fundraiser', 'ambassadorhub' );
	}

	/**
	 * {@inheritdoc}
	 */
	public function is_skippable(): bool {
		return true;
	}

	/**
	 * {@inheritdoc}
	 */
	public function is_alertable(): bool {
		return true;
	}

	/**
	 * {@inheritdoc}
	 */
	public function is_done(): bool {
		return (int) ( wp_count_posts( FundraisersModule::POST_TYPE )->publish ?? 0 ) > 0;
	}

	/**
	 * {@inheritdoc}
	 *
	 * When no fundraiser exists yet, creates a root fundraiser from the submitted
	 * title and description fields.
	 */
	public function handle( array $post_data ): ?string {
		if ( $this->is_done() ) {
			return null;
		}

		$post_title   = sanitize_text_field( $post_data['ambh_campaign_title'] ?? '' );
		$post_content = wp_kses_post( $post_data['ambh_campaign_description'] ?? '' );

		if ( '' === $post_title ) {
			return add_query_arg(
				array( 'ambh_wizard_error' => 'missing_title' ),
				admin_url( 'admin.php?page=' . SetupWizard::PAGE_SLUG )
			);
		}

		$result = wp_insert_post(
			array(
				'post_type'    => FundraisersModule::POST_TYPE,
				'post_title'   => $post_title,
				'post_content' => $post_content,
				'post_status'  => 'publish',
				'post_parent'  => 0,
			),
			true
		);

		if ( is_wp_error( $result ) ) {
			return add_query_arg(
				array( 'ambh_wizard_error' => 'create_failed' ),
				admin_url( 'admin.php?page=' . SetupWizard::PAGE_SLUG )
			);
		}

		return null;
	}

	/**
	 * {@inheritdoc}
	 */
	public function render(): void {
		$fundraiser_count    = (int) ( wp_count_posts( FundraisersModule::POST_TYPE )->publish ?? 0 );
		$all_fundraisers_url = admin_url( 'edit.php?post_type=' . FundraisersModule::POST_TYPE );

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$error = isset( $_GET['ambh_wizard_error'] ) ? sanitize_key( $_GET['ambh_wizard_error'] ) : '';
		?>
		<?php if ( $fundraiser_count > 0 ) : ?>
			<div class="ambh-wizard-status ambh-wizard-status--done">
				<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>
				<?php
				echo esc_html(
					sprintf(
						/* translators: %d: number of published fundraisers */
						_n(
							'You have %d published fundraiser.',
							'You have %d published fundraisers.',
							$fundraiser_count,
							'ambassadorhub'
						),
						$fundraiser_count
					)
				);
				?>
			</div>
			<p>
				<a href="<?php echo esc_url( $all_fundraisers_url ); ?>" class="button" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'View fundraisers', 'ambassadorhub' ); ?>
					<span class="dashicons dashicons-external" aria-hidden="true" style="font-size:14px;width:14px;height:14px;margin-top:2px;"></span>
				</a>
			</p>
		<?php else : ?>
			<p>
				<?php esc_html_e( 'A root fundraiser is the top-level entity in AmbassadorHub. It defines the overall goal and scope.', 'ambassadorhub' ); ?>
			</p>

			<?php if ( 'missing_title' === $error ) : ?>
				<div class="notice notice-error inline" style="margin:0 0 12px;">
					<p><?php esc_html_e( 'Please enter a fundraiser name.', 'ambassadorhub' ); ?></p>
				</div>
			<?php elseif ( 'create_failed' === $error ) : ?>
				<div class="notice notice-error inline" style="margin:0 0 12px;">
					<p><?php esc_html_e( 'Something went wrong while creating the fundraiser. Please try again.', 'ambassadorhub' ); ?></p>
				</div>
			<?php endif; ?>

			<table class="form-table" role="presentation" style="margin-top:0;">
				<tr>
					<th scope="row">
						<label for="ambh_campaign_title">
							<?php esc_html_e( 'Fundraiser name', 'ambassadorhub' ); ?>
							<span aria-hidden="true" style="color:#d63638;margin-left:2px;">*</span>
						</label>
					</th>
					<td>
						<input
							type="text"
							id="ambh_campaign_title"
							name="ambh_campaign_title"
							class="regular-text"
							required
							value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['ambh_campaign_title'] ?? '' ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing ?>"
						>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="ambh_campaign_description">
							<?php esc_html_e( 'Description', 'ambassadorhub' ); ?>
						</label>
					</th>
					<td>
						<textarea
							id="ambh_campaign_description"
							name="ambh_campaign_description"
							class="large-text"
							rows="4"
						><?php echo esc_textarea( sanitize_textarea_field( wp_unslash( $_POST['ambh_campaign_description'] ?? '' ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing ?></textarea>
						<p class="description">
							<?php esc_html_e( 'Optional. You can update this later.', 'ambassadorhub' ); ?>
						</p>
					</td>
				</tr>
			</table>
		<?php endif; ?>
		<?php
	}
}
