<?php
/**
 * The campaigns screen.
 *
 * Two views: composing a campaign, and what has already gone out. They used to
 * be one scroll, so seeing whether last night's send landed meant scrolling past
 * the whole compose form.
 *
 * Reviewing is a state of the compose view rather than a third view. The review
 * is deliberately not a dialog — a confirmation you can dismiss with Escape is
 * one you can dismiss without reading, and this one is worth reading.
 *
 * @package TextTango
 *
 * @var array<string, mixed> $args View data supplied by CampaignsPage::render().
 */

declare( strict_types=1 );

defined( 'ABSPATH' ) || exit;

use TextTango\Admin\CampaignsPage;
use TextTango\Marketing\Audience;
use TextTango\Marketing\Campaign;
use TextTango\Marketing\CampaignLog;
use TextTango\Marketing\Coupons;
use TextTango\Marketing\PersonalCampaign;
use TextTango\Marketing\SuppliedNumbers;
use TextTango\Support\Paging;

$texttango_view       = (string) ( $args['view'] ?? CampaignsPage::VIEW_NEW );
$texttango_reviewing  = ! empty( $args['reviewing'] );
$texttango_draft      = (array) ( $args['draft'] ?? array() );
$texttango_review     = (array) ( $args['review'] ?? array() );
$texttango_estimate   = (array) ( $texttango_review['estimate'] ?? array() );
$texttango_history    = (array) ( $args['history'] ?? array() );
$texttango_flight     = (array) ( $args['in_flight'] ?? array() );
$texttango_connected  = ! empty( $args['connected'] );
$texttango_sender     = (string) ( $args['sender_id'] ?? '' );
$texttango_ready      = $texttango_connected && '' !== $texttango_sender;
$texttango_count      = count( (array) ( $texttango_review['recipients'] ?? array() ) );
$texttango_blocked    = (string) ( $texttango_review['blocked'] ?? '' );
$texttango_delay      = (int) ( $texttango_review['delay'] ?? 0 );
$texttango_coupons    = (array) ( $args['coupons'] ?? array() );
$texttango_chosen     = (string) ( $texttango_draft['coupon'] ?? '' );
$texttango_refused    = (string) ( $texttango_review['refused'] ?? '' );
$texttango_warnings   = (array) ( $texttango_review['warnings'] ?? array() );
$texttango_supplied   = (array) ( $texttango_review['supplied'] ?? array() );
$texttango_mode       = (string) ( $texttango_draft['mode'] ?? Campaign::AUDIENCE_CUSTOMERS );
$texttango_from_list  = count( (array) ( $texttango_supplied['recipients'] ?? array() ) );
$texttango_unusable   = (array) ( $texttango_supplied['unusable'] ?? array() );
$texttango_opened     = $args['opened'] ?? null;
$texttango_recipients = (array) ( $args['recipients'] ?? array() );
$texttango_rec_paging = $args['recipient_paging'] ?? null;
?>
<div class="wrap">
	<div id="texttango-app" class="texttango-ui">
		<div class="tt-py-4">

			<header class="tt-mb-6">
				<?php
				load_template(
					TEXTTANGO_PATH . 'templates/admin/partials/brand.php',
					false,
					array( 'title' => __( 'Campaigns', 'texttango' ) )
				);
				?>
				<p class="tt-mt-1 tt-flex tt-flex-wrap tt-items-center tt-gap-x-3 tt-gap-y-1 tt-text-sm tt-text-slate-500">
					<span><?php esc_html_e( 'One message, to an audience you choose.', 'texttango' ); ?></span>

					<?php if ( '' !== (string) ( $args['balance'] ?? '' ) ) : ?>
						<span class="tt-text-slate-400">&middot;</span>
						<span><?php echo esc_html( (string) $args['balance'] ); ?></span>
					<?php endif; ?>

					<?php if ( '' !== $texttango_sender ) : ?>
						<span class="tt-text-slate-400">&middot;</span>
						<span><?php echo esc_html( $texttango_sender ); ?></span>
					<?php endif; ?>
				</p>
			</header>

			<?php foreach ( (array) ( $args['notices'] ?? array() ) as $texttango_notice ) : ?>
				<div class="tt-notice tt-notice-<?php echo esc_attr( 'ok' === $texttango_notice['type'] ? 'ok' : ( 'warn' === $texttango_notice['type'] ? 'warn' : 'error' ) ); ?> tt-mb-4">
					<?php echo esc_html( (string) $texttango_notice['message'] ); ?>
				</div>
			<?php endforeach; ?>

			<?php if ( ! $texttango_ready ) : ?>
				<div class="tt-notice tt-notice-warn tt-mb-4">
					<?php if ( ! $texttango_connected ) : ?>
						<?php esc_html_e( 'This site is not connected to TextTango yet, so there is nothing to send with.', 'texttango' ); ?>
					<?php else : ?>
						<?php esc_html_e( 'No sender ID is chosen, so a campaign has no name to arrive from.', 'texttango' ); ?>
					<?php endif; ?>
					<a href="<?php echo esc_url( (string) ( $args['settings_url'] ?? '' ) ); ?>"><?php esc_html_e( 'Open settings', 'texttango' ); ?></a>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $args['sandbox_active'] ) ) : ?>
				<div class="tt-notice tt-notice-warn tt-mb-4">
					<?php echo esc_html( (string) ( $args['sandbox_note'] ?? '' ) ); ?>
				</div>
			<?php endif; ?>

			<?php
			load_template(
				TEXTTANGO_PATH . 'templates/admin/partials/tab-bar.php',
				false,
				array(
					'rows'  => (array) ( $args['view_rows'] ?? array() ),
					'label' => __( 'Campaign sections', 'texttango' ),
				)
			);
			?>

			<?php if ( CampaignsPage::VIEW_NEW === $texttango_view ) : ?>

				<?php if ( $texttango_reviewing ) : ?>

				<!-- Review. The last screen before money is spent, so every figure
					that decides whether to press the button is on it. -->
				<div class="tt-card tt-mb-6">
					<h2 class="tt-m-0 tt-mb-1 tt-p-0 tt-text-lg tt-font-semibold tt-text-slate-900">
						<?php esc_html_e( 'Ready to send', 'texttango' ); ?>
					</h2>
					<p class="tt-hint tt-mt-0 tt-mb-4">
						<?php esc_html_e( 'Nothing has been sent yet. Check it over — this cannot be taken back once it goes.', 'texttango' ); ?>
					</p>

					<!-- The resolved body, not the draft. This is the message that
						arrives, and a merge tag that quietly resolved to nothing is
						exactly what this screen is for. -->
					<blockquote class="tt-m-0 tt-mb-4 tt-whitespace-pre-wrap tt-rounded-md tt-border-0 tt-border-l-4 tt-border-solid tt-border-slate-300 tt-bg-slate-50 tt-p-4 tt-text-sm tt-text-slate-700">
						<?php echo esc_html( (string) ( $texttango_review['body'] ?? $texttango_draft['body'] ?? '' ) ); ?>
					</blockquote>

					<dl class="tt-m-0 tt-mb-4 tt-grid tt-grid-cols-2 tt-gap-4 md:tt-grid-cols-4">
						<div>
							<dt class="tt-eyebrow"><?php esc_html_e( 'Recipients', 'texttango' ); ?></dt>
							<dd class="tt-m-0 tt-text-xl tt-font-semibold tt-text-slate-900"><?php echo esc_html( number_format_i18n( $texttango_count ) ); ?></dd>
						</div>
						<div>
							<dt class="tt-eyebrow"><?php esc_html_e( 'SMS each', 'texttango' ); ?></dt>
							<dd class="tt-m-0 tt-text-xl tt-font-semibold tt-text-slate-900"><?php echo esc_html( number_format_i18n( (int) ( $texttango_estimate['segments'] ?? 0 ) ) ); ?></dd>
						</div>
						<div>
							<dt class="tt-eyebrow"><?php esc_html_e( 'Credits', 'texttango' ); ?></dt>
							<dd class="tt-m-0 tt-text-xl tt-font-semibold tt-text-slate-900"><?php echo esc_html( number_format_i18n( (int) ( $texttango_estimate['credits'] ?? 0 ) ) ); ?></dd>
						</div>
						<div>
							<dt class="tt-eyebrow"><?php esc_html_e( 'Encoding', 'texttango' ); ?></dt>
							<dd class="tt-m-0 tt-text-xl tt-font-semibold tt-text-slate-900"><?php echo esc_html( (string) ( $texttango_estimate['encoding'] ?? '' ) ); ?></dd>
						</div>
					</dl>

					<?php
					/*
					 * A personal-code campaign is a different transaction from a bulk
					 * one, and the review is the last screen before money is spent, so
					 * the differences are stated rather than left to be discovered:
					 * it is N sends against one request, it is paced, and each code is
					 * single-use. None of that is visible from the message itself.
					 */
					?>
					<?php if ( Campaign::DELIVERY_PERSONAL === (string) ( $texttango_draft['delivery'] ?? '' ) && $texttango_count > 0 ) : ?>
						<?php
						// Batches run back to back, so the honest figure is the number
						// of batches rather than a guess at each message's latency.
						$texttango_batches = (int) ceil( $texttango_count / PersonalCampaign::BATCH );
						?>
						<div class="tt-notice tt-notice-warn tt-mb-4">
							<p class="tt-m-0 tt-mb-2">
								<strong><?php esc_html_e( 'Everybody gets their own code.', 'texttango' ); ?></strong>
							</p>
							<ul class="tt-m-0 tt-list-disc tt-pl-5 tt-text-sm">
								<li>
									<?php
									echo esc_html(
										sprintf(
											/* translators: 1: number of messages, 2: number of batches. */
											__( 'This sends %1$s separate messages rather than one campaign, in %2$s batches. Your spend caps count every one of them.', 'texttango' ),
											number_format_i18n( $texttango_count ),
											number_format_i18n( $texttango_batches )
										)
									);
									?>
								</li>
								<li><?php esc_html_e( 'Each code works once, for one person, and expires when the coupon above does.', 'texttango' ); ?></li>
								<li><?php esc_html_e( 'A code is created only as its message goes out, so stopping the campaign creates no more of them.', 'texttango' ); ?></li>
							</ul>
						</div>
					<?php endif; ?>

					<?php
					$texttango_chose = (string) ( $texttango_review['mode'] ?? Campaign::AUDIENCE_CUSTOMERS );
					?>
					<p class="tt-mt-0 tt-mb-4 tt-text-sm tt-text-slate-700">
						<strong><?php esc_html_e( 'Going to:', 'texttango' ); ?></strong>
						<?php echo esc_html( (string) ( ( $args['audiences'][ $texttango_chose ]['label'] ?? '' ) ) ); ?>
					</p>

					<?php if ( $texttango_from_list > 0 && Campaign::AUDIENCE_BOTH === $texttango_chose ) : ?>
						<!-- The split between consent this plugin can prove and consent
							somebody vouched for. Folded into one number, the difference
							disappears exactly where it matters most. -->
						<p class="tt-mt-0 tt-mb-4 tt-rounded-md tt-bg-slate-50 tt-p-3 tt-text-sm tt-text-slate-700">
							<?php
							printf(
								/* translators: 1: recipients from recorded consent, 2: recipients the merchant supplied. */
								esc_html__( '%1$s from your own consent records, %2$s you supplied.', 'texttango' ),
								esc_html( number_format_i18n( max( 0, $texttango_count - $texttango_from_list ) ) ),
								esc_html( number_format_i18n( $texttango_from_list ) )
							);
							?>
						</p>
					<?php endif; ?>

					<?php if ( array() !== $texttango_unusable ) : ?>
						<div class="tt-notice tt-notice-warn tt-mb-4">
							<?php esc_html_e( 'These numbers could not be read and will not be sent to:', 'texttango' ); ?>
							<code class="tt-text-xs"><?php echo esc_html( implode( ', ', array_slice( $texttango_unusable, 0, 20 ) ) ); ?></code>
						</div>
					<?php endif; ?>

					<?php if ( ! empty( $texttango_supplied['truncated'] ) ) : ?>
						<div class="tt-notice tt-notice-warn tt-mb-4">
							<?php
							printf(
								/* translators: %s: the maximum number of supplied recipients. */
								esc_html__( 'You supplied more numbers than one campaign takes, so only the first %s of them are included.', 'texttango' ),
								esc_html( number_format_i18n( SuppliedNumbers::MAX ) )
							);
							?>
						</div>
					<?php endif; ?>

					<?php if ( ! empty( $texttango_review['narrowing'] ) ) : ?>
						<p class="tt-mt-0 tt-mb-4 tt-rounded-md tt-bg-slate-50 tt-p-3 tt-text-sm tt-text-slate-700">
							<strong><?php esc_html_e( 'Segment:', 'texttango' ); ?></strong>
							<?php echo esc_html( (string) ( $texttango_review['segment'] ?? '' ) ); ?>
							<span class="tt-hint tt-block">
								<?php
								printf(
									/* translators: 1: people whose consent is on record, 2: how many fall outside the segment. */
									esc_html__( '%1$s consenting, %2$s outside this segment.', 'texttango' ),
									esc_html( number_format_i18n( (int) ( $texttango_review['consenting'] ?? 0 ) ) ),
									esc_html( number_format_i18n( (int) ( $texttango_review['outside'] ?? 0 ) ) )
								);
								?>
							</span>
							<?php if ( (int) ( $texttango_review['listed'] ?? 0 ) > 0 ) : ?>
								<span class="tt-hint tt-block">
									<?php
									printf(
										/* translators: %s: number of imported numbers set aside. */
										esc_html__( '%s imported without an account were set aside — they have no order history to narrow by.', 'texttango' ),
										esc_html( number_format_i18n( (int) $texttango_review['listed'] ) )
									);
									?>
								</span>
							<?php endif; ?>
						</p>
					<?php endif; ?>

					<!-- Who is not getting it, and why. Left off a review, this is the
						figure a merchant only discovers by wondering why the count is
						lower than their customer list. -->
					<p class="tt-hint tt-mt-0 tt-mb-4">
						<?php
						printf(
							/* translators: 1: people whose consent is on record, 2: excluded for opting out, 3: excluded for having no usable number. */
							esc_html__( '%1$s on record as agreeing. %2$s excluded for opting out, %3$s for having no usable number.', 'texttango' ),
							esc_html( number_format_i18n( (int) ( $texttango_review['consenting'] ?? 0 ) ) ),
							esc_html( number_format_i18n( (int) ( $texttango_review['suppressed'] ?? 0 ) ) ),
							esc_html( number_format_i18n( (int) ( $texttango_review['unusable'] ?? 0 ) ) )
						);
						?>
					</p>

					<?php if ( ! empty( $texttango_review['truncated'] ) ) : ?>
						<div class="tt-notice tt-notice-warn tt-mb-4">
							<?php
							printf(
								/* translators: %s: the maximum number of recipients one campaign can hold. */
								esc_html__( 'More people qualify than one campaign can hold, so only the first %s will receive this.', 'texttango' ),
								esc_html( number_format_i18n( Audience::MAX_RECIPIENTS ) )
							);
							?>
						</div>
					<?php endif; ?>

					<?php
					$texttango_sends_at = (int) ( $texttango_review['sends_at'] ?? 0 );
					$texttango_moved    = ! empty( $texttango_review['moved'] );
					$texttango_bad_time = (string) ( $texttango_review['bad_time'] ?? '' );
					?>

					<?php if ( '' !== $texttango_bad_time ) : ?>
						<div class="tt-notice tt-notice-error tt-mb-4">
							<?php echo esc_html( Campaign::refused_time_text( $texttango_bad_time ) ); ?>
						</div>
					<?php elseif ( $texttango_moved ) : ?>
						<div class="tt-notice tt-notice-warn tt-mb-4">
							<?php
							printf(
								/* translators: %s: local date and time. */
								esc_html__( 'The time you picked falls inside your quiet hours, so this will go at %s instead.', 'texttango' ),
								esc_html( wp_date( 'j M, H:i', $texttango_sends_at ) )
							);
							?>
						</div>
					<?php elseif ( $texttango_sends_at > 0 ) : ?>
						<div class="tt-notice tt-notice-warn tt-mb-4">
							<?php
							printf(
								/* translators: %s: local date and time. */
								esc_html__( 'TextTango will hold this until %s. You can stop it any time before then.', 'texttango' ),
								esc_html( wp_date( 'j M, H:i', $texttango_sends_at ) )
							);
							?>
						</div>
					<?php endif; ?>

					<?php if ( '' !== $texttango_refused ) : ?>
						<div class="tt-notice tt-notice-error tt-mb-4">
							<?php
							$texttango_says = Coupons::blocked_text( $texttango_refused );

							echo esc_html(
								'' !== $texttango_says
									? $texttango_says
									: SuppliedNumbers::refusal_text( $texttango_refused )
							);
							?>
						</div>
					<?php endif; ?>

					<?php foreach ( $texttango_warnings as $texttango_warning ) : ?>
						<div class="tt-notice tt-notice-warn tt-mb-4">
							<?php echo esc_html( (string) $texttango_warning ); ?>
						</div>
					<?php endforeach; ?>

					<?php if ( '' !== $texttango_blocked ) : ?>
						<div class="tt-notice tt-notice-error tt-mb-4">
							<?php echo esc_html( Campaign::blocked_text( $texttango_blocked ) ); ?>
						</div>
					<?php endif; ?>

					<div class="tt-flex tt-flex-wrap tt-items-center tt-gap-3">
						<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
							<?php wp_nonce_field( (string) $args['send_action'] ); ?>
							<input type="hidden" name="action" value="<?php echo esc_attr( (string) $args['send_action'] ); ?>">
							<button
								type="submit"
								class="tt-btn tt-btn-primary"
								<?php disabled( '' !== $texttango_blocked || '' !== $texttango_refused || '' !== (string) ( $texttango_review['bad_time'] ?? '' ) || 0 === $texttango_count || ! $texttango_ready ); ?>
							>
								<?php
								echo (int) ( $texttango_review['sends_at'] ?? 0 ) > 0
									? esc_html__( 'Schedule it', 'texttango' )
									: esc_html__( 'Send it now', 'texttango' );
								?>
							</button>
						</form>

						<!-- A plain link: it changes nothing, it only draws the other
							card. Beside the explanation of why a campaign cannot send,
							because that explanation is almost always something to go
							back and fix rather than to give up over. -->
						<a class="tt-btn tt-btn-secondary" href="<?php echo esc_url( (string) ( $args['edit_url'] ?? '' ) ); ?>">
							<?php esc_html_e( 'Edit', 'texttango' ); ?>
						</a>

						<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
							<?php wp_nonce_field( (string) $args['discard_action'] ); ?>
							<input type="hidden" name="action" value="<?php echo esc_attr( (string) $args['discard_action'] ); ?>">
							<button type="submit" class="tt-btn tt-btn-secondary">
								<?php esc_html_e( 'Discard', 'texttango' ); ?>
							</button>
						</form>
					</div>
				</div>

			<?php endif; ?>

				<?php if ( ! $texttango_reviewing ) : ?>

					<?php
					/*
					* A plain require, so the form inherits the locals above rather than
					* having a dozen of them threaded through load_template() — the same
					* reason the settings shell includes its panels this way.
					*/
					require TEXTTANGO_PATH . 'templates/admin/campaigns/compose.php';
					?>

			<?php endif; ?>

			<?php else : ?>

				<?php
				/*
				* One campaign's recipients, above the history it was opened from.
				*
				* Only reachable for a personal campaign, and only through a link on
				* its own row: the numbers and codes here are the same personal data
				* the message log holds, so this sits behind the same capability and
				* is never the default view.
				*/
				?>
				<?php if ( null !== $texttango_opened ) : ?>
				<div class="tt-card tt-mb-4">
					<div class="tt-mb-4 tt-flex tt-flex-wrap tt-items-start tt-justify-between tt-gap-3">
						<div>
							<h2 class="tt-m-0 tt-mb-1 tt-p-0 tt-text-lg tt-font-semibold tt-text-slate-900">
								<?php echo esc_html( (string) ( $texttango_opened['name'] ?? '' ) ); ?>
							</h2>
							<p class="tt-m-0 tt-text-sm tt-text-slate-500">
								<?php esc_html_e( 'Who this campaign reached, and the code each person was given. Each code works once.', 'texttango' ); ?>
							</p>
						</div>
						<a class="tt-btn tt-btn-secondary tt-shrink-0" href="<?php echo esc_url( CampaignsPage::url( CampaignsPage::VIEW_HISTORY ) ); ?>">
							<?php esc_html_e( 'Back to history', 'texttango' ); ?>
						</a>
					</div>

					<?php if ( empty( $texttango_recipients ) ) : ?>
						<?php
						load_template(
							TEXTTANGO_PATH . 'templates/admin/partials/empty-state.php',
							false,
							array(
								'title' => __( 'Nothing to show for this campaign.', 'texttango' ),
								'lead'  => __( 'Its recipients may have been removed by your retention setting, or by a request to be forgotten.', 'texttango' ),
							)
						);
						?>
					<?php else : ?>
						<div class="tt-overflow-x-auto">
							<table class="tt-table">
								<thead>
									<tr>
										<th class="tt-th tt-pl-0"><?php esc_html_e( 'Number', 'texttango' ); ?></th>
										<th class="tt-th"><?php esc_html_e( 'Code', 'texttango' ); ?></th>
										<th class="tt-th"><?php esc_html_e( 'Status', 'texttango' ); ?></th>
										<th class="tt-th tt-pr-0 tt-text-right"><?php esc_html_e( 'Used', 'texttango' ); ?></th>
									</tr>
								</thead>
								<tbody>
									<?php foreach ( $texttango_recipients as $texttango_who ) : ?>
										<?php
										$texttango_code = (string) ( $texttango_who['coupon'] ?? '' );
										$texttango_sent = PersonalCampaign::SENT === (string) ( $texttango_who['status'] ?? '' );
										?>
										<tr>
											<td class="tt-td tt-whitespace-nowrap tt-pl-0 tt-font-medium tt-text-slate-700">
												<?php echo esc_html( (string) ( $texttango_who['recipient'] ?? '' ) ); ?>
											</td>
											<td class="tt-td tt-whitespace-nowrap">
												<?php if ( '' === $texttango_code ) : ?>
													<span class="tt-td-muted"><?php esc_html_e( 'None issued', 'texttango' ); ?></span>
												<?php else : ?>
													<code class="tt-text-xs"><?php echo esc_html( $texttango_code ); ?></code>
												<?php endif; ?>
											</td>
											<td class="tt-td">
												<span class="tt-badge <?php echo esc_attr( $texttango_sent ? 'tt-badge-ok' : 'tt-badge-error' ); ?>">
													<span class="tt-dot"></span>
													<?php echo esc_html( (string) ( $texttango_who['status'] ?? '' ) ); ?>
												</span>
												<?php if ( '' !== (string) ( $texttango_who['error_reason'] ?? '' ) ) : ?>
													<span class="tt-block tt-text-xs tt-text-slate-500">
														<?php echo esc_html( (string) $texttango_who['error_reason'] ); ?>
													</span>
												<?php endif; ?>
											</td>
											<td class="tt-td tt-whitespace-nowrap tt-pr-0 tt-text-right">
												<?php
												/*
												 * Read off the coupon rather than stored here, so it
												 * cannot go stale: the redemption happens at a
												 * checkout this table never sees.
												 */
												?>
												<?php if ( '' !== $texttango_code && PersonalCampaign::redeemed( $texttango_code ) ) : ?>
													<span class="tt-text-slate-700"><?php esc_html_e( 'Yes', 'texttango' ); ?></span>
												<?php else : ?>
													<span class="tt-td-muted">&mdash;</span>
												<?php endif; ?>
											</td>
										</tr>
									<?php endforeach; ?>
								</tbody>
							</table>
						</div>

						<?php
						if ( $texttango_rec_paging instanceof Paging ) {
							load_template(
								TEXTTANGO_PATH . 'templates/admin/partials/pager.php',
								false,
								array(
									'paging' => $texttango_rec_paging,
									'total'  => (int) ( $args['recipient_total'] ?? 0 ),
									'shown'  => count( $texttango_recipients ),
									'url'    => CampaignsPage::recipients_url( (string) ( $texttango_opened['uuid'] ?? '' ) ),
									'keep'   => array(),
									'arg'    => CampaignsPage::RECIPIENT_PAGE,
								)
							);
						}
						?>
					<?php endif; ?>
				</div>
			<?php endif; ?>

			<!-- History. -->
			<div class="tt-card">
				<h2 class="tt-m-0 tt-mb-4 tt-p-0 tt-text-lg tt-font-semibold tt-text-slate-900">
					<?php esc_html_e( 'Recent campaigns', 'texttango' ); ?>
				</h2>

				<?php if ( empty( $texttango_history ) ) : ?>
					<?php
					/*
					 * The count is of *consent*, not of reach. The reachable figure
					 * needs a suppression check per person, which is the cost kept
					 * off page load everywhere else — and a number here that the
					 * review then contradicts would be the balance bug again.
					 */
					$texttango_consenting = (int) ( $args['consenting_count'] ?? 0 );

					load_template(
						TEXTTANGO_PATH . 'templates/admin/partials/empty-state.php',
						false,
						array(
							'title'  => __( 'No campaigns yet.', 'texttango' ),
							'lead'   => $texttango_consenting > 0
								? sprintf(
									/* translators: %s: number of customers who agreed to marketing. */
									_n(
										'%s customer has agreed to marketing messages. Anything you send appears here with how much of it arrived.',
										'%s customers have agreed to marketing messages. Anything you send appears here with how much of it arrived.',
										$texttango_consenting,
										'texttango'
									),
									number_format_i18n( $texttango_consenting )
								)
								: __( 'Nobody has agreed to marketing messages yet, so there is nobody to send to. Consent is collected at checkout and in the customer account.', 'texttango' ),
							'action' => $texttango_consenting > 0 ? '' : __( 'Set up consent', 'texttango' ),
							'url'    => $texttango_consenting > 0 ? '' : (string) ( $args['consent_url'] ?? '' ),
						)
					);
					?>
				<?php else : ?>
					<div class="tt-overflow-x-auto">
						<table class="tt-table">
							<thead>
								<tr>
									<th class="tt-th tt-pl-0"><?php esc_html_e( 'When', 'texttango' ); ?></th>
									<th class="tt-th"><?php esc_html_e( 'Campaign', 'texttango' ); ?></th>
									<th class="tt-th"><?php esc_html_e( 'Status', 'texttango' ); ?></th>
									<th class="tt-th tt-text-right"><?php esc_html_e( 'Recipients', 'texttango' ); ?></th>
									<th class="tt-th tt-text-right"><?php esc_html_e( 'Delivered', 'texttango' ); ?></th>
									<th class="tt-th tt-pr-0 tt-text-right"></th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( $texttango_history as $texttango_row ) : ?>
									<?php
									$texttango_status  = (string) ( $texttango_row['status'] ?? '' );
									$texttango_running = in_array( $texttango_status, $texttango_flight, true );
									$texttango_total   = (int) ( $texttango_row['accepted'] ?? $texttango_row['recipients'] ?? 0 );

									// A campaign that has not gone yet is asked a different
									// question from one that has: not "how long ago" but
									// "how long until".
									$texttango_goes = 'scheduled' === $texttango_status
										? (int) strtotime( (string) ( $texttango_row['scheduled_at'] ?? '' ) )
										: 0;
									?>
									<tr>
										<td class="tt-td tt-whitespace-nowrap tt-pl-0 tt-td-muted">
											<?php if ( $texttango_goes > 0 ) : ?>
												<span class="tt-text-slate-700">
													<?php
													echo esc_html(
														sprintf(
															/* translators: %s: human-readable time difference, e.g. "5 mins". */
															__( 'in %s', 'texttango' ),
															human_time_diff( time(), $texttango_goes )
														)
													);
													?>
												</span>
												<span class="tt-block"><?php echo esc_html( wp_date( 'j M, H:i', $texttango_goes ) ); ?></span>
											<?php else : ?>
												<?php
												echo esc_html(
													sprintf(
														/* translators: %s: human-readable time difference, e.g. "5 mins". */
														__( '%s ago', 'texttango' ),
														human_time_diff( (int) strtotime( (string) ( $texttango_row['created_at'] ?? '' ) . ' UTC' ) )
													)
												);
												?>
											<?php endif; ?>
										</td>
										<td class="tt-td">
											<span class="tt-font-medium"><?php echo esc_html( (string) ( $texttango_row['name'] ?? '' ) ); ?></span>
											<span class="tt-block tt-text-xs tt-text-slate-500"><?php echo esc_html( wp_trim_words( (string) ( $texttango_row['body'] ?? '' ), 12 ) ); ?></span>
										</td>
										<td class="tt-td">
											<span class="tt-badge <?php echo esc_attr( $texttango_running ? 'tt-badge-warn' : ( 'finished' === $texttango_status ? 'tt-badge-ok' : 'tt-badge-off' ) ); ?>">
												<span class="tt-dot"></span>
												<?php echo esc_html( $texttango_status ); ?>
											</span>
											<?php if ( ! empty( $texttango_row['sandbox'] ) ) : ?>
												<span class="tt-block tt-text-xs tt-text-slate-500"><?php esc_html_e( 'Sandbox', 'texttango' ); ?></span>
											<?php endif; ?>

											<?php
											/*
											 * A personal campaign sends over minutes rather than in
											 * one request, so "processing" on its own says nothing
											 * about whether it is moving or stuck. The counts come
											 * from this site because this site is doing the sending.
											 */
											?>
											<?php if ( CampaignLog::is_personal( $texttango_row ) ) : ?>
												<?php $texttango_progress = PersonalCampaign::progress( (string) ( $texttango_row['uuid'] ?? '' ) ); ?>
												<?php if ( $texttango_progress['total'] > 0 ) : ?>
													<span class="tt-block tt-text-xs tt-text-slate-500">
														<?php
														echo esc_html(
															sprintf(
																/* translators: 1: messages sent, 2: total recipients. */
																__( 'a code each — %1$s of %2$s sent', 'texttango' ),
																number_format_i18n( $texttango_progress['sent'] ),
																number_format_i18n( $texttango_progress['total'] )
															)
														);
														?>
														<?php if ( $texttango_progress['failed'] > 0 ) : ?>
															<span class="tt-text-rose-600">
																<?php
																echo esc_html(
																	sprintf(
																		/* translators: %s: number of recipients that could not be sent to. */
																		__( ', %s could not be sent', 'texttango' ),
																		number_format_i18n( $texttango_progress['failed'] )
																	)
																);
																?>
															</span>
														<?php endif; ?>
													</span>
												<?php endif; ?>
												<?php
												// Only a personal campaign has per-recipient rows to open: a bulk
												// one was fanned out by the platform, which never told this site
												// who it reached.
												?>
												<a
													class="tt-block tt-text-xs"
													href="<?php echo esc_url( CampaignsPage::recipients_url( (string) ( $texttango_row['uuid'] ?? '' ) ) ); ?>"
												>
													<?php esc_html_e( 'Who got which code', 'texttango' ); ?>
												</a>
											<?php endif; ?>
										</td>
										<td class="tt-td tt-whitespace-nowrap tt-text-right">
											<?php echo esc_html( number_format_i18n( $texttango_total ) ); ?>
										</td>
										<td class="tt-td tt-whitespace-nowrap tt-text-right">
											<?php
											if ( isset( $texttango_row['delivered'] ) ) {
												echo esc_html( number_format_i18n( (int) $texttango_row['delivered'] ) );
											} else {
												echo '<span class="tt-text-slate-400">&mdash;</span>';
											}
											?>
										</td>
										<td class="tt-td tt-whitespace-nowrap tt-pr-0 tt-text-right">
											<?php if ( $texttango_running ) : ?>
												<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
													<?php wp_nonce_field( (string) $args['cancel_action'] ); ?>
													<input type="hidden" name="action" value="<?php echo esc_attr( (string) $args['cancel_action'] ); ?>">
													<input type="hidden" name="uuid" value="<?php echo esc_attr( (string) ( $texttango_row['uuid'] ?? '' ) ); ?>">
													<button type="submit" class="tt-btn tt-btn-danger"><?php esc_html_e( 'Stop', 'texttango' ); ?></button>
												</form>
											<?php endif; ?>
										</td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>

					<p class="tt-hint tt-mt-4 tt-mb-0">
						<?php esc_html_e( 'Progress is checked every few minutes. Campaign delivery receipts are not sent to this site, so these figures come from asking TextTango rather than from being told.', 'texttango' ); ?>
					</p>

					<?php
					load_template(
						TEXTTANGO_PATH . 'templates/admin/partials/pager.php',
						false,
						array(
							'paging' => $args['history_paging'] ?? null,
							'total'  => (int) ( $args['history_total'] ?? 0 ),
							'shown'  => count( $texttango_history ),
							'url'    => CampaignsPage::url( CampaignsPage::VIEW_HISTORY ),
							'keep'   => array(),
							'arg'    => CampaignsPage::HISTORY_PAGE,
						)
					);
					?>
				<?php endif; ?>
			</div>

			<?php endif; ?>

		</div>
	</div>
</div>
