<?php
/**
 * Consent tab — opt-in capture and the opt-out list.
 *
 * @package TextTango
 *
 * @var array<string, mixed> $args View data supplied by SettingsPage::render().
 */

declare( strict_types=1 );

defined( 'ABSPATH' ) || exit;

use TextTango\Admin\SettingsPage;
use TextTango\Admin\Tabs;
use TextTango\Api\PhoneNumber;
use TextTango\Support\Paging;

$texttango_settings   = (array) ( $args['settings'] ?? array() );
$texttango_suppressed = (array) ( $args['suppressions'] ?? array() );
$texttango_total      = (int) ( $args['suppression_count'] ?? 0 );
$texttango_consented  = (array) ( $args['consent_list'] ?? array() );
$texttango_consents   = (int) ( $args['consent_list_count'] ?? 0 );

$texttango_sup_paging = $args['suppressed_paging'] ?? null;
$texttango_con_paging = $args['consent_paging'] ?? null;

/*
 * Two tables on one screen, so each pager has to carry the other's page or
 * turning to page two of the opt-out list would silently send the consent list
 * back to page one.
 */
$texttango_keep_con = $texttango_con_paging instanceof Paging
	? $texttango_con_paging->query_args( null, SettingsPage::CONSENT_PAGE )
	: array();
