<?php
/**
 * GoValid QR Code Verification Page Template.
 *
 * Rendered when a visitor hits /v/{token} on the WordPress site.
 *
 * @package GoValid_QR
 */

defined( 'ABSPATH' ) || exit;

$govalid_verify_token = sanitize_text_field( get_query_var( 'govalid_verify_token', '' ) );
$govalid_verify_token = rtrim( $govalid_verify_token, '/' );
$govalid_base_url     = GoValid_QR::get_base_url();
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
	<meta charset="<?php bloginfo( 'charset' ); ?>">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="robots" content="noindex, nofollow">
	<title><?php echo esc_html__( 'QR Code Verification', 'govalid-qr' ) . ' - ' . esc_html( get_bloginfo( 'name' ) ); ?></title>
	<?php wp_head(); ?>
</head>
<body <?php body_class( 'govalid-verify-page' ); ?>>

<div class="govalid-verify-wrapper">
	<div class="govalid-verify-card">
		<div class="govalid-verify-header">
			<h1><?php esc_html_e( 'QR Code Verification', 'govalid-qr' ); ?></h1>
			<p><?php echo esc_html( get_bloginfo( 'name' ) ); ?></p>
		</div>

		<div class="govalid-verify-body">
			<!-- Loading -->
			<div id="govalid-verify-loading" class="govalid-verify-loading">
				<div class="govalid-verify-spinner"></div>
				<p><?php esc_html_e( 'Verifying QR code...', 'govalid-qr' ); ?></p>
			</div>

			<!-- Result -->
			<div id="govalid-verify-result" class="govalid-verify-result">
				<div id="govalid-verify-status" class="govalid-verify-status">
					<div class="govalid-verify-status-icon"></div>
					<h2 id="govalid-verify-status-text"></h2>
					<p class="govalid-verify-subtitle" id="govalid-verify-status-sub"></p>
				</div>

				<table class="govalid-verify-details">
					<tr id="govalid-row-name">
						<th><?php esc_html_e( 'QR Name', 'govalid-qr' ); ?></th>
						<td id="govalid-verify-name"></td>
					</tr>
					<tr id="govalid-row-type">
						<th><?php esc_html_e( 'Type', 'govalid-qr' ); ?></th>
						<td id="govalid-verify-type"></td>
					</tr>
					<tr id="govalid-row-creator">
						<th><?php esc_html_e( 'Created by', 'govalid-qr' ); ?></th>
						<td id="govalid-verify-creator"></td>
					</tr>
					<tr id="govalid-row-institution">
						<th><?php esc_html_e( 'Institution', 'govalid-qr' ); ?></th>
						<td id="govalid-verify-institution"></td>
					</tr>
					<tr id="govalid-row-scans">
						<th><?php esc_html_e( 'Scan count', 'govalid-qr' ); ?></th>
						<td id="govalid-verify-scans"></td>
					</tr>
					<tr id="govalid-row-status">
						<th><?php esc_html_e( 'Status', 'govalid-qr' ); ?></th>
						<td id="govalid-verify-active"></td>
					</tr>
					<tr id="govalid-row-created">
						<th><?php esc_html_e( 'Created', 'govalid-qr' ); ?></th>
						<td id="govalid-verify-created"></td>
					</tr>
				</table>

				<div id="govalid-verify-violations" class="govalid-verify-violations" style="display:none;">
					<h3><?php esc_html_e( 'Security Alerts', 'govalid-qr' ); ?></h3>
					<div id="govalid-violations-list"></div>
				</div>
			</div>

			<!-- Error -->
			<div id="govalid-verify-error" class="govalid-verify-error">
				<div class="govalid-verify-error-icon">
					<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<circle cx="12" cy="12" r="10"></circle>
						<line x1="12" y1="8" x2="12" y2="12"></line>
						<line x1="12" y1="16" x2="12.01" y2="16"></line>
					</svg>
				</div>
				<h2 id="govalid-error-title"><?php esc_html_e( 'Verification Failed', 'govalid-qr' ); ?></h2>
				<p id="govalid-error-message"><?php esc_html_e( 'Unable to verify this QR code. It may be invalid or expired.', 'govalid-qr' ); ?></p>
			</div>
		</div>

		<?php if ( get_option( 'govalid_qr_show_powered_by', '' ) === '1' ) : ?>
		<div class="govalid-verify-footer">
			<a href="https://govalid.org" target="_blank" rel="noopener" class="govalid-powered-by">
				<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="20" height="20">
					<circle cx="128" cy="128" r="128" fill="#4169E1"/>
					<path fill="#ffffff" fill-rule="evenodd" d="M225.86,102.82c-3.77-3.94-7.67-8-9.14-11.57-1.36-3.27-1.44-8.69-1.52-13.94-.15-9.76-.31-20.82-8-28.51s-18.75-7.85-28.51-8c-5.25-.08-10.67-.16-13.94-1.52-3.56-1.47-7.63-5.37-11.57-9.14C146.28,23.51,138.44,16,128,16s-18.27,7.51-25.18,14.14c-3.94,3.77-8,7.67-11.57,9.14C88,40.64,82.56,40.72,77.31,40.8c-9.76.15-20.82.31-28.51,8S41,67.55,40.8,77.31c-.08,5.25-.16,10.67-1.52,13.94-1.47,3.56-5.37,7.63-9.14,11.57C23.51,109.72,16,117.56,16,128s7.51,18.27,14.14,25.18c3.77,3.94,7.67,8,9.14,11.57,1.36,3.27,1.44,8.69,1.52,13.94.15,9.76.31,20.82,8,28.51s18.75,7.85,28.51,8c5.25.08,10.67.16,13.94,1.52,3.56,1.47,7.63,5.37,11.57,9.14C109.72,232.49,117.56,240,128,240s18.27-7.51,25.18-14.14c3.94-3.77,8-7.67,11.57-9.14,3.27-1.36,8.69-1.44,13.94-1.52,9.76-.15,20.82-.31,28.51-8s7.85-18.75,8-28.51c.08-5.25.16-10.67,1.52-13.94,1.47-3.56,5.37-7.63,9.14-11.57C232.49,146.28,240,138.44,240,128S232.49,109.73,225.86,102.82Zm-52.2,6.84-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35a8,8,0,0,1,11.32,11.32Z"/>
				</svg>
				<?php echo esc_html__( 'Powered by', 'govalid-qr' ); ?>
				<span>GoValid</span>
			</a>
		</div>
		<?php endif; ?>
	</div>
