<?php
/**
 * A class for generating the download url for the eticket(s).
 *
 * @since 1.0
 */

declare( strict_types=1 );
namespace FeData\FastEvents\Hooks\Shortcodes;

defined( 'ABSPATH' ) || exit;

use FeData\FastEvents\Logging\LoggerFactory;


/**
 * A class for generating the download url for the eticket(s).
 */
final class DownloadShortcode {

	/**
	 * OrderPageShortcode constructor.
	 *
	 * @since 3.0.0
	 *
	 * @param LoggerFactory $logger Logger.
	 */
	public function __construct( private readonly LoggerFactory $logger ) {
	}

	/**
	 * Generate the download url for the eticket(s)
	 *
	 * @since 1.0
	 * @since 1.3 uid is added as an optional parameter
	 * @since 2.5.0 the client now generates the Qrcode
	 *
	 * @param array $atts   Download shortcode attributes ('showimage' and 'downloadtext').
	 * @return string
	 */
	public function add_download_url( array $atts ): string {
		global $wpdb;
		global $wp_query;

		// Is the uid set as a shortcode-parameter or as URL parameter?
		if ( isset( $atts['uid'] ) ) {
			$uid = $atts['uid'];
		} elseif ( ! isset( $wp_query->query_vars['redirect_uid'] ) ) {
			return '';
		} else {
			$uid = $wp_query->query_vars['redirect_uid'];
		}

		$order = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT id, created_at, num_tickets FROM {$wpdb->prefix}fe_event_orders WHERE uid = %s",
				sanitize_text_field( $uid )
			)
		);

		if ( null === $order ) {
			return '';
		}

		// Check params.
		$a = shortcode_atts(
			array(
				'showimage'    => 'no',
				'downloadtext' => esc_html__( 'Download eticket(s)', 'fast-events' ),
			),
			$atts
		);

		// Only show the image if there is only 1 ticket.
		$html = '';
		if ( 'yes' === $a['showimage'] && 1 === (int) $order->num_tickets ) {

			$ticket = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT qrcode FROM {$wpdb->prefix}fe_event_qrcodes WHERE order_id = %d",
					(int) $order->id
				)
			);

			if ( null !== $ticket ) {
				$html .= '<div id="fe_qrcode_id"></div>' . PHP_EOL;
				$html .= '<script src="' . plugins_url( '../assets/js/qrcode.min.js', __FILE__ ) . '?ver=1.0.0"></script>' . PHP_EOL; // phpcs:ignore
				$html .= '<script type="text/javascript">' . PHP_EOL;
				$html .= 'new QRCode(document.getElementById("fe_qrcode_id"), {text:"' . $ticket->qrcode . '",width:128,height:128});' . PHP_EOL;
				$html .= '</script>' . PHP_EOL;
			}
		}

		// Generate the link.
		$html .=
			'<a href="' . home_url() . '/wp-json/fast-events/v1/tickets/' .
			sanitize_text_field( $uid ) .
			'" rel="noreferrer noopener">' .
			htmlspecialchars( $a['downloadtext'] ) . '</a>';

		return $html;
	}
}