$texttango_keep_sup = $texttango_sup_paging instanceof Paging
	? $texttango_sup_paging->query_args( null, SettingsPage::SUPPRESSED_PAGE )
	: 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( 'Marketing consent', 'texttango' ); ?>
		</h2>
		<p class="tt-mb-5 tt-text-sm tt-text-slate-500">
			<?php esc_html_e( 'Order updates are service messages about a purchase the customer chose to make, and send either way. This consent governs marketing only.', 'texttango' ); ?>
		</p>

		<label class="tt-mb-4 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
			<input type="checkbox" name="consent_checkout_enabled" value="1" class="tt-mt-0.5"
				<?php checked( ! empty( $texttango_settings['consent_checkout_enabled'] ) ); ?> />
			<span>
				<?php esc_html_e( 'Ask for consent at checkout', 'texttango' ); ?>
				<span class="tt-hint tt-block">
					<?php esc_html_e( 'Adds an unticked checkbox to the contact step. Recorded against the order as well as the account, so a guest checkout still leaves a record.', 'texttango' ); ?>
				</span>
			</span>
		</label>

		<div class="tt-mb-2">
			<label class="tt-label" for="texttango-consent-label"><?php esc_html_e( 'Checkbox wording', 'texttango' ); ?></label>
			<input
				class="tt-input"
				id="texttango-consent-label"
				name="consent_checkout_label"
				type="text"
				placeholder="<?php echo esc_attr( (string) $args['consent_default_label'] ); ?>"
				value="<?php echo esc_attr( (string) $texttango_settings['consent_checkout_label'] ); ?>" />
			<p class="tt-hint">
				<?php esc_html_e( 'Shown at checkout and in the customer\'s account. Leave blank for the default. Wording is the merchant\'s responsibility.', 'texttango' ); ?>
			</p>
		</div>
	</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( 'Confirm the number', 'texttango' ); ?>
		</h2>
		<p class="tt-mb-5 tt-text-sm tt-text-slate-500">
			<?php esc_html_e( 'A tick in a box says the person filling in the form wants messages. It does not say they hold the number they typed. With this on, agreeing sends one message to that number and the consent stays pending until somebody answers from the handset.', 'texttango' ); ?>
		</p>

		<label class="tt-mb-4 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
			<input type="checkbox" name="consent_double_optin" value="1" class="tt-mt-0.5"
				<?php checked( ! empty( $texttango_settings['consent_double_optin'] ) ); ?> />
			<span>
				<?php esc_html_e( 'Ask the number to confirm before marketing to it', 'texttango' ); ?>
				<span class="tt-hint tt-block">
					<?php esc_html_e( 'Consent already on record is left alone. Only preferences given from now on are asked to confirm.', 'texttango' ); ?>
				</span>
			</span>
		</label>

		<label class="tt-label" for="texttango-confirm-tpl"><?php esc_html_e( 'Confirmation message', 'texttango' ); ?></label>
		<textarea
			class="tt-input tt-font-mono tt-text-xs"
			id="texttango-confirm-tpl"
			name="consent_confirm_template"
			rows="2"
			placeholder="<?php echo esc_attr( (string) $args['consent_default_tpl'] ); ?>"><?php echo esc_textarea( (string) $texttango_settings['consent_confirm_template'] ); ?></textarea>
		<p class="tt-hint">
			<?php
			printf(
				/* translators: 1: the confirm_link merge tag, 2: the store_name merge tag. */
				esc_html__( 'Leave blank for the default. %1$s is required — without it there is no way to confirm. %2$s is also available. Keep it short: the link alone is most of one message.', 'texttango' ),
				'<code>{confirm_link}</code>',
				'<code>{store_name}</code>'
			);
			?>
		</p>

		<div class="tt-notice tt-notice-warn tt-mt-4">
			<strong><?php esc_html_e( 'The confirmation itself costs a message.', 'texttango' ); ?></strong>
			<?php esc_html_e( 'It is sent to every customer who agrees, whether or not they go on to confirm, and it is charged like any other. Nobody is marketed to and no details leave this site until they do confirm.', 'texttango' ); ?>
		</div>
	</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( 'Contact sync', 'texttango' ); ?>
		</h2>
		<p class="tt-mb-5 tt-text-sm tt-text-slate-500">
			<?php esc_html_e( 'Adds customers who agree to marketing into a TextTango contact group, ready for campaigns. Nobody else leaves this site — declining keeps their details here, and withdrawing removes them from the group.', 'texttango' ); ?>
		</p>

		<label class="tt-mb-4 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
			<input type="checkbox" name="contacts_sync_enabled" value="1" class="tt-mt-0.5"
				<?php checked( ! empty( $texttango_settings['contacts_sync_enabled'] ) ); ?> />
			<span><?php esc_html_e( 'Sync opted-in customers to TextTango', 'texttango' ); ?></span>
		</label>

		<label class="tt-label" for="texttango-contact-group"><?php esc_html_e( 'Contact group', 'texttango' ); ?></label>
		<div class="tt-flex tt-gap-2">
			<input
				class="tt-input"
				id="texttango-contact-group"
				name="contacts_group_id"
				type="text"
				list="texttango-contact-groups"
				placeholder="<?php esc_attr_e( 'Group UUID', 'texttango' ); ?>"
				value="<?php echo esc_attr( (string) $texttango_settings['contacts_group_id'] ); ?>" />
			<datalist id="texttango-contact-groups"></datalist>
			<button type="button" class="tt-btn tt-btn-secondary tt-shrink-0" data-texttango-action="load-groups">
				<?php esc_html_e( 'Load', 'texttango' ); ?>
			</button>
		</div>
		<p class="tt-hint">
			<?php esc_html_e( 'Load pulls the groups from your account. Syncing does nothing until a group is chosen.', 'texttango' ); ?>
		</p>
		<p class="tt-text-sm tt-mt-2" data-texttango-result aria-live="polite"></p>

		<?php $texttango_sweep = (array) ( $args['reconcile_report'] ?? array() ); ?>
		<p class="tt-hint tt-mt-4">
			<?php if ( empty( $texttango_sweep['at'] ) ) : ?>
				<?php esc_html_e( 'A nightly sweep adds anyone who agreed but was missed, and removes anyone who withdrew but was not taken off. It has not run yet.', 'texttango' ); ?>
			<?php else : ?>
				<?php
				printf(
					/* translators: 1: how long ago, 2: number added, 3: number removed. */
					esc_html__( 'Nightly sweep ran %1$s ago: %2$d added, %3$d removed.', 'texttango' ),
					esc_html( human_time_diff( (int) $texttango_sweep['at'] ) ),
					(int) ( $texttango_sweep['pushed'] ?? 0 ),
					(int) ( $texttango_sweep['removed'] ?? 0 )
				);
				?>
				<?php if ( ! empty( $texttango_sweep['failed'] ) ) : ?>
					<?php
					printf(
						/* translators: %d: number that could not be added. */
						esc_html__( ' %d could not be added and will be tried again.', 'texttango' ),
						(int) $texttango_sweep['failed']
					);
					?>
				<?php endif; ?>
				<?php if ( ! empty( $texttango_sweep['truncated'] ) ) : ?>
					<?php esc_html_e( ' More were waiting than one run handles; the rest go tonight.', 'texttango' ); ?>
				<?php endif; ?>
			<?php endif; ?>
		</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( 'Quiet hours', 'texttango' ); ?>
		</h2>
		<p class="tt-mb-5 tt-text-sm tt-text-slate-500">
			<?php esc_html_e( 'Messages caught by the window are held and delivered when it opens, not dropped. Codes are never held — somebody is waiting on the screen for them.', 'texttango' ); ?>
		</p>

		<label class="tt-mb-4 tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
			<input type="checkbox" name="quiet_hours_enabled" value="1" class="tt-mt-0.5"
				<?php checked( ! empty( $texttango_settings['quiet_hours_enabled'] ) ); ?> />
			<span><?php esc_html_e( 'Hold messages overnight', 'texttango' ); ?></span>
		</label>

		<div class="tt-mb-4 tt-grid tt-grid-cols-1 tt-gap-5 sm:tt-grid-cols-2">
			<div>
				<label class="tt-label" for="texttango-quiet-start"><?php esc_html_e( 'Quiet from', 'texttango' ); ?></label>
				<input class="tt-input" id="texttango-quiet-start" name="quiet_hours_start" type="time"
					value="<?php echo esc_attr( (string) $texttango_settings['quiet_hours_start'] ); ?>" />
			</div>
			<div>
				<label class="tt-label" for="texttango-quiet-end"><?php esc_html_e( 'Until', 'texttango' ); ?></label>
				<input class="tt-input" id="texttango-quiet-end" name="quiet_hours_end" type="time"
					value="<?php echo esc_attr( (string) $texttango_settings['quiet_hours_end'] ); ?>" />
			</div>
		</div>

		<p class="tt-hint tt-mb-4">
			<?php
			printf(
				/* translators: %s: the site timezone, e.g. Africa/Accra. */
				esc_html__( 'Times are in the site timezone, %s.', 'texttango' ),
				'<code>' . esc_html( (string) $args['site_timezone'] ) . '</code>'
			);
			?>
		</p>

		<label class="tt-flex tt-items-start tt-gap-2 tt-text-sm tt-text-slate-700">
			<input type="checkbox" name="quiet_hours_include_transactional" value="1" class="tt-mt-0.5"
				<?php checked( ! empty( $texttango_settings['quiet_hours_include_transactional'] ) ); ?> />
			<span>
				<?php esc_html_e( 'Hold order updates too', 'texttango' ); ?>
				<span class="tt-hint tt-block">
					<?php esc_html_e( 'Off by default. A dispatch notice is usually more use promptly than politely.', 'texttango' ); ?>
				</span>
			</span>
		</label>
	</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>
	</div>
