<?php
/**
 * Logs tab — the delivery log.
 *
 * @package TextTango
 *
 * @var array<string, mixed> $args View data supplied by SettingsPage::render().
 */

declare( strict_types=1 );

defined( 'ABSPATH' ) || exit;

use TextTango\Admin\AnalyticsPage;
use TextTango\Admin\CampaignsPage;
use TextTango\Admin\Menu;
use TextTango\Admin\SettingsPage;
use TextTango\Admin\Tabs;
use TextTango\Api\PhoneNumber;
use TextTango\Messages\LogFilter;
use TextTango\Messages\Resend;

$texttango_rows     = (array) ( $args['log_rows'] ?? array() );
$texttango_statuses = (array) ( $args['log_statuses'] ?? array() );
$texttango_filter   = $args['log_filter'] ?? null;
$texttango_events   = (array) ( $args['log_events'] ?? array() );
$texttango_total    = (int) ( $args['log_total'] ?? 0 );
$texttango_pages    = (int) ( $args['log_pages'] ?? 1 );
$texttango_filtered = $texttango_filter instanceof LogFilter && $texttango_filter->is_active();

/*
 * The audit pager carries the message log's filter and page, or turning to
 * page two of the audit trail would quietly clear the filter above it.
 */
$texttango_keep_log = $texttango_filter instanceof LogFilter ? $texttango_filter->filter_args() : array();
?>
<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 esc_html_e( 'Message log', 'texttango' ); ?>
			</h2>
			<p class="tt-m-0 tt-text-sm tt-text-slate-500">
				<?php esc_html_e( 'Every message this site has sent. Delivery status arrives by webhook; anything still waiting is chased automatically every 15 minutes.', 'texttango' ); ?>
			</p>
			<?php
			/*
			 * The summary used to sit above this table and now has a screen of its
			 * own. This link is what is left of it: somebody who came here to count
			 * rather than to read a particular message still finds the counting.
			 */
			?>
			<p class="tt-mt-1 tt-mb-0 tt-text-sm tt-text-slate-500">
				<?php
				/*
				 * Said rather than left to be noticed. A campaign goes to the platform
				 * as one bulk request and is fanned out there, so no per-recipient row
				 * is ever written here — and somebody who has just sent one and cannot
				 * find it in this table will otherwise conclude the send failed.
				 */
				esc_html_e( 'Campaigns are sent in bulk and have no rows here.', 'texttango' );
				?>
				<a href="<?php echo esc_url( AnalyticsPage::url() ); ?>">
					<?php esc_html_e( 'View analytics', 'texttango' ); ?>
				</a>
				<span class="tt-text-slate-400">&middot;</span>
				<a href="<?php echo esc_url( CampaignsPage::url( CampaignsPage::VIEW_HISTORY ) ); ?>">
					<?php esc_html_e( 'Campaign history', 'texttango' ); ?>
				</a>
			</p>
		</div>
		<button type="button" class="tt-btn tt-btn-secondary tt-shrink-0" data-texttango-action="resync-pending">
			<?php esc_html_e( 'Resync pending', 'texttango' ); ?>
		</button>
	</div>

	<p class="tt-text-sm tt-mb-4" data-texttango-resync-result aria-live="polite"></p>

	<?php if ( $texttango_filter instanceof LogFilter ) : ?>
		<?php
		/*
		 * A GET form, like the tabs already are: a filtered log can be linked to
		 * a colleague, the back button behaves, and a read needs no nonce.
		 */
		?>
		<form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" class="tt-mb-4 tt-flex tt-flex-wrap tt-items-end tt-gap-3">
			<input type="hidden" name="page" value="<?php echo esc_attr( Menu::SETTINGS_SLUG ); ?>" />
			<input type="hidden" name="tab" value="<?php echo esc_attr( Tabs::LOGS ); ?>" />

			<div class="tt-w-44">
				<label class="tt-label" for="texttango-log-status"><?php esc_html_e( 'Status', 'texttango' ); ?></label>
				<select class="tt-input" id="texttango-log-status" name="log_status">
					<option value=""><?php esc_html_e( 'Any status', 'texttango' ); ?></option>
					<?php foreach ( $texttango_statuses as $texttango_key => $texttango_meta ) : ?>
						<option value="<?php echo esc_attr( (string) $texttango_key ); ?>" <?php selected( $texttango_filter->status(), (string) $texttango_key ); ?>>
							<?php echo esc_html( (string) $texttango_meta['label'] ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</div>

			<div class="tt-w-52">
				<label class="tt-label" for="texttango-log-event"><?php esc_html_e( 'Event', 'texttango' ); ?></label>
				<select class="tt-input" id="texttango-log-event" name="log_event">
					<option value=""><?php esc_html_e( 'Any event', 'texttango' ); ?></option>
					<?php foreach ( $texttango_events as $texttango_event ) : ?>
						<option value="<?php echo esc_attr( (string) $texttango_event ); ?>" <?php selected( $texttango_filter->event(), (string) $texttango_event ); ?>>
							<?php echo esc_html( (string) $texttango_event ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</div>

			<div class="tt-w-64">
				<label class="tt-label" for="texttango-log-search"><?php esc_html_e( 'Number', 'texttango' ); ?></label>
				<input
					class="tt-input"
					id="texttango-log-search"
					type="search"
					name="log_search"
					value="<?php echo esc_attr( $texttango_filter->search() ); ?>"
					placeholder="<?php esc_attr_e( 'Full number or last digits', 'texttango' ); ?>"
				/>
			</div>

			<button type="submit" class="tt-btn tt-btn-secondary"><?php esc_html_e( 'Filter', 'texttango' ); ?></button>

			<?php if ( $texttango_filtered ) : ?>
				<a class="tt-text-sm tt-text-slate-500" href="<?php echo esc_url( Tabs::url( Tabs::LOGS ) ); ?>">
					<?php esc_html_e( 'Clear', 'texttango' ); ?>
				</a>
			<?php endif; ?>
		</form>
	<?php endif; ?>

	<?php if ( empty( $texttango_rows ) && $texttango_filtered ) : ?>
		<?php
		/*
		 * Distinguished from "nothing sent yet" deliberately. An empty table
		 * means the opposite thing in each case, and reading the first as the
		 * second sends somebody looking for a bug in their own site.
		 */
		load_template(
			TEXTTANGO_PATH . 'templates/admin/partials/empty-state.php',
			false,
			array(
				'title'  => __( 'No messages match these filters.', 'texttango' ),
				'lead'   => __( 'Nothing in the log has all of the things you asked for. Widening one of them, or searching only the last four digits of the number, usually finds it.', 'texttango' ),
				'action' => __( 'Clear the filters', 'texttango' ),
				'url'    => Tabs::url( Tabs::LOGS ),
			)
		);
		?>
	<?php elseif ( empty( $texttango_rows ) ) : ?>
		<?php
		load_template(
			TEXTTANGO_PATH . 'templates/admin/partials/empty-state.php',
			false,
			array(
				'title'  => __( 'Nothing sent yet.', 'texttango' ),
				'lead'   => __( 'Every message this site sends is recorded here with what it cost, whether it arrived, and the reason if it did not. A test message is the quickest way to see one.', 'texttango' ),
				'action' => __( 'Send a test message', 'texttango' ),
				'url'    => Tabs::url( Tabs::TESTING ),
			)
		);
		?>
	<?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( 'Event', 'texttango' ); ?></th>
						<th class="tt-th"><?php esc_html_e( 'To', 'texttango' ); ?></th>
						<th class="tt-th"><?php esc_html_e( 'Status', 'texttango' ); ?></th>
						<th class="tt-th"><?php esc_html_e( 'Order', 'texttango' ); ?></th>
						<th class="tt-th tt-text-right"><?php esc_html_e( 'Cost', 'texttango' ); ?></th>
						<th class="tt-th tt-pr-0 tt-text-right"><span class="screen-reader-text"><?php esc_html_e( 'Actions', 'texttango' ); ?></span></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $texttango_rows as $texttango_row ) : ?>
						<?php
						$texttango_status = (string) $texttango_row['status'];
						$texttango_meta   = $texttango_statuses[ $texttango_status ] ?? array(
							'label' => $texttango_status,
							'badge' => 'tt-badge-off',
						);
						$texttango_order  = (int) ( $texttango_row['order_id'] ?? 0 );
						?>
						<tr>
							<td class="tt-td tt-whitespace-nowrap tt-pl-0 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>
							<td class="tt-td">
								<?php echo esc_html( (string) $texttango_row['event'] ); ?>
							</td>
							<td class="tt-td tt-whitespace-nowrap tt-font-mono">
								<?php echo esc_html( PhoneNumber::mask( (string) $texttango_row['recipient'] ) ); ?>
							</td>
							<td class="tt-td">
								<span class="tt-badge <?php echo esc_attr( (string) $texttango_meta['badge'] ); ?>">
									<?php echo esc_html( (string) $texttango_meta['label'] ); ?>
								</span>
								<?php if ( ! empty( $texttango_row['error_reason'] ) ) : ?>
									<span class="tt-hint tt-block tt-max-w-xs">
										<?php echo esc_html( (string) $texttango_row['error_reason'] ); ?>
									</span>
								<?php endif; ?>
							</td>
							<td class="tt-td">
								<?php if ( $texttango_order > 0 ) : ?>
									<a class="tt-text-brand-600" href="<?php echo esc_url( admin_url( 'post.php?post=' . $texttango_order . '&action=edit' ) ); ?>">
										#<?php echo esc_html( (string) $texttango_order ); ?>
									</a>
								<?php else : ?>
									<span class="tt-text-slate-400">&mdash;</span>
								<?php endif; ?>
							</td>
							<td class="tt-td tt-whitespace-nowrap tt-text-right">
								<?php
								echo null !== $texttango_row['cost']
									? esc_html( number_format_i18n( (float) $texttango_row['cost'], 4 ) )
									: '<span class="tt-text-slate-400">&mdash;</span>';
								?>
							</td>
							<td class="tt-td tt-whitespace-nowrap tt-pr-0 tt-text-right">
								<?php if ( Resend::is_offered( $texttango_row ) ) : ?>
									<button
										type="button"
										class="tt-cursor-pointer tt-border-0 tt-bg-transparent tt-p-0 tt-text-xs tt-font-medium tt-text-brand-600 tt-underline"
										data-texttango-action="resend-message"
										data-texttango-id="<?php echo esc_attr( (string) $texttango_row['id'] ); ?>"
									><?php esc_html_e( 'Send again', 'texttango' ); ?></button>
								<?php endif; ?>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>

		<?php
		load_template(
			TEXTTANGO_PATH . 'templates/admin/partials/pager.php',
			false,
			array(
				'paging' => $texttango_filter instanceof LogFilter ? $texttango_filter->paging() : null,
				'total'  => $texttango_total,
				'shown'  => count( $texttango_rows ),
				'url'    => Tabs::url( Tabs::LOGS ),
				'keep'   => $texttango_keep_log,
				'arg'    => 'log_page',
			)
		);
		?>
	<?php endif; ?>
</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( 'Delivery receipts', 'texttango' ); ?>
	</h2>
	<p class="tt-mb-4 tt-text-sm tt-text-slate-500">
		<?php esc_html_e( 'Set this as the token\'s single_sms_callback_url in the TextTango dashboard. Requests are rejected unless they carry a valid signature, so the webhook signing secret on the Connection tab must match.', 'texttango' ); ?>
	</p>
	<input
		class="tt-input tt-font-mono tt-text-xs"
		type="text"
		readonly
		onfocus="this.select()"
		value="<?php echo esc_attr( (string) $args['webhook_url'] ); ?>" />

	<?php if ( empty( $args['has_webhook'] ) ) : ?>
		<div class="tt-notice tt-notice-warn tt-mt-4">
			<?php esc_html_e( 'No webhook signing secret is saved, so every inbound receipt is being rejected. Add it on the Connection tab.', 'texttango' ); ?>
		</div>
	<?php endif; ?>
</div>

<?php $texttango_audit = (array) ( $args['audit_rows'] ?? 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( 'Audit trail', 'texttango' ); ?>
	</h2>
	<p class="tt-mb-4 tt-text-sm tt-text-slate-500">
		<?php esc_html_e( 'Who changed what, and when. Credentials are recorded as having changed, never as their value.', 'texttango' ); ?>
	</p>

	<?php if ( empty( $texttango_audit ) ) : ?>
		<?php
		load_template(
			TEXTTANGO_PATH . 'templates/admin/partials/empty-state.php',
			false,
			array(
				'title' => __( 'Nothing recorded yet.', 'texttango' ),
				'lead'  => __( 'Changes to settings, credentials, consent and campaigns are recorded here with who made them. Nothing you have done yet was worth recording.', '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( 'When', 'texttango' ); ?></th>
						<th class="tt-th"><?php esc_html_e( 'Who', 'texttango' ); ?></th>
						<th class="tt-th"><?php esc_html_e( 'What', 'texttango' ); ?></th>
						<th class="tt-th tt-pr-0"><?php esc_html_e( 'Detail', 'texttango' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $texttango_audit as $texttango_entry ) : ?>
						<tr>
							<td class="tt-td tt-whitespace-nowrap tt-pl-0 tt-td-muted">
								<?php echo esc_html( (string) $texttango_entry['created_at'] ); ?>
							</td>
							<td class="tt-td tt-whitespace-nowrap">
								<?php echo esc_html( (string) $texttango_entry['actor_name'] ); ?>
							</td>
							<td class="tt-td">
								<span class="tt-font-medium"><?php echo esc_html( TextTango\Audit\AuditLog::label( (string) $texttango_entry['action'] ) ); ?></span>
								<span class="tt-block tt-text-slate-500"><?php echo esc_html( (string) $texttango_entry['subject'] ); ?></span>
							</td>
							<td class="tt-td tt-pr-0 tt-font-mono tt-td-muted">
								<?php echo esc_html( TextTango\Audit\AuditLog::describe( (string) $texttango_entry['detail'] ) ); ?>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>

		<?php
		load_template(
			TEXTTANGO_PATH . 'templates/admin/partials/pager.php',
			false,
			array(
				'paging' => $args['audit_paging'] ?? null,
				'total'  => (int) ( $args['audit_total'] ?? 0 ),
				'shown'  => count( $texttango_audit ),
				'url'    => Tabs::url( Tabs::LOGS ),
				'keep'   => $texttango_keep_log,
				'arg'    => SettingsPage::AUDIT_PAGE,
			)
		);
		?>
	<?php endif; ?>
</div>
