<?php
/**
 * Admin view: diagnostics, archiving and data reset.
 *
 * @package BitForgeNet_Guest_Tickets
 */

defined( 'ABSPATH' ) || exit;

// This file is a template: it is included from a method -- never at file
// scope -- so everything declared here belongs to that method's variable
// scope and not to the global one. PHPCS reads each file on its own and has
// no way to see where the include happens, so it reads these as globals.
// Stated once, for the whole file, per this plugin's suppression rule.
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

$checks   = BFNET_Fulfilment::diagnostics();
$stats    = BFNET_Order::stats( 0 );
$events   = BFNET_Event::query( array( 'limit' => 100, 'orderby' => 'starts_at', 'order' => 'DESC' ) );
$batches  = BFNET_Archive::batches( 10 );
$totals   = BFNET_Archive::totals();
$auth     = BFNET_Archive::authorised_email();
$pending  = get_transient( BFNET_Archive::CODE_TRANSIENT );
$has_code = is_array( $pending ) && ! empty( $pending['hash'] );

// phpcs:ignore WordPress.Security.NonceVerification
$search  = isset( $_GET['as'] ) ? sanitize_text_field( wp_unslash( $_GET['as'] ) ) : '';
$results = $search ? BFNET_Archive::search( $search ) : array();
?>
<div class="wrap bfnet-admin">

	<?php
	$bfnet_title    = __( 'Tools & data', 'bitforgenet-guest-tickets' );
	$bfnet_subtitle = __( 'Check that ticket generation and email delivery really work, then archive your test data when you are ready to go live.', 'bitforgenet-guest-tickets' );
	include BFNET_PATH . 'admin/views/partial-masthead.php';
	?>

	<div class="bfnet-cols">
		<div>
			<!-- Diagnostics -->
			<div class="bfnet-panel">
				<div class="bfnet-panel__head">
					<h2><?php esc_html_e( 'System check', 'bitforgenet-guest-tickets' ); ?></h2>
					<span class="description"><?php esc_html_e( 'Run this first whenever a ticket or an email does not arrive.', 'bitforgenet-guest-tickets' ); ?></span>
				</div>
				<div class="bfnet-panel__body bfnet-panel__body--flush">
					<table class="bfnet-table">
						<tbody>
						<?php foreach ( $checks as $check ) : ?>
							<tr>
								<td style="width:26px">
									<span class="bfnet-badge" style="background:<?php echo $check['ok'] ? '#1e8e3e' : '#c5221f'; ?>;padding:3px 7px">
										<?php echo $check['ok'] ? '&#10003;' : '&#10005;'; ?>
									</span>
								</td>
								<td class="bfnet-table__title"><?php echo esc_html( $check['label'] ); ?></td>
								<td style="color:#646970;font-size:12.5px;word-break:break-word"><?php echo esc_html( $check['detail'] ); ?></td>
							</tr>
						<?php endforeach; ?>
						</tbody>
					</table>
				</div>
			</div>

			<!-- Test email -->
			<div class="bfnet-panel">
				<div class="bfnet-panel__head"><h2><?php esc_html_e( 'Database', 'bitforgenet-guest-tickets' ); ?></h2></div>
				<div class="bfnet-panel__body">
					<?php
					$bfnet_cols    = BFNET_Install::columns( BFNET_Install::table( 'events' ) );
					$bfnet_missing = array_diff( array( 'tables_mode', 'table_seats', 'menu_enabled', 'sponsors_image' ), $bfnet_cols );
					?>
					<?php if ( $bfnet_missing ) : ?>
						<div class="bfnet-note-box" style="border-left-color:#c5221f">
							<strong><?php esc_html_e( 'Your database is behind the plugin.', 'bitforgenet-guest-tickets' ); ?></strong><br>
							<?php
							printf(
								/* translators: %s: list of column names. */
								esc_html__( 'These columns are missing: %s. Anything that uses them cannot be saved — the event screen will appear to accept a change and then lose it.', 'bitforgenet-guest-tickets' ),
								esc_html( implode( ', ', $bfnet_missing ) )
							);
							?>
						</div>
					<?php else : ?>
						<p><?php esc_html_e( 'The database matches this version of the plugin. Every field can be saved.', 'bitforgenet-guest-tickets' ); ?></p>
					<?php endif; ?>

					<form method="post" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
						<?php wp_nonce_field( 'bfnet_repair_db', '_bfnet_nonce' ); ?>
						<input type="hidden" name="bfnet_do" value="repair_db">
						<button class="button <?php echo $bfnet_missing ? 'button-bfnet button-large' : ''; ?>">
							<?php esc_html_e( 'Bring the database up to date', 'bitforgenet-guest-tickets' ); ?>
						</button>
						<p class="description">
							<?php esc_html_e( 'Adds anything missing. It never removes a column and never touches your bookings — running it when nothing is wrong does nothing at all.', 'bitforgenet-guest-tickets' ); ?>
						</p>
					</form>
				</div>
			</div>

			<div class="bfnet-panel">
				<div class="bfnet-panel__head"><h2><?php esc_html_e( 'Send a test ticket email', 'bitforgenet-guest-tickets' ); ?></h2></div>
				<div class="bfnet-panel__body">
					<p style="margin-top:0" class="description">
						<?php esc_html_e( 'Sends a real message with a rendered sample ticket attached. If the email arrives but the PDF does not, your mail server is stripping attachments — lower the attachment ceiling in Settings and rely on the download links.', 'bitforgenet-guest-tickets' ); ?>
					</p>
					<form method="post" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
						<?php wp_nonce_field( 'bfnet_send_test_email', '_bfnet_nonce' ); ?>
						<input type="hidden" name="page" value="bitforgenet-guest-tickets-tools">
						<input type="hidden" name="bfnet_do" value="send_test_email">
						<div class="bfnet-inline">
							<input type="email" name="test_email" required style="flex:1;max-width:340px" value="<?php echo esc_attr( wp_get_current_user()->user_email ); ?>">
							<button class="button button-primary"><?php esc_html_e( 'Send test', 'bitforgenet-guest-tickets' ); ?></button>
						</div>
					</form>
				</div>
			</div>

			<!-- Archive & reset -->
			<div class="bfnet-panel" style="border-color:#f0c36d">
				<div class="bfnet-panel__head" style="background:#fffaf0">
					<h2><?php esc_html_e( 'Archive and clear the bookings', 'bitforgenet-guest-tickets' ); ?></h2>
				</div>
				<div class="bfnet-panel__body">
					<div class="bfnet-note-box" style="margin-top:0">
						<strong><?php esc_html_e( 'Nothing is destroyed.', 'bitforgenet-guest-tickets' ); ?></strong>
						<?php esc_html_e( 'Every booking, guest, ticket and scan is copied into the archive tables first, then removed from the live ones. Events, venues, organizers and ticket designs are untouched, so the site keeps working exactly as before — just empty.', 'bitforgenet-guest-tickets' ); ?>
					</div>

					<div class="bfnet-stats" style="margin:16px 0">
						<div class="bfnet-stat">
							<div class="bfnet-stat__label"><?php esc_html_e( 'Live bookings', 'bitforgenet-guest-tickets' ); ?></div>
							<div class="bfnet-stat__value"><?php echo esc_html( number_format_i18n( $stats['orders_total'] ) ); ?></div>
						</div>
						<div class="bfnet-stat">
							<div class="bfnet-stat__label"><?php esc_html_e( 'Live tickets', 'bitforgenet-guest-tickets' ); ?></div>
							<div class="bfnet-stat__value"><?php echo esc_html( number_format_i18n( $stats['tickets_total'] ) ); ?></div>
						</div>
						<div class="bfnet-stat">
							<div class="bfnet-stat__label"><?php esc_html_e( 'Already archived', 'bitforgenet-guest-tickets' ); ?></div>
							<div class="bfnet-stat__value"><?php echo esc_html( number_format_i18n( isset( $totals['orders'] ) ? $totals['orders'] : 0 ) ); ?></div>
							<div class="bfnet-stat__meta"><?php esc_html_e( 'bookings', 'bitforgenet-guest-tickets' ); ?></div>
						</div>
					</div>

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

						<div class="notice notice-error inline" style="margin:0">
							<p><?php esc_html_e( 'Set the authorising email address in Settings before this tool can be used.', 'bitforgenet-guest-tickets' ); ?></p>
						</div>

					<?php else : ?>

						<p>
							<?php
							/* translators: %s: authorising email address. */
							echo esc_html( sprintf( __( 'Step 1 — a one-time code is emailed to %s.', 'bitforgenet-guest-tickets' ), $auth ) );
							?>
						</p>

						<form method="post" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" style="margin-bottom:20px">
							<?php wp_nonce_field( 'bfnet_reset_code', '_bfnet_nonce' ); ?>
							<input type="hidden" name="page" value="bitforgenet-guest-tickets-tools">
							<input type="hidden" name="bfnet_do" value="reset_code">
							<button class="button"><?php esc_html_e( 'Email me the confirmation code', 'bitforgenet-guest-tickets' ); ?></button>
						</form>

						<form method="post" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
							<?php wp_nonce_field( 'bfnet_reset_confirm', '_bfnet_nonce' ); ?>
							<input type="hidden" name="page" value="bitforgenet-guest-tickets-tools">
							<input type="hidden" name="bfnet_do" value="reset_confirm">

							<p><?php esc_html_e( 'Step 2 — choose what to clear and enter the code.', 'bitforgenet-guest-tickets' ); ?></p>

							<div class="bfnet-row">
								<div class="bfnet-field">
									<label for="bfnet-reset-scope"><?php esc_html_e( 'What to clear', 'bitforgenet-guest-tickets' ); ?></label>
									<select id="bfnet-reset-scope" name="scope">
										<option value="all"><?php esc_html_e( 'Every booking on the site', 'bitforgenet-guest-tickets' ); ?></option>
										<option value="event"><?php esc_html_e( 'Only one event', 'bitforgenet-guest-tickets' ); ?></option>
									</select>
								</div>
								<div class="bfnet-field">
									<label for="bfnet-reset-event"><?php esc_html_e( 'Event', 'bitforgenet-guest-tickets' ); ?></label>
									<select id="bfnet-reset-event" name="event_id">
										<option value="0"><?php esc_html_e( '— choose —', 'bitforgenet-guest-tickets' ); ?></option>
										<?php foreach ( $events as $row ) : ?>
											<option value="<?php echo (int) $row->id; ?>"><?php echo esc_html( $row->title ); ?></option>
										<?php endforeach; ?>
									</select>
								</div>
							</div>

							<div class="bfnet-field">
								<label for="bfnet-reset-reason"><?php esc_html_e( 'Note for the archive', 'bitforgenet-guest-tickets' ); ?></label>
								<input type="text" id="bfnet-reset-reason" name="reason" placeholder="<?php esc_attr_e( 'End of testing, going live', 'bitforgenet-guest-tickets' ); ?>">
							</div>

							<div class="bfnet-field">
								<label>
									<input type="checkbox" name="delete_files" value="1" checked>
									<?php esc_html_e( 'Also delete the generated ticket PDFs from the server', 'bitforgenet-guest-tickets' ); ?>
								</label>
							</div>

							<div class="bfnet-field">
								<label for="bfnet-reset-code"><?php esc_html_e( 'Confirmation code', 'bitforgenet-guest-tickets' ); ?></label>
								<input type="text" id="bfnet-reset-code" name="reset_code" inputmode="numeric" maxlength="6" autocomplete="off"
									style="max-width:180px;font-size:20px;letter-spacing:.3em;font-family:monospace;text-align:center"
									placeholder="000000" required>
								<?php if ( $has_code ) : ?>
									<p class="description" style="color:#1e8e3e"><?php esc_html_e( 'A code is waiting in that mailbox.', 'bitforgenet-guest-tickets' ); ?></p>
								<?php endif; ?>
							</div>

							<button class="button button-primary" style="background:#c5221f;border-color:#a91b18"
								data-bfnet-confirm="<?php esc_attr_e( 'Archive and clear the selected bookings now?', 'bitforgenet-guest-tickets' ); ?>">
								<?php esc_html_e( 'Archive and clear', 'bitforgenet-guest-tickets' ); ?>
							</button>
						</form>

					<?php endif; ?>
				</div>
			</div>
		</div>

		<div>
			<!-- Archive browser -->
			<div class="bfnet-panel">
				<div class="bfnet-panel__head"><h2><?php esc_html_e( 'Archive', 'bitforgenet-guest-tickets' ); ?></h2></div>
				<div class="bfnet-panel__body">
					<form method="get" style="margin-bottom:14px">
						<input type="hidden" name="page" value="bitforgenet-guest-tickets-tools">
						<label class="bfnet-label" for="bfnet-archive-search"><?php esc_html_e( 'Find an archived booking', 'bitforgenet-guest-tickets' ); ?></label>
						<div class="bfnet-inline">
							<input type="search" id="bfnet-archive-search" name="as" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Reference, name or email', 'bitforgenet-guest-tickets' ); ?>" style="flex:1">
							<button class="button"><?php esc_html_e( 'Search', 'bitforgenet-guest-tickets' ); ?></button>
						</div>
					</form>

					<?php if ( $search ) : ?>
						<?php if ( empty( $results ) ) : ?>
							<p class="description"><?php esc_html_e( 'Nothing archived matches that.', 'bitforgenet-guest-tickets' ); ?></p>
						<?php else : ?>
							<table class="bfnet-table" style="margin-bottom:14px">
								<tbody>
								<?php foreach ( $results as $record ) : ?>
									<?php $data = BFNET_Util::json( $record->payload ); ?>
									<tr>
										<td>
											<div class="bfnet-table__title">
												<?php echo esc_html( BFNET_Util::full_name( isset( $data['first_name'] ) ? $data['first_name'] : '', isset( $data['last_name'] ) ? $data['last_name'] : '' ) ); ?>
											</div>
											<div class="bfnet-table__sub bfnet-mono"><?php echo esc_html( $record->reference ); ?> · <?php echo esc_html( $record->email ); ?></div>
										</td>
										<td class="bfnet-num">
											<?php echo esc_html( isset( $data['quantity'] ) ? (int) $data['quantity'] : 0 ); ?>×<br>
											<span class="bfnet-table__sub"><?php echo esc_html( isset( $data['payment_status'] ) ? $data['payment_status'] : '' ); ?></span>
										</td>
									</tr>
								<?php endforeach; ?>
								</tbody>
							</table>
						<?php endif; ?>
					<?php endif; ?>

					<h3 style="font-size:13px;margin:0 0 8px;color:#646970;text-transform:uppercase;letter-spacing:.08em"><?php esc_html_e( 'Batches', 'bitforgenet-guest-tickets' ); ?></h3>

					<?php if ( empty( $batches ) ) : ?>
						<p class="description" style="margin:0"><?php esc_html_e( 'Nothing has been archived yet.', 'bitforgenet-guest-tickets' ); ?></p>
					<?php else : ?>
						<?php foreach ( $batches as $batch ) : ?>
							<?php $counts = BFNET_Util::json( $batch->counts ); ?>
							<div style="padding:11px 0;border-bottom:1px solid #f0f0f1">
								<strong style="font-size:13.5px"><?php echo esc_html( $batch->label ); ?></strong>
								<div class="bfnet-table__sub">
									<?php echo esc_html( BFNET_Util::date( $batch->created_at ) ); ?>
									<?php if ( $counts ) : ?>
										·
										<?php
										$bits = array();
										foreach ( array( 'orders', 'tickets', 'scans' ) as $key ) {
											if ( ! empty( $counts[ $key ] ) ) {
												$bits[] = (int) $counts[ $key ] . ' ' . $key;
											}
										}
										echo esc_html( implode( ', ', $bits ) );
										?>
									<?php endif; ?>
								</div>
								<?php if ( $batch->reason ) : ?>
									<div class="bfnet-table__sub"><em><?php echo esc_html( $batch->reason ); ?></em></div>
								<?php endif; ?>
							</div>
						<?php endforeach; ?>
					<?php endif; ?>
				</div>
			</div>

			<div class="bfnet-panel">
				<div class="bfnet-panel__head"><h2><?php esc_html_e( 'Where things live', 'bitforgenet-guest-tickets' ); ?></h2></div>
				<div class="bfnet-panel__body">
					<dl class="bfnet-kv" style="font-size:12.5px">
						<dt><?php esc_html_e( 'Booking page', 'bitforgenet-guest-tickets' ); ?></dt>
						<dd><?php echo esc_html( BFNET_Util::registration_page_url() ); ?></dd>
						<dt><?php esc_html_e( 'Ticket storage', 'bitforgenet-guest-tickets' ); ?></dt>
						<dd><?php $bfnet_storage = BFNET_Install::storage(); echo esc_html( str_replace( ABSPATH, '', $bfnet_storage['dir'] ) ); ?></dd>
						<dt><?php esc_html_e( 'Site timezone', 'bitforgenet-guest-tickets' ); ?></dt>
						<dd><?php echo esc_html( BFNET_Util::site_timezone() ); ?></dd>
						<dt><?php esc_html_e( 'Server time', 'bitforgenet-guest-tickets' ); ?></dt>
						<dd><?php echo esc_html( BFNET_Util::date( current_time( 'mysql' ), 'j M Y H:i' ) . ' ' . BFNET_Util::tz_abbr( current_time( 'mysql' ) ) ); ?></dd>
						<dt><?php esc_html_e( 'Plugin version', 'bitforgenet-guest-tickets' ); ?></dt>
						<dd><?php echo esc_html( BFNET_VERSION ); ?></dd>
					</dl>
				</div>
			</div>
		</div>
	</div>
</div>
