<?php
/**
 * Advanced tab — data handling and site-level notes.
 *
 * @package TextTango
 *
 * @var array<string, mixed> $args View data supplied by SettingsPage::render().
 */

declare( strict_types=1 );

defined( 'ABSPATH' ) || exit;

$texttango_settings = (array) ( $args['settings'] ?? array() );
?>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
	<input type="hidden" name="action" value="<?php echo esc_attr( (string) $args['save_action'] ); ?>" />
	<input type="hidden" name="texttango_tab" value="<?php echo esc_attr( (string) $args['tab'] ); ?>" />
	<?php wp_nonce_field( (string) $args['save_nonce'] ); ?>

	<div class="tt-card tt-mb-4">
		<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( 'Data', 'texttango' ); ?>
		</h2>
		<label class="tt-mt-2 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
			<input
				type="checkbox"
				name="keep_data_on_uninstall"
				value="1"
				class="tt-mt-0.5"
				<?php checked( ! empty( $texttango_settings['keep_data_on_uninstall'] ) ); ?> />
			<span>
				<?php esc_html_e( 'Keep settings and the message log if this plugin is uninstalled', 'texttango' ); ?>
				<span class="tt-hint tt-block">
					<?php esc_html_e( 'When unchecked, uninstalling removes the delivery log, settings, and stored credentials.', 'texttango' ); ?>
				</span>
			</span>
		</label>
	</div>

	<div class="tt-card tt-mb-4">
		<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( 'Message log retention', 'texttango' ); ?>
		</h2>
		<p class="tt-mb-4 tt-text-sm tt-text-slate-500">
			<?php esc_html_e( 'The log holds each recipient\'s number and the text sent to them, so it is worth deciding how long to keep it. It is also the record of what was sent and whether it arrived, so nothing is removed unless you set a limit.', 'texttango' ); ?>
		</p>
		<label class="tt-label" for="texttango-retention"><?php esc_html_e( 'Delete log entries older than', 'texttango' ); ?></label>
		<div class="tt-flex tt-items-center tt-gap-2">
			<input class="tt-input tt-max-w-xs" id="texttango-retention" name="log_retention_days" type="number" min="0" max="3650"
				value="<?php echo esc_attr( (string) $texttango_settings['log_retention_days'] ); ?>" />
			<span class="tt-text-sm tt-text-slate-600"><?php esc_html_e( 'days', 'texttango' ); ?></span>
		</div>
		<p class="tt-hint"><?php esc_html_e( 'Zero keeps everything. Old entries are removed once a day.', 'texttango' ); ?></p>

		<label class="tt-label tt-mt-5" for="texttango-audit-retention"><?php esc_html_e( 'Delete audit entries older than', 'texttango' ); ?></label>
		<div class="tt-flex tt-items-center tt-gap-2">
			<input class="tt-input tt-max-w-xs" id="texttango-audit-retention" name="audit_retention_days" type="number" min="0" max="3650"
				value="<?php echo esc_attr( (string) $texttango_settings['audit_retention_days'] ); ?>" />
			<span class="tt-text-sm tt-text-slate-600"><?php esc_html_e( 'days', 'texttango' ); ?></span>
		</div>
		<p class="tt-hint">
			<?php esc_html_e( 'Kept separately, and kept by default. The audit trail holds no message content — it records who changed what, which is normally asked about long after anyone would have thought to keep the evidence.', 'texttango' ); ?>
		</p>
	</div>

	<?php
	$texttango_usage   = (array) ( $args['usage'] ?? array() );
	$texttango_seen    = (string) ( $args['balance_seen'] ?? '' );
	$texttango_circuit = (array) ( $args['circuit'] ?? array() );
	?>
	<div class="tt-card tt-mb-4">
		<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( 'Sending limits', 'texttango' ); ?>
		</h2>
		<p class="tt-mb-4 tt-text-sm tt-text-slate-500">
			<?php esc_html_e( 'A safety net against spending that should not be happening — a hook firing in a loop, an import replaying order statuses, an integration retrying in a circle. Leave at zero for no limit.', 'texttango' ); ?>
		</p>

		<div class="tt-notice tt-notice-warn tt-mb-5">
			<strong><?php esc_html_e( 'Sign-in codes are never held back.', 'texttango' ); ?></strong>
			<?php esc_html_e( 'A limit stops marketing first, then order updates. Codes always send, because a code that does not arrive locks somebody out of their own account. Messages stopped by a limit are skipped and listed in the log — they are not queued for later.', 'texttango' ); ?>
		</div>

		<div class="tt-mb-5 tt-grid tt-grid-cols-1 tt-gap-5 sm:tt-grid-cols-3">
			<div>
				<label class="tt-label" for="texttango-cap-daily"><?php esc_html_e( 'Messages per day', 'texttango' ); ?></label>
				<input class="tt-input" id="texttango-cap-daily" name="spend_cap_daily" type="number" min="0" max="1000000"
					value="<?php echo esc_attr( (string) $texttango_settings['spend_cap_daily'] ); ?>" />
				<?php if ( ! empty( $texttango_usage ) ) : ?>
					<p class="tt-hint">
						<?php
						printf(
							/* translators: %d: messages sent today. */
							esc_html__( '%d sent today.', 'texttango' ),
							(int) $texttango_usage['today']
						);
						?>
					</p>
				<?php endif; ?>
			</div>
			<div>
				<label class="tt-label" for="texttango-cap-monthly"><?php esc_html_e( 'Messages per month', 'texttango' ); ?></label>
				<input class="tt-input" id="texttango-cap-monthly" name="spend_cap_monthly" type="number" min="0" max="1000000"
					value="<?php echo esc_attr( (string) $texttango_settings['spend_cap_monthly'] ); ?>" />
				<?php if ( ! empty( $texttango_usage ) ) : ?>
					<p class="tt-hint">
						<?php
						printf(
							/* translators: %d: messages sent this month. */
							esc_html__( '%d sent this month.', 'texttango' ),
							(int) $texttango_usage['month']
						);
						?>
					</p>
				<?php endif; ?>
			</div>
			<div>
				<label class="tt-label" for="texttango-cap-recipient"><?php esc_html_e( 'Per number, per day', 'texttango' ); ?></label>
				<input class="tt-input" id="texttango-cap-recipient" name="spend_cap_recipient" type="number" min="0" max="1000"
					value="<?php echo esc_attr( (string) $texttango_settings['spend_cap_recipient'] ); ?>" />
				<p class="tt-hint"><?php esc_html_e( 'Catches a loop aimed at one customer.', 'texttango' ); ?></p>
			</div>
		</div>

		<h3 class="tt-m-0 tt-mb-1 tt-mt-6 tt-p-0 tt-text-sm tt-font-semibold tt-text-slate-900">
			<?php esc_html_e( 'Low balance', 'texttango' ); ?>
		</h3>
		<p class="tt-mb-4 tt-text-sm tt-text-slate-500">
			<?php
			if ( '' !== $texttango_seen ) {
				printf(
					/* translators: %s: last seen balance, e.g. "GHS 91.65". */
					esc_html__( 'Checked hourly. Last seen: %s.', 'texttango' ),
					'<strong>' . esc_html( $texttango_seen ) . '</strong>'
				);
			} else {
				esc_html_e( 'Checked hourly. The balance has not been read yet.', 'texttango' );
			}
			?>
		</p>

		<div class="tt-grid tt-grid-cols-1 tt-gap-5 sm:tt-grid-cols-2">
			<div>
				<label class="tt-label" for="texttango-warn-below"><?php esc_html_e( 'Warn me below', 'texttango' ); ?></label>
				<input class="tt-input" id="texttango-warn-below" name="balance_warn_below" type="number" min="0" step="0.01"
					value="<?php echo esc_attr( (string) $texttango_settings['balance_warn_below'] ); ?>" />
				<p class="tt-hint"><?php esc_html_e( 'Shows a notice in the dashboard. Nothing stops sending.', 'texttango' ); ?></p>
			</div>
			<div>
				<label class="tt-label" for="texttango-pause-below"><?php esc_html_e( 'Pause marketing below', 'texttango' ); ?></label>
				<input class="tt-input" id="texttango-pause-below" name="balance_pause_below" type="number" min="0" step="0.01"
					value="<?php echo esc_attr( (string) $texttango_settings['balance_pause_below'] ); ?>" />
				<p class="tt-hint"><?php esc_html_e( 'Keeps what is left for order updates and sign-in codes.', 'texttango' ); ?></p>
			</div>
		</div>

		<h3 class="tt-m-0 tt-mb-1 tt-mt-6 tt-p-0 tt-text-sm tt-font-semibold tt-text-slate-900">
			<?php esc_html_e( 'If a message cannot be delivered', 'texttango' ); ?>
		</h3>
		<label class="tt-mt-2 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
			<input type="checkbox" name="email_fallback_enabled" value="1" class="tt-mt-0.5"
				<?php checked( ! empty( $texttango_settings['email_fallback_enabled'] ) ); ?> />
			<span>
				<?php esc_html_e( 'Email the customer instead', 'texttango' ); ?>
				<span class="tt-hint tt-block">
					<?php esc_html_e( 'Only when the number is genuinely undeliverable — a landline, or a carrier rejection. Never for a message somebody opted out of, never for a sign-in code, and never after a timeout, since the text may have arrived after all.', 'texttango' ); ?>
				</span>
			</span>
		</label>

		<h3 class="tt-m-0 tt-mb-1 tt-mt-6 tt-p-0 tt-text-sm tt-font-semibold tt-text-slate-900">
			<?php esc_html_e( 'If sending stops working', 'texttango' ); ?>
		</h3>
		<label class="tt-mt-2 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
			<input type="checkbox" name="health_alert_enabled" value="1" class="tt-mt-0.5"
				<?php checked( ! empty( $texttango_settings['health_alert_enabled'] ) ); ?> />
			<span>
				<?php esc_html_e( 'Email me', 'texttango' ); ?>
				<span class="tt-hint tt-block">
					<?php esc_html_e( 'Only when nothing can send until somebody acts: the token is refused, the balance has run out, or TextTango cannot be reached at all. A single message failing is normal and is never emailed about. At most one email every six hours per fault.', 'texttango' ); ?>
				</span>
			</span>
		</label>

		<div class="tt-mt-3">
			<label class="tt-label" for="texttango-health-email"><?php esc_html_e( 'Send those to', 'texttango' ); ?></label>
			<input class="tt-input" id="texttango-health-email" name="health_alert_email" type="email"
				placeholder="<?php echo esc_attr( (string) get_option( 'admin_email', '' ) ); ?>"
				value="<?php echo esc_attr( (string) $texttango_settings['health_alert_email'] ); ?>" />
			<p class="tt-hint"><?php esc_html_e( 'Leave blank to use the site admin address.', 'texttango' ); ?></p>
		</div>
	</div>

	<?php if ( ! empty( $texttango_circuit['failures'] ) || ! empty( $texttango_circuit['open_until'] ) ) : ?>
		<div class="tt-card tt-mb-4">
			<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( 'Connection trouble', 'texttango' ); ?>
			</h2>
			<p class="tt-text-sm tt-text-slate-500">
				<?php
				printf(
					/* translators: 1: number of consecutive failures, 2: last error code. */
					esc_html__( '%1$d requests in a row could not reach TextTango. Last error: %2$s. After a few more, sending pauses for a couple of minutes rather than waiting out a timeout on every message.', 'texttango' ),
					(int) $texttango_circuit['failures'],
					'<code>' . esc_html( '' !== (string) $texttango_circuit['last_code'] ? (string) $texttango_circuit['last_code'] : '—' ) . '</code>'
				);
				?>
			</p>
		</div>
	<?php endif; ?>

	<?php
	$texttango_sources = array_filter(
		(array) ( $args['import_sources'] ?? array() ),
		static fn( array $source ): bool => ! empty( $source['present'] )
	);
	?>
	<?php if ( array() !== $texttango_sources ) : ?>
		<div class="tt-card tt-mb-4">
			<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( 'Bring consent over from another plugin', 'texttango' ); ?>
			</h2>
			<p class="tt-mb-4 tt-text-sm tt-text-slate-500">
				<?php esc_html_e( 'Only who agreed comes across. Settings, wording and message history do not — they belong to a different gateway and a different set of merge tags, and a record of sends this site did not make is not a record worth keeping.', 'texttango' ); ?>
			</p>

			<?php foreach ( $texttango_sources as $texttango_slug => $texttango_source ) : ?>
				<div class="tt-mb-3 tt-flex tt-flex-wrap tt-items-center tt-justify-between tt-gap-3 tt-rounded-md tt-bg-slate-50 tt-p-4">
					<div>
						<strong class="tt-text-sm tt-text-slate-900"><?php echo esc_html( (string) $texttango_source['label'] ); ?></strong>
						<span class="tt-hint tt-block">
							<?php
							printf(
								/* translators: %s: number of confirmed subscribers found. */
								esc_html( _n( '%s confirmed subscriber found.', '%s confirmed subscribers found.', (int) $texttango_source['rows'], 'texttango' ) ),
								esc_html( number_format_i18n( (int) $texttango_source['rows'] ) )
							);
							?>
						</span>
					</div>
					<button
						type="button"
						class="tt-btn tt-btn-secondary"
						data-texttango-action="import-consent"
						data-texttango-source="<?php echo esc_attr( (string) $texttango_slug ); ?>"
					><?php esc_html_e( 'Import consent', 'texttango' ); ?></button>
				</div>
			<?php endforeach; ?>

			<p class="tt-hint tt-m-0" data-texttango-import-result aria-live="polite">
				<?php esc_html_e( 'Anyone still waiting to confirm is skipped, and so is anyone on your opt-out list. Each import is recorded in the audit trail with the plugin it came from.', 'texttango' ); ?>
			</p>
		</div>
	<?php endif; ?>

	<div class="tt-card tt-mb-4">
		<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( 'Move this configuration', 'texttango' ); ?>
		</h2>
		<p class="tt-mb-4 tt-text-sm tt-text-slate-500">
			<?php esc_html_e( 'Carry the events, wording, consent rules and limits to another site. Credentials are not included — they are not settings, and a file that held one would end up emailed around or committed to a repository.', 'texttango' ); ?>
		</p>

		<div class="tt-notice tt-notice-warn tt-mb-4">
			<strong><?php esc_html_e( 'Sandbox never travels.', 'texttango' ); ?></strong>
			<?php esc_html_e( 'It belongs to the environment, not the configuration. Carrying it from production into a staging clone would switch sandbox off there — and that clone still holds a copy of your real customer list.', 'texttango' ); ?>
		</div>

		<label class="tt-label" for="texttango-import"><?php esc_html_e( 'Paste a settings file to import', 'texttango' ); ?></label>
		<textarea class="tt-input tt-font-mono tt-text-xs" id="texttango-import" name="texttango_import" rows="4"
			placeholder="<?php esc_attr_e( '{ "format": 1, "settings": { … } }', 'texttango' ); ?>"></textarea>
		<p class="tt-hint">
			<?php esc_html_e( 'Applied when you save. This can switch notifications on, so read what you are pasting — the audit trail records exactly what changed.', 'texttango' ); ?>
		</p>
	</div>

	<div class="tt-card tt-mb-4">
		<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( 'Encryption', 'texttango' ); ?>
		</h2>
		<?php if ( ! empty( $args['derived_key'] ) ) : ?>
			<p class="tt-text-sm tt-text-slate-500">
				<?php esc_html_e( 'Credentials are encrypted with a key derived from this site\'s security salts. Rotating those salts will make them unreadable and you will need to paste them again.', 'texttango' ); ?>
			</p>
			<p class="tt-hint">
				<?php esc_html_e( 'Define TEXTTANGO_ENCRYPTION_KEY in wp-config.php — a base64-encoded 32-byte value — to use a dedicated key that survives a salt rotation.', 'texttango' ); ?>
			</p>
		<?php else : ?>
			<p class="tt-text-sm tt-text-slate-500">
				<?php esc_html_e( 'Credentials are encrypted with the dedicated TEXTTANGO_ENCRYPTION_KEY defined in wp-config.php, so rotating this site\'s security salts will not affect them.', 'texttango' ); ?>
			</p>
		<?php endif; ?>
	</div>

	<div class="tt-flex tt-flex-wrap tt-items-center tt-gap-3">
		<button type="submit" class="tt-btn tt-btn-primary">
			<?php esc_html_e( 'Save settings', 'texttango' ); ?>
		</button>
		<?php
		/*
		 * The export posts to its own `action`, so it cannot share this form —
		 * and a second <form> is a block, which is what used to stack the two
		 * buttons on top of each other. The `form` attribute lets the button sit
		 * in this row while still submitting the form below, which is why that
		 * one is empty and lives after </form> rather than nested inside it.
		 */
		?>
		<button type="submit" class="tt-btn tt-btn-secondary" form="texttango-export-settings">
			<?php esc_html_e( 'Download settings as JSON', 'texttango' ); ?>
		</button>
	</div>
</form>

<form id="texttango-export-settings" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
	<input type="hidden" name="action" value="<?php echo esc_attr( (string) $args['export_action'] ); ?>" />
	<?php wp_nonce_field( (string) $args['export_nonce'] ); ?>
</form>
