<?php
/**
 * Admin view: the door.
 *
 * This screen no longer tries to be a scanner. Running a camera inside wp-admin
 * puts it behind every other plugin's scripts and styles, any one of which can
 * stop ours from running or collapse the preview — and from the agent's side both
 * look like a black rectangle. The scanner now lives at its own address, on a page
 * the plugin renders from nothing. What is left here is what an office screen is
 * actually for: opening that station, handing out the code, and watching the door.
 *
 * @package BitForgeNet_Guest_Tickets
 * @since   1.2.0
 */

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

// phpcs:ignore WordPress.Security.NonceVerification
$event_id = isset( $_GET['event'] ) ? (int) $_GET['event'] : 0;

$events = BFNET_Event::query(
	array(
		'statuses' => array( 'open', 'closed', 'sold_out', 'published' ),
		'orderby'  => 'starts_at',
		'order'    => 'ASC',
		'limit'    => 50,
	)
);

if ( ! $event_id && $events ) {
	$event_id = (int) $events[0]->id;
}

$event = $event_id ? BFNET_Event::get( $event_id ) : null;
$stats = BFNET_Order::stats( $event_id );

// Shown exactly once, immediately after it is issued.
// phpcs:ignore WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- preg_replace strips everything but letters and digits.
$fresh_pin = isset( $_GET['pin'] ) ? strtoupper( preg_replace( '/[^A-Za-z0-9]/', '', (string) wp_unslash( $_GET['pin'] ) ) ) : '';
$record    = $event ? BFNET_Door::pin_record( (int) $event->id ) : null;
$station   = BFNET_Door::url();
?>
<div class="wrap bfnet-admin">

	<?php
	$bfnet_title    = __( 'The door', 'bitforgenet-guest-tickets' );
	$bfnet_subtitle = $event
		? sprintf( '%s · %s', $event->title, BFNET_Util::event_date( $event, 'starts_at', 'l j F Y · H:i' ) )
		: __( 'Select an event to set the door up.', 'bitforgenet-guest-tickets' );
	$bfnet_actions  = $event ? '<a class="button button-bfnet" target="_blank" rel="noopener" href="' . esc_url( add_query_arg( 'event', (int) $event->id, $station ) ) . '">' . esc_html__( 'Open the door station', 'bitforgenet-guest-tickets' ) . '</a>' : '';
	include BFNET_PATH . 'admin/views/partial-masthead.php';
	?>

	<div class="bfnet-panel">
		<div class="bfnet-panel__head">
			<form method="get" class="bfnet-filters">
				<input type="hidden" name="page" value="bitforgenet-guest-tickets-scanner">
				<div class="bfnet-field">
					<label class="bfnet-label" for="bfnet-s-event"><?php esc_html_e( 'Event at the door', 'bitforgenet-guest-tickets' ); ?></label>
					<select id="bfnet-s-event" name="event" onchange="this.form.submit()">
						<?php foreach ( $events as $row ) : ?>
							<option value="<?php echo (int) $row->id; ?>" <?php selected( $event_id, (int) $row->id ); ?>>
								<?php echo esc_html( $row->title . ' — ' . BFNET_Util::event_date( $row, 'starts_at', 'j M Y' ) ); ?>
							</option>
						<?php endforeach; ?>
					</select>
				</div>
			</form>
		</div>

		<div class="bfnet-panel__body">
			<?php if ( ! $event ) : ?>
				<div class="bfnet-empty-state">
					<h3><?php esc_html_e( 'No event to scan', 'bitforgenet-guest-tickets' ); ?></h3>
					<p><?php esc_html_e( 'Publish an event first, then come back here on the night.', 'bitforgenet-guest-tickets' ); ?></p>
				</div>
			<?php else : ?>

				<div id="bfnet-live-stats" class="bfnet-stats">
					<div class="bfnet-stat bfnet-stat--good">
						<div class="bfnet-stat__label"><?php esc_html_e( 'Inside', 'bitforgenet-guest-tickets' ); ?></div>
						<div class="bfnet-stat__value" data-stat="checked_in"><?php echo esc_html( number_format_i18n( $stats['tickets_checked_in'] ) ); ?></div>
						<div class="bfnet-progress bfnet-progress--good"><span style="width:<?php echo (int) ( $stats['seats_paid'] > 0 ? min( 100, round( ( $stats['tickets_checked_in'] / $stats['seats_paid'] ) * 100 ) ) : 0 ); ?>%"></span></div>
					</div>
					<div class="bfnet-stat">
						<div class="bfnet-stat__label"><?php esc_html_e( 'Expected', 'bitforgenet-guest-tickets' ); ?></div>
						<div class="bfnet-stat__value" data-stat="expected"><?php echo esc_html( number_format_i18n( $stats['seats_paid'] ) ); ?></div>
					</div>
					<div class="bfnet-stat bfnet-stat--warn">
						<div class="bfnet-stat__label"><?php esc_html_e( 'Still outside', 'bitforgenet-guest-tickets' ); ?></div>
						<div class="bfnet-stat__value" data-stat="remaining"><?php echo esc_html( number_format_i18n( max( 0, $stats['seats_paid'] - $stats['tickets_checked_in'] ) ) ); ?></div>
					</div>
					<div class="bfnet-stat bfnet-stat--bad">
						<div class="bfnet-stat__label"><?php esc_html_e( 'Unpaid holds', 'bitforgenet-guest-tickets' ); ?></div>
						<div class="bfnet-stat__value" data-stat="pending"><?php echo esc_html( number_format_i18n( $stats['seats_pending'] ) ); ?></div>
					</div>
				</div>

				<div class="bfnet-cols" style="margin-top:20px">

					<div>
						<div class="bfnet-panel">
							<div class="bfnet-panel__head"><h2><?php esc_html_e( 'The door code', 'bitforgenet-guest-tickets' ); ?></h2></div>
							<div class="bfnet-panel__body">

								<?php if ( $fresh_pin ) : ?>
									<div class="bfnet-pin">
										<div class="bfnet-pin__label"><?php esc_html_e( 'Give this code to your door agents', 'bitforgenet-guest-tickets' ); ?></div>
										<div class="bfnet-pin__value"><?php echo esc_html( implode( ' ', str_split( $fresh_pin, 4 ) ) ); ?></div>
										<p class="description"><?php esc_html_e( 'Write it down now — it is shown once and never stored in clear. Issuing a new code closes every station using the old one.', 'bitforgenet-guest-tickets' ); ?></p>
									</div>
								<?php elseif ( $record ) : ?>
									<p>
										<?php
										printf(
											/* translators: 1: date and time, 2: number of times a code has been issued. */
											esc_html__( 'A code is active for this event, issued %1$s (issue #%2$d). The code itself is stored only as a digest, so it cannot be shown again.', 'bitforgenet-guest-tickets' ),
											esc_html( BFNET_Util::date( gmdate( 'Y-m-d H:i:s', (int) $record['issued'] ), 'j M · H:i' ) ),
											(int) $record['version']
										);
										?>
									</p>
								<?php else : ?>
									<p><?php esc_html_e( 'No code has been issued for this event yet. Your agents need one to open the station on their own phones.', 'bitforgenet-guest-tickets' ); ?></p>
								<?php endif; ?>

								<form method="post" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" style="margin-top:14px">
									<?php wp_nonce_field( 'bfnet_door_pin', '_bfnet_nonce' ); ?>
									<input type="hidden" name="bfnet_do" value="door_pin">
									<input type="hidden" name="event" value="<?php echo (int) $event->id; ?>">
									<button class="button button-bfnet button-large">
										<?php echo $record ? esc_html__( 'Issue a new code', 'bitforgenet-guest-tickets' ) : esc_html__( 'Issue the door code', 'bitforgenet-guest-tickets' ); ?>
									</button>
									<?php if ( $record ) : ?>
										<button class="button" name="revoke" value="1" data-bfnet-confirm="<?php esc_attr_e( 'Every open station will be signed out. Continue?', 'bitforgenet-guest-tickets' ); ?>">
											<?php esc_html_e( 'Close all stations', 'bitforgenet-guest-tickets' ); ?>
										</button>
									<?php endif; ?>
								</form>
							</div>
						</div>

						<div class="bfnet-panel">
							<div class="bfnet-panel__head"><h2><?php esc_html_e( 'How the night runs', 'bitforgenet-guest-tickets' ); ?></h2></div>
							<div class="bfnet-panel__body">
								<ol class="bfnet-steps">
									<li>
										<strong><?php esc_html_e( 'Send your agents the station address.', 'bitforgenet-guest-tickets' ); ?></strong><br>
										<code class="bfnet-mono"><?php echo esc_html( $station ); ?></code>
										<button class="button button-small" data-bfnet-copy="<?php echo esc_attr( $station ); ?>"><?php esc_html_e( 'Copy', 'bitforgenet-guest-tickets' ); ?></button>
									</li>
									<li><strong><?php esc_html_e( 'They enter the code once.', 'bitforgenet-guest-tickets' ); ?></strong> <?php esc_html_e( 'No WordPress account, no password, nothing to install. The station stays open for the night and can be closed from here at any moment.', 'bitforgenet-guest-tickets' ); ?></li>
									<li><strong><?php esc_html_e( 'They scan.', 'bitforgenet-guest-tickets' ); ?></strong> <?php esc_html_e( 'Live camera, a photograph, or the ticket number on a keypad — three routes, so a stubborn phone never stops the queue.', 'bitforgenet-guest-tickets' ); ?></li>
								</ol>
								<p class="description" style="margin-top:10px">
									<?php esc_html_e( 'Without a code, a stranger who photographs a ticket QR sees nothing and changes nothing.', 'bitforgenet-guest-tickets' ); ?>
								</p>
							</div>
						</div>
					</div>

					<div>
						<div class="bfnet-panel">
							<div class="bfnet-panel__head"><h2><?php esc_html_e( 'Open it on this screen', 'bitforgenet-guest-tickets' ); ?></h2></div>
							<div class="bfnet-panel__body">
								<p><?php esc_html_e( 'You are signed in, so the station opens for you without a code.', 'bitforgenet-guest-tickets' ); ?></p>
								<p>
									<a class="button button-bfnet button-large" target="_blank" rel="noopener"
										href="<?php echo esc_url( add_query_arg( 'event', (int) $event->id, $station ) ); ?>">
										<?php esc_html_e( 'Open the door station', 'bitforgenet-guest-tickets' ); ?>
									</a>
								</p>
								<p class="description">
									<?php esc_html_e( 'It runs on a phone, a tablet or this computer. Add it to the phone’s home screen and it opens full-screen like an app.', 'bitforgenet-guest-tickets' ); ?>
								</p>
							</div>
						</div>

						<div class="bfnet-panel">
							<div class="bfnet-panel__head"><h2><?php esc_html_e( 'The paper fallback', 'bitforgenet-guest-tickets' ); ?></h2></div>
							<div class="bfnet-panel__body">
								<p><?php esc_html_e( 'Print this before you leave. If the wifi, the phone or the server lets you down, the night still runs on paper: guests listed by surname, with the ticket number and a box to tick.', 'bitforgenet-guest-tickets' ); ?></p>
								<p class="bfnet-inline">
									<?php foreach ( BFNET_Roll_Call::filters() as $bfnet_f => $bfnet_fl ) : ?>
										<a class="button <?php echo 'paid' === $bfnet_f ? 'button-bfnet' : ''; ?>"
											href="<?php echo esc_url( wp_nonce_url( BFNET_Util::admin_url( 'bitforgenet-guest-tickets-scanner', array( 'bfnet_do' => 'roll_call', 'event' => (int) $event->id, 'filter' => $bfnet_f ) ), 'bfnet_roll_call', '_bfnet_nonce' ) ); ?>">
											<?php echo esc_html( $bfnet_fl ); ?>
										</a>
									<?php endforeach; ?>
								</p>
								<p class="description"><?php esc_html_e( 'A4, ordered by surname — because at a door you are given a name, not a reference. Unpaid guests are flagged in red.', 'bitforgenet-guest-tickets' ); ?></p>
							</div>
						</div>

						<div class="bfnet-panel">
							<div class="bfnet-panel__head"><h2><?php esc_html_e( 'Last scans', 'bitforgenet-guest-tickets' ); ?></h2></div>
							<div class="bfnet-panel__body bfnet-panel__body--flush">
								<div class="bfnet-feed" id="bfnet-feed">
									<?php
									$recent = BFNET_Ticket::query(
										array(
											'event_id'   => (int) $event->id,
											'checked_in' => 1,
											'orderby'    => 'checked_in_at',
											'order'      => 'DESC',
											'limit'      => 12,
										)
									);
									?>
									<?php if ( ! $recent ) : ?>
										<div class="bfnet-empty-state" style="padding:26px 18px">
											<p style="margin:0"><?php esc_html_e( 'Nobody has come through yet.', 'bitforgenet-guest-tickets' ); ?></p>
										</div>
									<?php else : ?>
										<table class="bfnet-table">
											<tbody>
											<?php foreach ( $recent as $row ) : ?>
												<tr>
													<td>
														<div class="bfnet-table__title"><?php echo esc_html( BFNET_Util::full_name( isset( $row->first_name ) ? $row->first_name : '', isset( $row->last_name ) ? $row->last_name : '' ) ); ?></div>
														<div class="bfnet-table__sub bfnet-mono"><?php echo esc_html( $row->serial ); ?></div>
													</td>
													<td class="bfnet-num"><?php echo esc_html( BFNET_Util::date( $row->checked_in_at, 'H:i' ) ); ?></td>
												</tr>
											<?php endforeach; ?>
											</tbody>
										</table>
									<?php endif; ?>
								</div>
							</div>
						</div>
					</div>
				</div>

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