</div>

<script>
(function() {
	var token  = <?php echo wp_json_encode( $govalid_verify_token ); ?>;
	var apiUrl = <?php echo wp_json_encode( esc_url_raw( $govalid_base_url . '/api/v1/ojs/verify-signed/?token=' . rawurlencode( $govalid_verify_token ) ) ); ?>;

	var loadingEl = document.getElementById( 'govalid-verify-loading' );
	var resultEl  = document.getElementById( 'govalid-verify-result' );
	var errorEl   = document.getElementById( 'govalid-verify-error' );

	if ( ! token ) {
		showError(
			<?php echo wp_json_encode( __( 'No Token Provided', 'govalid-qr' ) ); ?>,
			<?php echo wp_json_encode( __( 'No QR code token was found in the URL.', 'govalid-qr' ) ); ?>
		);
		return;
	}

	var xhr = new XMLHttpRequest();
	xhr.open( 'GET', apiUrl, true );
	xhr.timeout = 15000;

	xhr.onload = function() {
		if ( xhr.status === 200 ) {
			try {
				var raw = JSON.parse( xhr.responseText );
				var data = raw.content ? raw.content : raw;
				if ( data.success && data.verified ) {
					showResult( data );
				} else {
					showError(
						<?php echo wp_json_encode( __( 'QR Code Not Verified', 'govalid-qr' ) ); ?>,
						data.message || <?php echo wp_json_encode( __( 'This QR code could not be verified.', 'govalid-qr' ) ); ?>
					);
				}
			} catch ( e ) {
				showError(
					<?php echo wp_json_encode( __( 'Verification Error', 'govalid-qr' ) ); ?>,
					<?php echo wp_json_encode( __( 'An error occurred while processing the verification response.', 'govalid-qr' ) ); ?>
				);
			}
		} else if ( xhr.status === 404 ) {
			showError(
				<?php echo wp_json_encode( __( 'QR Code Not Found', 'govalid-qr' ) ); ?>,
				<?php echo wp_json_encode( __( 'This QR code was not found in the GoValid system.', 'govalid-qr' ) ); ?>
			);
		} else if ( xhr.status === 429 ) {
			showError(
				<?php echo wp_json_encode( __( 'Too Many Requests', 'govalid-qr' ) ); ?>,
				<?php echo wp_json_encode( __( 'Please wait a moment and try again.', 'govalid-qr' ) ); ?>
			);
		} else {
			showError(
				<?php echo wp_json_encode( __( 'Verification Failed', 'govalid-qr' ) ); ?>,
				<?php echo wp_json_encode( __( 'Unable to verify this QR code. Please try again later.', 'govalid-qr' ) ); ?>
			);
		}
	};

	xhr.onerror = function() {
		showError(
			<?php echo wp_json_encode( __( 'Connection Error', 'govalid-qr' ) ); ?>,
			<?php echo wp_json_encode( __( 'Unable to connect to the verification server. Please check your internet connection.', 'govalid-qr' ) ); ?>
		);
	};

	xhr.ontimeout = function() {
		showError(
			<?php echo wp_json_encode( __( 'Request Timeout', 'govalid-qr' ) ); ?>,
			<?php echo wp_json_encode( __( 'The verification request timed out. Please try again.', 'govalid-qr' ) ); ?>
		);
	};

	xhr.send();

	function showResult( data ) {
		loadingEl.style.display = 'none';
		resultEl.style.display  = 'block';

		var qr      = data.qr_code || {};
		var creator = data.creator || {};
		var ac      = data.anti_counterfeit || {};
		var hasViolations = ac.has_violations || false;

		var statusEl   = document.getElementById( 'govalid-verify-status' );
		var statusIcon = statusEl.querySelector( '.govalid-verify-status-icon' );
		var statusText = document.getElementById( 'govalid-verify-status-text' );
		var statusSub  = document.getElementById( 'govalid-verify-status-sub' );

		if ( hasViolations && ac.action === 'block' ) {
			statusEl.className = 'govalid-verify-status counterfeit';
			statusIcon.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>';
			statusText.textContent = <?php echo wp_json_encode( __( 'Counterfeit Detected', 'govalid-qr' ) ); ?>;
			statusSub.textContent  = <?php echo wp_json_encode( __( 'This QR code has security violations.', 'govalid-qr' ) ); ?>;
		} else if ( hasViolations ) {
			statusEl.className = 'govalid-verify-status inactive';
			statusIcon.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>';
			statusText.textContent = <?php echo wp_json_encode( __( 'Verified with Warnings', 'govalid-qr' ) ); ?>;
			statusSub.textContent  = <?php echo wp_json_encode( __( 'This QR code is valid but has security warnings.', 'govalid-qr' ) ); ?>;
		} else if ( ! qr.is_active ) {
			statusEl.className = 'govalid-verify-status inactive';
			statusIcon.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>';
			statusText.textContent = <?php echo wp_json_encode( __( 'QR Code Inactive', 'govalid-qr' ) ); ?>;
			statusSub.textContent  = <?php echo wp_json_encode( __( 'This QR code has been deactivated by its owner.', 'govalid-qr' ) ); ?>;
		} else {
			statusEl.className = 'govalid-verify-status verified';
			statusIcon.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>';
			statusText.textContent = <?php echo wp_json_encode( __( 'Verified Authentic', 'govalid-qr' ) ); ?>;
			statusSub.textContent  = <?php echo wp_json_encode( __( 'This QR code is genuine and active.', 'govalid-qr' ) ); ?>;
		}

		setText( 'govalid-verify-name', qr.name || '-' );
		setText( 'govalid-verify-type', formatType( qr.qr_type, qr.template_type ) );
		setText( 'govalid-verify-scans', ( qr.scan_count || 0 ).toLocaleString() );

		var creatorName = creator.full_name || creator.username || '-';
		if ( creator.is_verified || creator.staff_verified ) creatorName += ' \u2713';
		setText( 'govalid-verify-creator', creatorName );

		if ( creator.institution_name ) {
			setText( 'govalid-verify-institution', creator.institution_name );
		} else {
			hideRow( 'govalid-row-institution' );
		}

		var activeEl = document.getElementById( 'govalid-verify-active' );
		if ( qr.is_active ) {
			activeEl.innerHTML = '<span class="govalid-verify-badge active">' + escapeHtml( <?php echo wp_json_encode( __( 'Active', 'govalid-qr' ) ); ?> ) + '</span>';
		} else {
			activeEl.innerHTML = '<span class="govalid-verify-badge inactive">' + escapeHtml( <?php echo wp_json_encode( __( 'Inactive', 'govalid-qr' ) ); ?> ) + '</span>';
		}

		if ( qr.created_at ) {
			setText( 'govalid-verify-created', new Date( qr.created_at ).toLocaleDateString( undefined, { year: 'numeric', month: 'long', day: 'numeric' } ) );
		} else {
			hideRow( 'govalid-row-created' );
		}

		if ( hasViolations && ac.violations && ac.violations.length > 0 ) {
			document.getElementById( 'govalid-verify-violations' ).style.display = 'block';
			var listEl = document.getElementById( 'govalid-violations-list' );
			var html = '';
			for ( var i = 0; i < ac.violations.length; i++ ) {
				var v = ac.violations[i];
				html += '<div class="govalid-verify-violation-item"><strong>' + escapeHtml( v.title || v.type ) + '</strong>';
				if ( v.message ) html += escapeHtml( v.message );
				html += '</div>';
			}
			listEl.innerHTML = html;
		}
	}

	function showError( title, message ) {
		loadingEl.style.display = 'none';
		errorEl.style.display   = 'block';
		document.getElementById( 'govalid-error-title' ).textContent   = title;
		document.getElementById( 'govalid-error-message' ).textContent = message;
	}

	function setText( id, text ) {
		var el = document.getElementById( id );
		if ( el ) el.textContent = text;
	}

	function hideRow( id ) {
		var el = document.getElementById( id );
		if ( el ) el.style.display = 'none';
	}

	function formatType( qrType, templateType ) {
		var types = { url: 'URL', vcard: 'vCard', wifi: 'WiFi', text: 'Text', email: 'Email', sms: 'SMS', phone: 'Phone', location: 'Location' };
		return types[ qrType ] || qrType || templateType || '-';
	}

	function escapeHtml( str ) {
		var d = document.createElement( 'div' );
		d.appendChild( document.createTextNode( str ) );
		return d.innerHTML;
	}
})();
</script>

<?php wp_footer(); ?>
</body>
</html>
