<?php
/**
 * Admin view: per-event dashboard.
 *
 * @package BitForgeNet_Guest_Tickets
 *
 * @var object $event Event row.
 */

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

// This file talks to the plugin's own tables. WordPress has no API for them --
// they are not posts and not meta -- so $wpdb is the only way in. The rows
// change on every booking and every scan, which makes an object cache wrong
// more often than it is right. Table names are built from $wpdb->prefix and
// never from a request, so interpolating one carries nothing to inject; every
// value goes through $wpdb->prepare(), and the few identifiers that cannot
// (ORDER BY columns) are matched against a whitelist first.
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable WordPress.DB.DirectDatabaseQuery.SchemaChange
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter


global $wpdb;

$stats     = BFNET_Order::stats( (int) $event->id );
$venue     = BFNET_Venue::get( $event->venue_id );
$organizer = BFNET_Organizer::get( $event->organizer_id );
$types     = BFNET_Offers::tiers( (int) $event->id );
$left      = BFNET_Event::seats_left( $event );
$capacity  = (int) $event->capacity;
$pending   = BFNET_Order::query( array( 'event_id' => (int) $event->id, 'payment_status' => 'pending', 'limit' => 8 ) );

$scans_table = BFNET_Install::table( 'scans' );
$recent_scan = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$scans_table} WHERE event_id = %d ORDER BY id DESC LIMIT 12", (int) $event->id ) ); // phpcs:ignore WordPress.DB.PreparedSQL