</form>

<?php if ( $texttango_consents > 0 ) : ?>
	<!-- The mirror of the opt-out list below, and it exists for the same reason:
		a number can agree without an account behind it. Read-only, like that
		one — these are records the plugin was given, not settings. -->
	<div class="tt-card tt-mb-4 tt-mt-6">
		<h2 class="tt-m-0 tt-mb-1 tt-p-0 tt-text-lg tt-font-semibold tt-text-slate-900">
			<?php
			printf(
				/* translators: %d: number of consenting numbers. */
				esc_html__( 'Agreed, with no account (%d)', 'texttango' ),
				(int) $texttango_consents
			);
			?>
		</h2>
		<p class="tt-mb-4 tt-text-sm tt-text-slate-500">
			<?php esc_html_e( 'Numbers that agreed somewhere this site cannot see — brought over from another plugin\'s subscriber list. They receive campaigns like any consenting customer, and your opt-out list still applies to them.', 'texttango' ); ?>
		</p>

		<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( 'Came from', 'texttango' ); ?></th>
						<th class="tt-th tt-pr-0 tt-text-right"><?php esc_html_e( 'Added', 'texttango' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $texttango_consented as $texttango_row ) : ?>
						<tr>
							<td class="tt-td tt-whitespace-nowrap tt-pl-0 tt-font-mono">
								<?php echo esc_html( PhoneNumber::mask( (string) $texttango_row['recipient'] ) ); ?>
							</td>
							<td class="tt-td tt-td-muted">
								<?php echo esc_html( (string) $texttango_row['source'] ); ?>
							</td>
							<td class="tt-td tt-whitespace-nowrap tt-pr-0 tt-text-right tt-td-muted">
								<?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' ) )
									)
								);
								?>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>

		<?php
		load_template(
			TEXTTANGO_PATH . 'templates/admin/partials/pager.php',
			false,
			array(
				/*
				 * The consent list's own pager. This and the opt-out list's below
				 * had their contents swapped: each was paging the other's table,
				 * counting the other's rows and writing the other's page argument.
				 * The half that referenced `$texttango_rows` — a variable this file
				 * never had — turned that into a fatal the moment the section had
				 * anything to show, which is why an empty consent list hid it.
				 *
				 * `keep` carries the *other* table's page, per the note above.
				 */
				'paging' => $texttango_con_paging,
				'total'  => $texttango_consents,
				'shown'  => count( $texttango_consented ),
				'url'    => Tabs::url( Tabs::CONSENT ),
				'keep'   => $texttango_keep_sup,
				'arg'    => SettingsPage::CONSENT_PAGE,
			)
		);
		?>
	</div>
