<?php
/**
 * The compose form.
 *
 * Ordered name, audience, message, schedule: what the campaign is called, who
 * it goes to, what it says, and when it goes.
 *
 * It used to ask for the audience, the narrowing, the numbers, a name, a time
 * and a discount code before the message — the message, the thing actually being
 * sent, came last of all.
 *
 * Included with `require` from campaigns.php rather than `load_template()`, so
 * it inherits that file's locals — the same reason the settings shell includes
 * its panels that way.
 *
 * @package TextTango
 *
 * @var array<string, mixed> $args                View data from CampaignsPage::render().
 * @var array<string, mixed> $texttango_draft     The draft being edited, or empty defaults.
 * @var string               $texttango_mode      Audience mode of the draft.
 * @var array<string, mixed> $texttango_coupons   Published coupons, code => label.
 * @var string               $texttango_chosen    Coupon chosen on the draft.
 * @var bool                 $texttango_ready     Whether the site can send at all.
 */

declare( strict_types=1 );

defined( 'ABSPATH' ) || exit;

use TextTango\Marketing\Campaign;

?>
<!-- One card at a time. This used to render under the review as well, which put
	a heading reading "New campaign" beneath a campaign that was ready to send —
	two things that looked separately actionable and were in fact the same one. -->
<div class="tt-card tt-mb-6">
	<h2 class="tt-m-0 tt-mb-4 tt-p-0 tt-text-lg tt-font-semibold tt-text-slate-900">
		<?php
		echo empty( $args['editing'] )
			? esc_html__( 'New campaign', 'texttango' )
			: esc_html__( 'Edit campaign', 'texttango' );
		?>
	</h2>

	<?php
	/*
	 * Held to a readable measure rather than the width of the card. Every field
	 * used to span the whole thing — around 1700px on a large screen — so an SMS
	 * was composed on a line four times longer than the message can ever be.
	 */
	?>
	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="tt-max-w-2xl">
		<?php wp_nonce_field( (string) $args['review_action'] ); ?>
		<input type="hidden" name="action" value="<?php echo esc_attr( (string) $args['review_action'] ); ?>">

		<h3 class="tt-eyebrow tt-m-0 tt-mb-3 tt-p-0"><?php esc_html_e( 'Campaign', 'texttango' ); ?></h3>

		<p class="tt-m-0">
			<label class="tt-label" for="texttango-campaign-name"><?php esc_html_e( 'Name', 'texttango' ); ?></label>
			<input
				type="text"
				class="tt-input"
				id="texttango-campaign-name"
				name="campaign_name"
				maxlength="255"
				value="<?php echo esc_attr( (string) ( $texttango_draft['name'] ?? '' ) ); ?>"
				placeholder="<?php esc_attr_e( 'Weekend sale', 'texttango' ); ?>"
			>
			<span class="tt-hint"><?php esc_html_e( 'Only you see this. It is how you find the campaign again.', 'texttango' ); ?></span>
		</p>

		<div class="tt-mt-8 tt-border-0 tt-border-t tt-border-solid tt-border-slate-200 tt-pt-6">
			<h3 class="tt-eyebrow tt-m-0 tt-mb-3 tt-p-0"><?php esc_html_e( 'Audience', 'texttango' ); ?></h3>

			<!-- The audience decides what everything under it means, which is why
				both panels below are nested in it and hidden with it. This was the
				mistake in an earlier version of this form: the audience was implicit,
				and the only way to influence it was a box labelled "also". -->
			<fieldset class="tt-m-0 tt-mb-5 tt-border-0 tt-p-0">
				<legend class="tt-label tt-p-0"><?php esc_html_e( 'Send to', 'texttango' ); ?></legend>

				<?php foreach ( (array) ( $args['audiences'] ?? array() ) as $texttango_value => $texttango_audience ) : ?>
					<label class="tt-mt-2 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
						<input
							type="radio"
							name="campaign_audience"
							class="tt-mt-0.5"
							value="<?php echo esc_attr( (string) $texttango_value ); ?>"
							data-texttango-audience
							<?php checked( $texttango_mode, (string) $texttango_value ); ?>
						>
						<span>
							<?php echo esc_html( (string) $texttango_audience['label'] ); ?>
							<span class="tt-hint tt-block"><?php echo esc_html( (string) $texttango_audience['hint'] ); ?></span>
						</span>
					</label>
				<?php endforeach; ?>

				<!-- Nested under the audience it narrows, and hidden with it, because a
					segment means nothing when the campaign is going to a pasted list. -->
				<div
					class="tt-mt-3 tt-rounded-md tt-bg-slate-50 tt-p-4"
					data-texttango-segment
					<?php echo Campaign::uses_customers( $texttango_mode ) ? '' : 'hidden'; ?>
				>
					<label class="tt-label" for="texttango-campaign-segment"><?php esc_html_e( 'Narrow it down', 'texttango' ); ?></label>
					<select class="tt-input tt-bg-white" id="texttango-campaign-segment" name="campaign_segment" data-texttango-segment-kind>
						<?php foreach ( (array) ( $args['segments'] ?? array() ) as $texttango_kind => $texttango_label ) : ?>
							<option value="<?php echo esc_attr( (string) $texttango_kind ); ?>" <?php selected( (string) ( $texttango_draft['segment'] ?? '' ), (string) $texttango_kind ); ?>>
								<?php echo esc_html( (string) $texttango_label ); ?>
							</option>
						<?php endforeach; ?>
					</select>

					<div
						class="tt-mt-3 tt-grid tt-grid-cols-1 tt-gap-3 sm:tt-grid-cols-2"
						data-texttango-buyers
						<?php echo 'buyers' === (string) ( $texttango_draft['segment'] ?? '' ) ? '' : 'hidden'; ?>
					>
						<div>
							<label class="tt-label" for="texttango-campaign-days"><?php esc_html_e( 'Ordered in the last', 'texttango' ); ?></label>
							<input class="tt-input tt-bg-white" id="texttango-campaign-days" name="campaign_days" type="number" min="0" max="730" step="1"
								value="<?php echo esc_attr( (string) ( $texttango_draft['days'] ?? 0 ) ); ?>" />
							<span class="tt-hint tt-block"><?php esc_html_e( 'Days. Zero means any time.', 'texttango' ); ?></span>
						</div>
						<div class="sm:tt-col-span-2">
							<label class="tt-label" for="texttango-campaign-product"><?php esc_html_e( 'Who bought', 'texttango' ); ?></label>
							<?php
							$texttango_product    = (int) ( $texttango_draft['product'] ?? 0 );
							$texttango_product_ob = $texttango_product > 0 && function_exists( 'wc_get_product' ) ? wc_get_product( $texttango_product ) : null;
							?>
							<select
								class="wc-product-search tt-input tt-bg-white"
								id="texttango-campaign-product"
								name="campaign_product"
								style="width: 100%;"
								data-placeholder="<?php esc_attr_e( 'Any product', 'texttango' ); ?>"
								data-action="woocommerce_json_search_products_and_variations"
								data-allow_clear="true"
							>
								<?php if ( $texttango_product_ob ) : ?>
									<option value="<?php echo esc_attr( (string) $texttango_product ); ?>" selected>
										<?php echo esc_html( (string) $texttango_product_ob->get_name() ); ?>
									</option>
								<?php endif; ?>
							</select>
							<span class="tt-hint tt-block">
								<?php esc_html_e( 'Leave empty for any product. Choosing one with variations also matches anybody who bought a variation of it.', 'texttango' ); ?>
							</span>
						</div>

						<div>
							<label class="tt-label" for="texttango-campaign-spend"><?php esc_html_e( 'And spent at least', 'texttango' ); ?></label>
							<input class="tt-input tt-bg-white" id="texttango-campaign-spend" name="campaign_spend" type="number" min="0" step="0.01"
								value="<?php echo esc_attr( (string) ( $texttango_draft['spend'] ?? 0 ) ); ?>" />
							<span class="tt-hint tt-block">
								<?php
								printf(
									/* translators: %s: the store's currency code. */
									esc_html__( '%s, over that same period. Zero means any amount.', 'texttango' ),
									esc_html( (string) ( $args['currency'] ?? '' ) )
								);
								?>
							</span>
						</div>

						<div>
							<label class="tt-label" for="texttango-campaign-min-orders"><?php esc_html_e( 'And ordered at least', 'texttango' ); ?></label>
							<input class="tt-input tt-bg-white" id="texttango-campaign-min-orders" name="campaign_min_orders" type="number" min="0" step="1"
								value="<?php echo esc_attr( (string) ( $texttango_draft['min_orders'] ?? 0 ) ); ?>" />
							<span class="tt-hint tt-block"><?php esc_html_e( 'Times. Zero means any number.', 'texttango' ); ?></span>
						</div>

						<div class="sm:tt-col-span-2">
							<label class="tt-label" for="texttango-campaign-category"><?php esc_html_e( 'From the category', 'texttango' ); ?></label>
							<?php
							$texttango_category = (int) ( $texttango_draft['category'] ?? 0 );
							$texttango_cats     = function_exists( 'get_terms' )
								? get_terms(
									array(
										'taxonomy'   => 'product_cat',
										'hide_empty' => false,
									)
								)
								: array();
							?>
							<select class="wc-enhanced-select tt-input tt-bg-white" id="texttango-campaign-category" name="campaign_category" style="width: 100%;" data-placeholder="<?php esc_attr_e( 'Any category', 'texttango' ); ?>" data-allow_clear="true">
								<option value=""></option>
								<?php foreach ( (array) $texttango_cats as $texttango_term ) : ?>
									<?php if ( ! $texttango_term instanceof WP_Term ) : ?>
										<?php continue; ?>
									<?php endif; ?>
									<option value="<?php echo esc_attr( (string) $texttango_term->term_id ); ?>" <?php selected( $texttango_category, $texttango_term->term_id ); ?>>
										<?php echo esc_html( $texttango_term->name ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<span class="tt-hint tt-block">
								<?php esc_html_e( 'Matches whichever product was bought, not a category chosen above and below it.', 'texttango' ); ?>
							</span>
						</div>

						<div class="sm:tt-col-span-2">
							<label class="tt-label" for="texttango-campaign-country"><?php esc_html_e( 'Billed to', 'texttango' ); ?></label>
							<?php
							$texttango_country   = (string) ( $texttango_draft['country'] ?? '' );
							$texttango_countries = function_exists( 'WC' ) && WC()->countries instanceof WC_Countries
								? WC()->countries->get_countries()
								: array();
							?>
							<select class="wc-enhanced-select tt-input tt-bg-white" id="texttango-campaign-country" name="campaign_country" style="width: 100%;" data-placeholder="<?php esc_attr_e( 'Any country', 'texttango' ); ?>" data-allow_clear="true">
								<option value=""></option>
								<?php foreach ( (array) $texttango_countries as $texttango_code => $texttango_name ) : ?>
									<option value="<?php echo esc_attr( (string) $texttango_code ); ?>" <?php selected( $texttango_country, (string) $texttango_code ); ?>>
										<?php echo esc_html( (string) $texttango_name ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<span class="tt-hint tt-block"><?php esc_html_e( 'The billing country on the order.', 'texttango' ); ?></span>
						</div>
					</div>

					<?php if ( (int) ( $args['consent_list_count'] ?? 0 ) > 0 ) : ?>
						<p class="tt-hint tt-mt-3 tt-mb-0">
							<?php esc_html_e( 'Numbers imported without an account have no order history, so narrowing by orders sets them aside. The review says how many.', 'texttango' ); ?>
						</p>
					<?php endif; ?>
				</div>
			</fieldset>

			<!-- Revealed by the two audiences that use it. The server ignores anything
				in here when the audience is customers, so this is presentation and
				never the guard. -->
			<div
				class="tt-m-0 tt-rounded-md tt-bg-slate-50 tt-p-4"
				data-texttango-supplied
				<?php echo Campaign::uses_supplied( $texttango_mode ) ? '' : 'hidden'; ?>
			>
				<label class="tt-label" for="texttango-campaign-supplied"><?php esc_html_e( 'Numbers', 'texttango' ); ?></label>
				<p class="tt-hint tt-mt-0">
					<?php
					printf(
						/* translators: %s: the maximum number of supplied recipients. */
						esc_html__( 'For consent you hold somewhere this plugin cannot see — a signup sheet, or a system you are moving from. One per line, or separated by commas. Up to %s.', 'texttango' ),
						esc_html( number_format_i18n( (int) ( $args['supplied_max'] ?? 0 ) ) )
					);
					?>
				</p>

				<textarea
					class="tt-input tt-bg-white tt-font-mono tt-text-xs"
					id="texttango-campaign-supplied"
					name="campaign_supplied"
					rows="4"
					placeholder="+233501234567&#10;0244123456"
				><?php echo esc_textarea( (string) ( $texttango_draft['supplied'] ?? '' ) ); ?></textarea>

				<label class="tt-mt-3 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
					<input type="checkbox" name="campaign_asserted" value="1" class="tt-mt-0.5"
						<?php checked( ! empty( $texttango_draft['asserted'] ) ); ?> />
					<span>
						<?php esc_html_e( 'These people agreed to marketing messages from this store.', 'texttango' ); ?>
						<span class="tt-hint tt-block">
							<?php esc_html_e( 'Recorded in the audit trail against your name and today\'s date. Anyone on your opt-out list is still excluded — pasting a number back in does not undo somebody asking you to stop.', 'texttango' ); ?>
						</span>
					</span>
				</label>
			</div>
		</div>

		<div class="tt-mt-8 tt-border-0 tt-border-t tt-border-solid tt-border-slate-200 tt-pt-6">
			<h3 class="tt-eyebrow tt-m-0 tt-mb-3 tt-p-0"><?php esc_html_e( 'Message', 'texttango' ); ?></h3>

			<p class="tt-mb-4">
				<label class="tt-label" for="texttango-campaign-body"><?php esc_html_e( 'What it says', 'texttango' ); ?></label>
				<textarea
					class="tt-input"
					id="texttango-campaign-body"
					name="campaign_body"
					rows="5"
					data-texttango-campaign-body
					data-texttango-estimate="#texttango-campaign-estimate"
				><?php echo esc_textarea( (string) ( $texttango_draft['body'] ?? '' ) ); ?></textarea>
				<span class="tt-hint tt-block" id="texttango-campaign-estimate">
					<?php
					$texttango_typed = Campaign::estimate( 0, (string) ( $texttango_draft['body'] ?? '' ) );

					printf(
						/* translators: 1: character count, 2: encoding name, 3: number of SMS segments. */
						esc_html__( '%1$d characters, %2$s encoding, %3$d SMS', 'texttango' ),
						(int) $texttango_typed['length'],
						esc_html( (string) $texttango_typed['encoding'] ),
						(int) $texttango_typed['segments']
					);
					?>
				</span>
			</p>

			<!-- Coupon tags only. Order tags have no meaning here — a campaign is not
				about an order — and offering them would produce messages reading "your
				order {order_number} is ready" to everybody. -->
			<p class="tt-hint tt-mt-0 tt-mb-2">
				<?php esc_html_e( 'Merge tags:', 'texttango' ); ?>
				<?php foreach ( (array) ( $args['coupon_tags'] ?? array() ) as $texttango_tag => $texttango_meaning ) : ?>
					<code class="tt-text-xs" title="<?php echo esc_attr( (string) $texttango_meaning ); ?>"><?php echo esc_html( (string) $texttango_tag ); ?></code>
				<?php endforeach; ?>
			</p>

			<p class="tt-hint tt-mt-0 tt-mb-4">
				<?php esc_html_e( 'Include how to stop: TextTango adds no opt-out line for you, and a marketing SMS without one is a complaint waiting to happen.', 'texttango' ); ?>
			</p>

			<!-- With the message rather than with the scheduling: choosing a code puts
				{coupon_code} into the text, so it is part of what is being written. -->
			<p class="tt-m-0">
				<label class="tt-label" for="texttango-campaign-coupon"><?php esc_html_e( 'Discount code', 'texttango' ); ?></label>
				<select class="tt-input" id="texttango-campaign-coupon" name="campaign_coupon">
					<option value=""><?php esc_html_e( 'No discount code', 'texttango' ); ?></option>
					<?php foreach ( $texttango_coupons as $texttango_code => $texttango_label ) : ?>
						<option value="<?php echo esc_attr( (string) $texttango_code ); ?>" <?php selected( $texttango_chosen, (string) $texttango_code ); ?>>
							<?php echo esc_html( (string) $texttango_label ); ?>
						</option>
					<?php endforeach; ?>
				</select>
				<span class="tt-hint tt-block">
					<?php if ( array() === $texttango_coupons ) : ?>
						<?php esc_html_e( 'This store has no published coupons yet. Create one under Marketing → Coupons and it will appear here.', 'texttango' ); ?>
					<?php else : ?>
						<?php esc_html_e( 'Whatever you choose here sets the discount, the expiry and the minimum spend.', 'texttango' ); ?>
					<?php endif; ?>
				</span>
			</p>

			<?php
			/*
			 * Only once a coupon is chosen. With none, both options do the same
			 * nothing, and a control whose settings make no difference teaches
			 * somebody that this one never matters.
			 */
			?>
			<?php if ( '' !== $texttango_chosen ) : ?>
				<?php $texttango_delivery = (string) ( $texttango_draft['delivery'] ?? Campaign::DELIVERY_BULK ); ?>
				<fieldset class="tt-m-0 tt-mt-4 tt-border-0 tt-p-0">
					<legend class="tt-label tt-p-0"><?php esc_html_e( 'How the code is given out', 'texttango' ); ?></legend>

					<label class="tt-mt-2 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
						<input type="radio" name="campaign_delivery" value="<?php echo esc_attr( Campaign::DELIVERY_BULK ); ?>" class="tt-mt-1"
							<?php checked( Campaign::DELIVERY_BULK, $texttango_delivery ); ?> />
						<span>
							<strong><?php esc_html_e( 'One code, shared', 'texttango' ); ?></strong>
							<span class="tt-hint tt-block"><?php esc_html_e( 'Everybody gets the same code. Sent as one campaign, which is the cheapest and fastest way — but a code that reaches one person can reach anybody they send it to.', 'texttango' ); ?></span>
						</span>
					</label>

					<label class="tt-mt-3 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
						<input type="radio" name="campaign_delivery" value="<?php echo esc_attr( Campaign::DELIVERY_PERSONAL ); ?>" class="tt-mt-1"
							<?php checked( Campaign::DELIVERY_PERSONAL, $texttango_delivery ); ?> />
						<span>
							<strong><?php esc_html_e( 'A code each', 'texttango' ); ?></strong>
							<span class="tt-hint tt-block"><?php esc_html_e( 'Everybody gets their own single-use code, built from the coupon above and expiring with it. Sent one message at a time rather than as one campaign, so it takes longer — the review will say how much longer.', 'texttango' ); ?></span>
						</span>
					</label>
				</fieldset>
			<?php endif; ?>
		</div>

		<div class="tt-mt-8 tt-border-0 tt-border-t tt-border-solid tt-border-slate-200 tt-pt-6">
			<h3 class="tt-eyebrow tt-m-0 tt-mb-3 tt-p-0"><?php esc_html_e( 'Schedule', 'texttango' ); ?></h3>

			<?php $texttango_when = (int) ( $texttango_draft['when'] ?? 0 ); ?>
			<fieldset class="tt-m-0 tt-border-0 tt-p-0">
				<legend class="tt-label tt-p-0"><?php esc_html_e( 'When', 'texttango' ); ?></legend>

				<label class="tt-mt-2 tt-flex tt-items-center tt-gap-2 tt-text-sm tt-text-slate-700">
					<input type="radio" name="campaign_timing" value="now" data-texttango-timing
						<?php checked( 0, $texttango_when ); ?> />
					<span><?php esc_html_e( 'Send now', 'texttango' ); ?></span>
				</label>

				<label class="tt-mt-2 tt-flex tt-items-center tt-gap-2 tt-text-sm tt-text-slate-700">
					<input type="radio" name="campaign_timing" value="later" data-texttango-timing
						<?php checked( true, $texttango_when > 0 ); ?> />
					<span><?php esc_html_e( 'Send later', 'texttango' ); ?></span>
				</label>

				<div class="tt-mt-2" data-texttango-when <?php echo $texttango_when > 0 ? '' : 'hidden'; ?>>
					<input
						type="datetime-local"
						class="tt-input"
						name="campaign_when"
						value="<?php echo esc_attr( $texttango_when > 0 ? wp_date( 'Y-m-d\TH:i', $texttango_when ) : '' ); ?>"
					/>
					<span class="tt-hint tt-block">
						<?php
						printf(
							/* translators: %s: the site's timezone, e.g. Africa/Accra. */
							esc_html__( 'Your site\'s time (%s). TextTango holds the campaign until then, and you can stop it any time before it goes.', 'texttango' ),
							esc_html( (string) ( $args['timezone'] ?? '' ) )
						);
						?>
					</span>
				</div>
			</fieldset>
		</div>

		<div class="tt-mt-8 tt-border-0 tt-border-t tt-border-solid tt-border-slate-200 tt-pt-6">
			<button type="submit" class="tt-btn tt-btn-primary" <?php disabled( ! $texttango_ready ); ?>>
				<?php esc_html_e( 'Review before sending', 'texttango' ); ?>
			</button>
		</div>
	</form>
</div>
