<?php
/**
 * Shortcode handler for [govalid_qr].
 *
 * @package GoValid_QR
 */

defined( 'ABSPATH' ) || exit;

class GoValid_Shortcodes {

	/**
	 * Register shortcodes.
	 */
	public function register(): void {
		add_shortcode( 'govalid_qr', array( $this, 'render_qr_shortcode' ) );
	}

	/**
	 * Render the [govalid_qr] shortcode.
	 *
	 * Usage: [govalid_qr id="uuid" width="200" align="center" show_label="true"]
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string HTML output.
	 */
	public function render_qr_shortcode( $atts ): string {
		$atts = shortcode_atts( array(
			'id'         => '',
			'width'      => '200',
			'align'      => 'center',
			'show_label' => 'false',
		), $atts, 'govalid_qr' );

		$uuid = sanitize_text_field( $atts['id'] );
		if ( empty( $uuid ) ) {
			return $this->render_error( __( 'Missing QR code ID.', 'govalid-qr-validator' ) );
		}

		if ( ! GoValid_QR::is_connected() ) {
			return $this->render_error( __( 'GoValid is not connected.', 'govalid-qr-validator' ) );
		}

		$api    = new GoValid_QR_API();
		$qr     = $api->get_qr_detail( $uuid );

		if ( is_wp_error( $qr ) ) {
			return $this->render_error( __( 'QR code not found.', 'govalid-qr-validator' ) );
		}

		$image_url = isset( $qr['image_url'] ) ? $qr['image_url'] : '';
		if ( ! empty( $image_url ) ) {
			$image_url = $api->get_cached_image_url( $uuid, $image_url );
		}

		$width      = absint( $atts['width'] );
		$align      = in_array( $atts['align'], array( 'left', 'center', 'right' ), true ) ? $atts['align'] : 'center';
		$show_label = filter_var( $atts['show_label'], FILTER_VALIDATE_BOOLEAN );
		$qr_name    = isset( $qr['name'] ) ? $qr['name'] : '';

		$align_style = 'center' === $align ? 'margin-left:auto;margin-right:auto;' : '';
		if ( 'right' === $align ) {
			$align_style = 'margin-left:auto;';
		}

		$html = '<div class="govalid-qr-embed" style="text-align:' . esc_attr( $align ) . ';' . esc_attr( $align_style ) . '">';

		if ( ! empty( $image_url ) ) {
			$html .= '<img src="' . esc_url( $image_url ) . '"'
				. ' alt="' . esc_attr( $qr_name ) . '"'
				. ' width="' . esc_attr( $width ) . '"'
				. ' height="' . esc_attr( $width ) . '"'
				. ' loading="lazy"'
				. ' class="govalid-qr-image" />';
		}

		if ( $show_label && ! empty( $qr_name ) ) {
			$html .= '<p class="govalid-qr-label">' . esc_html( $qr_name ) . '</p>';
		}

		$html .= '</div>';

		return $html;
	}

	/**
	 * Render an error message (only visible to editors).
	 *
	 * @param string $message Error message.
	 * @return string
	 */
	private function render_error( string $message ): string {
		if ( current_user_can( 'edit_posts' ) ) {
			return '<p class="govalid-qr-error" style="color:#c00;font-style:italic;">'
				. esc_html( $message ) . '</p>';
		}
		return '';
	}
}
