<?php
/**
 * Smart Verify widget shortcode and floating widget.
 *
 * [govalid_verify] — inline verify widget
 * Floating FAB — enabled via settings (appears on all public pages)
 *
 * @package GoValid_QR
 */

defined( 'ABSPATH' ) || exit;

class GoValid_Verify_Shortcode {

	/** @var bool Track if assets are already enqueued. */
	private static $assets_enqueued = false;

	/**
	 * Register shortcode and floating widget hooks.
	 */
	public function register(): void {
		add_shortcode( 'govalid_verify', array( $this, 'render_shortcode' ) );

		// Floating widget on frontend (if enabled).
		add_action( 'wp_footer', array( $this, 'maybe_render_floating_widget' ) );
	}

	/**
	 * Render inline verify widget via shortcode.
	 *
	 * Usage: [govalid_verify position="inline" title="Verify QR Code"]
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string HTML.
	 */
	public function render_shortcode( $atts ): string {
		$atts = shortcode_atts( array(
			'title' => __( 'Smart Verify', 'govalid-qr-validator' ),
		), $atts, 'govalid_verify' );

		$this->enqueue_assets();

		$title = $atts['title'];
		$base  = GoValid_QR::get_base_url();

		ob_start();
		?>
		<div class="govalid-sv-inline" data-govalid-base="<?php echo esc_url( $base ); ?>">
			<div class="govalid-sv-panel govalid-sv-panel-inline open">
				<div class="govalid-sv-header">
					<div class="govalid-sv-title">
						<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
							<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>
						<?php echo esc_html( $title ); ?>
					</div>
				</div>
				<?php $this->render_widget_body(); ?>
				<?php $this->render_widget_footer(); ?>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Render floating FAB widget in footer if enabled.
	 */
	public function maybe_render_floating_widget(): void {
		if ( is_admin() ) {
			return;
		}

		$enabled = get_option( 'govalid_qr_floating_verify', '1' );
		if ( '1' !== $enabled ) {
			return;
		}

		$this->enqueue_assets();

		$position = get_option( 'govalid_qr_verify_position', 'bottom-right' );
		$position = in_array( $position, array( 'bottom-right', 'bottom-left', 'top-right', 'top-left' ), true )
			? $position : 'bottom-right';
		$base = GoValid_QR::get_base_url();
		?>
		<div id="govalid-smart-verify-widget" class="govalid-sv-widget govalid-sv-<?php echo esc_attr( $position ); ?>"
			 data-govalid-base="<?php echo esc_url( $base ); ?>">
			<button id="govalid-sv-toggle" class="govalid-sv-toggle"
					title="<?php esc_attr_e( 'Verify QR Code', 'govalid-qr-validator' ); ?>">
				<svg width="24" height="24" 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>
			</button>
			<div id="govalid-sv-panel" class="govalid-sv-panel">
				<div class="govalid-sv-header">
					<div class="govalid-sv-title">
						<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
							<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>
						<?php esc_html_e( 'Smart Verify', 'govalid-qr-validator' ); ?>
					</div>
					<button id="govalid-sv-close" class="govalid-sv-close">&times;</button>
				</div>
				<?php $this->render_widget_body(); ?>
				<?php $this->render_widget_footer(); ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the widget body (tabs + content). Shared by inline and floating.
	 */
	private function render_widget_body(): void {
		?>
		<div class="govalid-sv-body">
			<div class="govalid-sv-tabs">
				<button class="govalid-sv-tab active" data-tab="qr-id"><?php esc_html_e( 'QR ID', 'govalid-qr-validator' ); ?></button>
				<button class="govalid-sv-tab" data-tab="camera"><?php esc_html_e( 'Camera', 'govalid-qr-validator' ); ?></button>
				<button class="govalid-sv-tab" data-tab="upload"><?php esc_html_e( 'Upload', 'govalid-qr-validator' ); ?></button>
			</div>

			<!-- QR ID tab -->
			<div class="govalid-sv-tab-content active" data-tab-content="qr-id">
				<div class="govalid-sv-input-group">
					<input type="text" class="govalid-sv-input govalid-sv-qr-input"
						   placeholder="<?php esc_attr_e( 'Enter QR ID (e.g., 1ACE-DO-abc123)', 'govalid-qr-validator' ); ?>" />
					<button class="govalid-sv-btn-primary govalid-sv-search-btn">
						<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
							<circle cx="11" cy="11" r="8"></circle>
							<path d="m21 21-4.35-4.35"></path>
						</svg>
					</button>
				</div>
				<div class="govalid-sv-hint"><?php esc_html_e( 'Format: XXXX-XX-xxxxxxxx or XXXXXXxxxxxxxx', 'govalid-qr-validator' ); ?></div>
			</div>

			<!-- Camera tab -->
			<div class="govalid-sv-tab-content" data-tab-content="camera">
				<div class="govalid-sv-camera-container">
					<video class="govalid-sv-camera-video" playsinline></video>
					<canvas class="govalid-sv-camera-canvas" style="display:none;"></canvas>
					<div class="govalid-sv-camera-overlay">
						<div class="govalid-sv-scan-region"></div>
					</div>
				</div>
				<div class="govalid-sv-camera-controls">
					<button class="govalid-sv-btn-primary govalid-sv-camera-start">
						<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
							<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path>
							<circle cx="12" cy="13" r="4"></circle>
						</svg>
						<?php esc_html_e( 'Start Camera', 'govalid-qr-validator' ); ?>
					</button>
					<button class="govalid-sv-btn-secondary govalid-sv-camera-stop" style="display:none;">
						<?php esc_html_e( 'Stop', 'govalid-qr-validator' ); ?>
					</button>
				</div>
				<div class="govalid-sv-camera-status"></div>
			</div>

			<!-- Upload tab -->
			<div class="govalid-sv-tab-content" data-tab-content="upload">
				<div class="govalid-sv-dropzone">
					<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
						<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
						<polyline points="17 8 12 3 7 8"></polyline>
						<line x1="12" y1="3" x2="12" y2="15"></line>
					</svg>
					<span><?php esc_html_e( 'Drop image here or click to upload', 'govalid-qr-validator' ); ?></span>
					<input type="file" class="govalid-sv-file-input" accept="image/*" style="display:none;" />
				</div>
				<div class="govalid-sv-preview" style="display:none;">
					<img class="govalid-sv-preview-img" src="" alt="<?php esc_attr_e( 'Preview', 'govalid-qr-validator' ); ?>" />
					<button class="govalid-sv-btn-secondary govalid-sv-clear-preview"><?php esc_html_e( 'Clear', 'govalid-qr-validator' ); ?></button>
				</div>
			</div>

			<!-- Results area -->
			<div class="govalid-sv-results" style="display:none;">
				<div class="govalid-sv-loading" style="display:none;">
					<div class="govalid-sv-spinner"></div>
					<span><?php esc_html_e( 'Verifying...', 'govalid-qr-validator' ); ?></span>
				</div>
				<div class="govalid-sv-result-content"></div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the widget footer.
	 */
	private function render_widget_footer(): void {
		?>
		<?php if ( get_option( 'govalid_qr_show_powered_by', '' ) === '1' ) : ?>
		<div class="govalid-sv-footer">
			<a href="https://govalid.org" target="_blank" rel="noopener" class="govalid-sv-powered">
				<?php
				printf(
					/* translators: %s: GoValid brand name */
					esc_html__( 'Powered by %s', 'govalid-qr-validator' ),
					'<strong>GoValid</strong>'
				);
				?>
			</a>
		</div>
		<?php endif; ?>
		<?php
	}

	/**
	 * Enqueue frontend assets (once).
	 */
	private function enqueue_assets(): void {
		if ( self::$assets_enqueued ) {
			return;
		}
		self::$assets_enqueued = true;

		wp_enqueue_style(
			'govalid-verify-widget',
			GOVALID_QR_PLUGIN_URL . 'public/css/smart-verify-widget.css',
			array(),
			GOVALID_QR_VERSION
		);

		// jsQR library for client-side QR decoding.
		wp_enqueue_script(
			'jsqr',
			GOVALID_QR_PLUGIN_URL . 'public/js/jsqr.min.js',
			array(),
			'1.4.0',
			true
		);

		wp_enqueue_script(
			'govalid-verify-widget',
			GOVALID_QR_PLUGIN_URL . 'public/js/smart-verify-widget.js',
			array( 'jsqr' ),
			GOVALID_QR_VERSION,
			true
		);

		wp_localize_script( 'govalid-verify-widget', 'govalidVerify', array(
			'baseUrl' => GoValid_QR::get_base_url(),
			'i18n'    => array(
				'searching'         => __( 'Searching...', 'govalid-qr-validator' ),
				'verifying'         => __( 'Verifying...', 'govalid-qr-validator' ),
				'scanning'          => __( 'Scanning for QR code...', 'govalid-qr-validator' ),
				'qr_detected'       => __( 'QR code detected!', 'govalid-qr-validator' ),
				'camera_starting'   => __( 'Starting camera...', 'govalid-qr-validator' ),
				'camera_denied'     => __( 'Camera access denied or not available', 'govalid-qr-validator' ),
				'camera_unsupported' => __( 'Camera not supported on this device', 'govalid-qr-validator' ),
				'not_govalid'       => __( 'This is not a GoValid QR code', 'govalid-qr-validator' ),
				'not_found'         => __( 'QR code not found', 'govalid-qr-validator' ),
				'no_qr_detected'    => __( 'No QR code detected in the image', 'govalid-qr-validator' ),
				'failed_decode'     => __( 'Failed to decode QR code', 'govalid-qr-validator' ),
				'failed_search'     => __( 'Failed to search. Please try again.', 'govalid-qr-validator' ),
				'failed_load_image' => __( 'Failed to load image', 'govalid-qr-validator' ),
				'enter_qr_id'      => __( 'Please enter a QR ID', 'govalid-qr-validator' ),
				'valid'             => __( 'Valid', 'govalid-qr-validator' ),
				'inactive'          => __( 'Inactive', 'govalid-qr-validator' ),
				'counterfeit'       => __( 'Potentially Counterfeit', 'govalid-qr-validator' ),
				'suspicious'        => __( 'Warning: Suspicious Activity', 'govalid-qr-validator' ),
				'govalid_qr'        => __( 'GoValid QR Code', 'govalid-qr-validator' ),
				'govalid_detected'  => __( 'GoValid QR Code Detected', 'govalid-qr-validator' ),
				'verify_on_govalid' => __( 'Verify on GoValid', 'govalid-qr-validator' ),
				'view_details'      => __( 'View Full Details', 'govalid-qr-validator' ),
				'name'              => __( 'Name:', 'govalid-qr-validator' ),
				'qr_id'             => __( 'QR ID:', 'govalid-qr-validator' ),
				'type'              => __( 'Type:', 'govalid-qr-validator' ),
				'generated_by'      => __( 'Generated by:', 'govalid-qr-validator' ),
				'institution'       => __( 'Institution:', 'govalid-qr-validator' ),
				'scans'             => __( 'Scans:', 'govalid-qr-validator' ),
			),
		) );
	}
}
