<?php
/**
 * Dashboard widget template.
 *
 * @package GoValid_QR
 */

defined( 'ABSPATH' ) || exit;

$govalid_api   = new GoValid_QR_API();
$govalid_stats = $govalid_api->get_dashboard_stats();

if ( is_wp_error( $govalid_stats ) ) :
	?>
	<p class="govalid-widget-error">
		<?php esc_html_e( 'Unable to load stats. Please check your GoValid connection.', 'govalid-qr-validator' ); ?>
	</p>
	<?php
	return;
endif;

$govalid_total_qr    = isset( $govalid_stats['total_qr_codes'] ) ? absint( $govalid_stats['total_qr_codes'] ) : 0;
$govalid_total_scans = isset( $govalid_stats['total_scans'] ) ? absint( $govalid_stats['total_scans'] ) : 0;
$govalid_recent      = isset( $govalid_stats['recent_scans'] ) ? (array) $govalid_stats['recent_scans'] : array();
?>
<div class="govalid-dashboard-widget">
	<div class="govalid-stats-grid">
		<div class="govalid-stat">
			<span class="govalid-stat-number"><?php echo esc_html( number_format_i18n( $govalid_total_qr ) ); ?></span>
			<span class="govalid-stat-label"><?php esc_html_e( 'QR Codes', 'govalid-qr-validator' ); ?></span>
		</div>
		<div class="govalid-stat">
			<span class="govalid-stat-number"><?php echo esc_html( number_format_i18n( $govalid_total_scans ) ); ?></span>
			<span class="govalid-stat-label"><?php esc_html_e( 'Total Scans', 'govalid-qr-validator' ); ?></span>
		</div>
	</div>

	<?php if ( ! empty( $govalid_recent ) ) : ?>
		<h4><?php esc_html_e( 'Recent Scans', 'govalid-qr-validator' ); ?></h4>
		<ul class="govalid-recent-scans">
			<?php foreach ( array_slice( $govalid_recent, 0, 5 ) as $govalid_scan ) : ?>
				<li>
					<strong><?php echo esc_html( $govalid_scan['qr_name'] ?? '' ); ?></strong>
					<span class="govalid-scan-meta">
						<?php echo esc_html( $govalid_scan['location'] ?? '' ); ?>
						&mdash;
						<?php echo esc_html( $govalid_scan['scanned_at'] ?? '' ); ?>
					</span>
				</li>
			<?php endforeach; ?>
		</ul>
	<?php endif; ?>

	<p class="govalid-widget-footer">
		<a href="<?php echo esc_url( GoValid_QR::get_base_url() . '/dashboard/' ); ?>" target="_blank">
			<?php esc_html_e( 'View All in GoValid', 'govalid-qr-validator' ); ?> &rarr;
		</a>
	</p>
</div>