$checkin_pct = $stats['seats_paid'] > 0 ? min( 100, round( ( $stats['tickets_checked_in'] / $stats['seats_paid'] ) * 100 ) ) : 0;
$fill_pct    = $capacity > 0 ? min( 100, round( ( $stats['seats_paid'] / $capacity ) * 100 ) ) : 0;
?>
<div class="wrap bfnet-admin">

	<?php
	$bfnet_title    = $event->title;
	$bfnet_subtitle = sprintf(
		'%s%s · %s',
		$event->series ? $event->series . ' · ' : '',
		BFNET_Util::date( $event->starts_at ),
		$venue ? $venue->name : __( 'venue to be confirmed', 'bitforgenet-guest-tickets' )
	);
	/**
	 * Buttons a module adds to this event's masthead.
	 *
	 * A module's screen needs a way in, and the way in has to disappear with the
	 * module — a button that leads nowhere is worse than no button.
	 *
	 * @param string $extra Pre-escaped markup.
	 * @param object $event The event.
	 */
	$bfnet_actions  = (string) apply_filters( 'bfnet_event_actions', '', $event );
	$bfnet_actions .= '<a class="button" href="' . esc_url( BFNET_Util::admin_url( 'bitforgenet-guest-tickets-events', array( 'action' => 'edit', 'event' => (int) $event->id ) ) ) . '">' . esc_html__( 'Edit event', 'bitforgenet-guest-tickets' ) . '</a>'
		. '<a class="button" href="' . esc_url( BFNET_Util::admin_url( 'bitforgenet-guest-tickets-orders', array( 'event' => (int) $event->id ) ) ) . '">' . esc_html__( 'Subscribers', 'bitforgenet-guest-tickets' ) . '</a>'
		. '<a class="button button-bfnet" href="' . esc_url( BFNET_Util::admin_url( 'bitforgenet-guest-tickets-scanner', array( 'event' => (int) $event->id ) ) ) . '">' . esc_html__( 'Door scanner', 'bitforgenet-guest-tickets' ) . '</a>';
	include BFNET_PATH . 'admin/views/partial-masthead.php';
	?>

	<div class="bfnet-stats">
		<div class="bfnet-stat bfnet-stat--good">
			<div class="bfnet-stat__label"><?php esc_html_e( 'Revenue', 'bitforgenet-guest-tickets' ); ?></div>
			<div class="bfnet-stat__value"><?php echo esc_html( BFNET_Util::money( $stats['revenue_cents'], $event->currency ) ); ?></div>
			<div class="bfnet-stat__meta">
				<?php
				/* translators: %s: pipeline amount. */
				echo esc_html( sprintf( __( '%s pending', 'bitforgenet-guest-tickets' ), BFNET_Util::money( $stats['pipeline_cents'], $event->currency ) ) );
				?>
			</div>
		</div>
		<div class="bfnet-stat">
			<div class="bfnet-stat__label"><?php esc_html_e( 'Seats sold', 'bitforgenet-guest-tickets' ); ?></div>
			<div class="bfnet-stat__value"><?php echo esc_html( number_format_i18n( $stats['seats_paid'] ) ); ?><?php echo $capacity > 0 ? '<small style="font-size:15px;color:#646970"> / ' . esc_html( number_format_i18n( $capacity ) ) . '</small>' : ''; ?></div>
			<?php if ( $capacity > 0 ) : ?>
				<div class="bfnet-progress"><span style="width:<?php echo (int) $fill_pct; ?>%"></span></div>
			<?php endif; ?>
		</div>
		<div class="bfnet-stat bfnet-stat--warn">
			<div class="bfnet-stat__label"><?php esc_html_e( 'Awaiting payment', 'bitforgenet-guest-tickets' ); ?></div>
			<div class="bfnet-stat__value"><?php echo esc_html( number_format_i18n( $stats['seats_pending'] ) ); ?></div>
			<div class="bfnet-stat__meta">
				<?php
				/* translators: %d: number of bookings. */
				echo esc_html( sprintf( _n( '%d booking', '%d bookings', $stats['orders_pending'], 'bitforgenet-guest-tickets' ), $stats['orders_pending'] ) );
				?>
			</div>
		</div>
		<div class="bfnet-stat">
			<div class="bfnet-stat__label"><?php esc_html_e( 'Checked in', 'bitforgenet-guest-tickets' ); ?></div>
			<div class="bfnet-stat__value"><?php echo esc_html( number_format_i18n( $stats['tickets_checked_in'] ) ); ?> / <?php echo esc_html( number_format_i18n( $stats['seats_paid'] ) ); ?></div>
			<div class="bfnet-progress bfnet-progress--good"><span style="width:<?php echo (int) $checkin_pct; ?>%"></span></div>
		</div>
		<div class="bfnet-stat">
			<div class="bfnet-stat__label"><?php esc_html_e( 'Still to arrive', 'bitforgenet-guest-tickets' ); ?></div>
			<div class="bfnet-stat__value"><?php echo esc_html( number_format_i18n( max( 0, $stats['seats_paid'] - $stats['tickets_checked_in'] ) ) ); ?></div>
			<div class="bfnet-stat__meta">
				<?php
				/* translators: %d: number of seats left to sell. */
				echo null === $left ? esc_html__( 'unlimited capacity', 'bitforgenet-guest-tickets' ) : esc_html( sprintf( __( '%d seats still on sale', 'bitforgenet-guest-tickets' ), $left ) );
				?>
			</div>
		</div>
	</div>

	<div class="bfnet-cols">
		<div>
			<div class="bfnet-panel">
				<div class="bfnet-panel__head">
					<h2><?php esc_html_e( 'Waiting for payment validation', 'bitforgenet-guest-tickets' ); ?></h2>
					<a class="button button-small" href="<?php echo esc_url( BFNET_Util::admin_url( 'bitforgenet-guest-tickets-orders', array( 'event' => (int) $event->id, 'status' => 'pending' ) ) ); ?>"><?php esc_html_e( 'See all', 'bitforgenet-guest-tickets' ); ?></a>
				</div>
				<div class="bfnet-panel__body bfnet-panel__body--flush">
					<?php if ( empty( $pending ) ) : ?>
						<div class="bfnet-empty-state"><p><?php esc_html_e( 'Nothing pending. Every booking on this event is paid.', 'bitforgenet-guest-tickets' ); ?></p></div>
					<?php else : ?>
						<table class="bfnet-table">
							<tbody>
							<?php foreach ( $pending as $order ) : ?>
								<tr>
									<td>
										<div class="bfnet-table__title"><?php echo esc_html( BFNET_Util::full_name( $order->first_name, $order->last_name ) ); ?></div>
										<div class="bfnet-table__sub bfnet-mono"><?php echo esc_html( $order->reference ); ?> · <?php echo esc_html( $order->phone ); ?></div>
									</td>
									<td class="bfnet-num"><?php echo esc_html( (int) $order->quantity ); ?>×</td>
									<td class="bfnet-num"><strong><?php echo esc_html( BFNET_Util::money( $order->total_cents, $order->currency ) ); ?></strong></td>
									<td class="bfnet-num"><?php echo esc_html( BFNET_Util::relative( $order->created_at ) ); ?></td>
									<td class="bfnet-num">
										<a class="button button-small button-primary" href="<?php echo esc_url( BFNET_Util::admin_url( 'bitforgenet-guest-tickets-orders', array( 'action' => 'view', 'order' => (int) $order->id ) ) ); ?>"><?php esc_html_e( 'Validate', 'bitforgenet-guest-tickets' ); ?></a>
									</td>
								</tr>
							<?php endforeach; ?>
							</tbody>
						</table>
					<?php endif; ?>
				</div>
			</div>

			<?php if ( $types ) : ?>
			<div class="bfnet-panel">
				<div class="bfnet-panel__head">
					<h2><?php esc_html_e( 'Sales by category', 'bitforgenet-guest-tickets' ); ?></h2>
				</div>
				<div class="bfnet-panel__body bfnet-panel__body--flush">
					<table class="bfnet-table">
						<thead>
							<tr>
								<th><?php esc_html_e( 'Category', 'bitforgenet-guest-tickets' ); ?></th>
								<th class="bfnet-num"><?php esc_html_e( 'Price', 'bitforgenet-guest-tickets' ); ?></th>
								<th class="bfnet-num"><?php esc_html_e( 'Sold', 'bitforgenet-guest-tickets' ); ?></th>
								<th class="bfnet-num"><?php esc_html_e( 'Remaining', 'bitforgenet-guest-tickets' ); ?></th>
							</tr>
						</thead>
						<tbody>
						<?php foreach ( $types as $type ) : ?>
							<?php
							$attendees_table = BFNET_Install::table( 'attendees' );
							$orders_table    = BFNET_Order::table();
							$sold            = (int) $wpdb->get_var(
								$wpdb->prepare(
									"SELECT COUNT(*) FROM {$attendees_table} a INNER JOIN {$orders_table} o ON o.id = a.order_id
									 WHERE a.ticket_type_id = %d AND o.payment_status = 'paid'",
									(int) $type->id
								)
							); // phpcs:ignore WordPress.DB.PreparedSQL
							$type_left = BFNET_Offers::seats_left( $type );
							?>
							<tr>
								<td>
									<div class="bfnet-table__title"><?php echo esc_html( $type->name ); ?></div>
									<?php if ( $type->badge ) : ?><div class="bfnet-table__sub"><?php echo esc_html( $type->badge ); ?></div><?php endif; ?>
								</td>
								<td class="bfnet-num"><?php echo esc_html( BFNET_Util::money( BFNET_Offers::price( $event, $type ), $event->currency ) ); ?></td>
								<td class="bfnet-num"><?php echo esc_html( number_format_i18n( $sold ) ); ?></td>
								<td class="bfnet-num"><?php echo null === $type_left ? '∞' : esc_html( number_format_i18n( $type_left ) ); ?></td>
							</tr>
						<?php endforeach; ?>
						</tbody>
					</table>
				</div>
			</div>

			<?php endif; ?>

			<div class="bfnet-panel">
				<div class="bfnet-panel__head"><h2><?php esc_html_e( 'Last scans at the door', 'bitforgenet-guest-tickets' ); ?></h2></div>
				<div class="bfnet-panel__body bfnet-panel__body--flush">
					<?php if ( empty( $recent_scan ) ) : ?>
						<div class="bfnet-empty-state"><p><?php esc_html_e( 'No scan recorded yet for this event.', 'bitforgenet-guest-tickets' ); ?></p></div>
					<?php else : ?>
						<div class="bfnet-feed">
							<?php foreach ( $recent_scan as $scan ) : ?>
								<?php
								$dot    = in_array( $scan->result, array( 'valid', 'manual' ), true ) ? 'ok' : ( 'already_used' === $scan->result ? 'warn' : 'bad' );
								$ticket = $scan->ticket_id ? BFNET_Ticket::get( (int) $scan->ticket_id ) : null;
								$who    = $ticket ? BFNET_Ticket::attendee( $ticket ) : null;
								?>
								<div class="bfnet-feed__item">
									<span class="bfnet-feed__dot bfnet-feed__dot--<?php echo esc_attr( $dot ); ?>"></span>
									<span><?php echo esc_html( $who ? BFNET_Util::full_name( $who->first_name, $who->last_name ) : __( 'Unknown code', 'bitforgenet-guest-tickets' ) ); ?></span>
									<span style="opacity:.6"><?php echo esc_html( str_replace( '_', ' ', $scan->result ) ); ?></span>
									<span style="margin-left:auto;opacity:.6"><?php echo esc_html( BFNET_Util::date( $scan->scanned_at, 'H:i:s' ) ); ?></span>
								</div>
							<?php endforeach; ?>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>

		<div>
			<div class="bfnet-panel">
				<div class="bfnet-panel__head"><h2><?php esc_html_e( 'At a glance', 'bitforgenet-guest-tickets' ); ?></h2></div>
				<div class="bfnet-panel__body">
					<dl class="bfnet-kv">
						<dt><?php esc_html_e( 'Status', 'bitforgenet-guest-tickets' ); ?></dt>
						<dd><span class="bfnet-badge" style="background:<?php echo esc_attr( BFNET_Util::status_color( $event->status ) ); ?>"><?php echo esc_html( BFNET_Util::event_statuses()[ $event->status ] ?? $event->status ); ?></span></dd>

						<dt><?php esc_html_e( 'Starts', 'bitforgenet-guest-tickets' ); ?></dt>
						<dd><?php echo esc_html( BFNET_Util::date( $event->starts_at ) ); ?></dd>

						<?php if ( ! empty( $event->doors_open_at ) && '0000-00-00 00:00:00' !== $event->doors_open_at ) : ?>
							<dt><?php esc_html_e( 'Doors', 'bitforgenet-guest-tickets' ); ?></dt>
							<dd><?php echo esc_html( BFNET_Util::date( $event->doors_open_at, get_option( 'time_format' ) ) ); ?></dd>
						<?php endif; ?>

						<dt><?php esc_html_e( 'Organizer', 'bitforgenet-guest-tickets' ); ?></dt>
						<dd><?php echo esc_html( $organizer ? $organizer->name : '—' ); ?></dd>

						<dt><?php esc_html_e( 'Venue', 'bitforgenet-guest-tickets' ); ?></dt>
						<dd>
							<?php echo esc_html( $venue ? $venue->name : '—' ); ?>
							<?php $map = BFNET_Venue::map_url( $venue ); ?>
							<?php if ( $map ) : ?>
								<br><a href="<?php echo esc_url( $map ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Google Maps', 'bitforgenet-guest-tickets' ); ?></a>
							<?php endif; ?>
						</dd>
					</dl>
				</div>
			</div>

			<div class="bfnet-panel">
				<div class="bfnet-panel__head"><h2><?php esc_html_e( 'Export', 'bitforgenet-guest-tickets' ); ?></h2></div>
				<div class="bfnet-panel__body">
					<p style="margin-top:0" class="description"><?php esc_html_e( 'CSV files open directly in Excel and Google Sheets.', 'bitforgenet-guest-tickets' ); ?></p>
					<p>
						<a class="button" href="<?php echo esc_url( BFNET_Util::admin_url( 'bitforgenet-guest-tickets-orders', array( 'action' => 'export', 'what' => 'orders', 'event' => (int) $event->id ) ) ); ?>"><?php esc_html_e( 'Download bookings', 'bitforgenet-guest-tickets' ); ?></a>
					</p>
					<p style="margin-bottom:0">
						<a class="button" href="<?php echo esc_url( BFNET_Util::admin_url( 'bitforgenet-guest-tickets-orders', array( 'action' => 'export', 'what' => 'guests', 'event' => (int) $event->id ) ) ); ?>"><?php esc_html_e( 'Download guest list', 'bitforgenet-guest-tickets' ); ?></a>
					</p>
				</div>
			</div>

			<div class="bfnet-panel">
				<div class="bfnet-panel__head"><h2><?php esc_html_e( 'Booking link', 'bitforgenet-guest-tickets' ); ?></h2></div>
				<div class="bfnet-panel__body">
					<code class="bfnet-code"><?php echo esc_html( BFNET_Util::event_url( $event ) ); ?></code>
					<p class="description" style="margin-bottom:0"><?php esc_html_e( 'Send this on WhatsApp so guests land straight on this event.', 'bitforgenet-guest-tickets' ); ?></p>
				</div>
			</div>
		</div>
	</div>

	<?php
	/**
	 * Panels a module adds to an event dashboard.
	 *
	 * @param object $event The event.
	 */
	do_action( 'bfnet_event_dashboard_panels', $event );
	?>

</div>