<?php endif; ?>

<div class="tt-card tt-mb-4 tt-mt-6">
	<h2 class="tt-m-0 tt-mb-1 tt-p-0 tt-text-lg tt-font-semibold tt-text-slate-900">
		<?php
		printf(
			/* translators: %d: number of suppressed numbers. */
			esc_html__( 'Opted out (%d)', 'texttango' ),
			(int) $texttango_total
		);
		?>
	</h2>
	<p class="tt-mb-4 tt-text-sm tt-text-slate-500">
		<?php esc_html_e( 'Numbers TextTango is refusing. Nothing is sent to these, order updates included.', 'texttango' ); ?>
	</p>

	<div class="tt-notice tt-notice-warn tt-mb-4">
		<strong><?php esc_html_e( 'Opt-outs are discovered, not announced.', 'texttango' ); ?></strong>
		<?php esc_html_e( 'TextTango does not deliver inbound SMS to this site, so a STOP text cannot reach it. A number is added here the first time a send is refused — meaning one message is attempted, and charged, before the opt-out is known. After that it is skipped locally with no further attempts.', 'texttango' ); ?>
	</div>

	<?php if ( empty( $texttango_suppressed ) ) : ?>
		<?php
		load_template(
			TEXTTANGO_PATH . 'templates/admin/partials/empty-state.php',
			false,
			array(
				'title' => __( 'Nobody has opted out.', 'texttango' ),
				'lead'  => __( 'Numbers appear here on their own, the first time TextTango refuses one. You do not have to add them, and nothing is ever sent to a number on this list again.', '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( 'Reason', 'texttango' ); ?></th>
						<th class="tt-th"><?php esc_html_e( 'Learned from', 'texttango' ); ?></th>
						<th class="tt-th tt-pr-0"><?php esc_html_e( 'When', 'texttango' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $texttango_suppressed as $texttango_row ) : ?>
						<tr>
							<td class="tt-td tt-whitespace-nowrap tt-pl-0 tt-font-mono">
								<?php echo esc_html( PhoneNumber::mask( (string) $texttango_row['recipient'] ) ); ?>
							</td>
							<td class="tt-td"><?php echo esc_html( (string) $texttango_row['reason'] ); ?></td>
							<td class="tt-td tt-td-muted"><?php echo esc_html( (string) $texttango_row['source'] ); ?></td>
							<td class="tt-td tt-whitespace-nowrap tt-pr-0 tt-td-muted"><?php echo esc_html( (string) $texttango_row['created_at'] ); ?></td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>

		<?php
		load_template(
			TEXTTANGO_PATH . 'templates/admin/partials/pager.php',
			false,
			array(
				// The opt-out list's own pager. See the note on the consent list's.
				'paging' => $texttango_sup_paging,
				'total'  => $texttango_total,
				'shown'  => count( $texttango_suppressed ),
				'url'    => Tabs::url( Tabs::CONSENT ),
				'keep'   => $texttango_keep_con,
				'arg'    => SettingsPage::SUPPRESSED_PAGE,
			)
		);
		?>

		<p class="tt-hint tt-mt-3">
			<?php esc_html_e( 'These mirror refusals from the platform and cannot be cleared here. A customer has to opt back in with TextTango.', 'texttango' ); ?>
		</p>
	<?php endif; ?>
</div>
