<?php
namespace Pay4All\Pro\Frontend;

use Pay4All\Pro\Domain\Ticket;

if ( ! defined( 'ABSPATH' ) ) { exit; }

/**
 * Feeds the free plugin's `customer-new-order.php` template with the QR
 * codes it needs. Pay4All Form fires the `p4all_form_email_context` filter
 * with the base context (customer, items, totals, downloads, …); we look
 * up the tickets for the order via Ticket::tickets_for_order() and stuff
 * them under $ctx['tickets'] with everything the template renders — title,
 * short description, QR image URL — so the template stays namespace-agnostic
 * and doesn't have to load anything from the Pro plugin at render time.
 *
 * Runs unconditionally: the base filter payload is empty when the order has
 * no ticket rows, and the template gates the whole « Vos billets » block on
 * `! empty( $ctx['tickets'] )`.
 */
final class TicketMailContext {

	// api.qrserver.com renders at 600x600 with margin=20 + ecc=M so the QR
	// stays scannable through iPhone Mail's re-encoding pipeline (which
	// historically broke smaller/ecc=L codes on iPhone 11 + iOS 14).
	private const QR_ENDPOINT = 'https://api.qrserver.com/v1/create-qr-code/?size=600x600&margin=20&ecc=M&data=';

	public static function register() : void {
		add_filter( 'p4all_form_email_context', [ self::class, 'inject_tickets' ], 10, 3 );
	}

	/**
	 * @param array<string,mixed> $ctx
	 * @param string              $template
	 * @param int                 $order_id
	 * @return array<string,mixed>
	 */
	public static function inject_tickets( array $ctx, string $template, int $order_id ) : array {
		// Both customer-new-order and admin-new-order can benefit from
		// showing tickets — the merchant's copy references the same URLs
		// so they can spot-check that the QR codes exist.
		if ( $template !== 'customer-new-order' && $template !== 'admin-new-order' ) {
			return $ctx;
		}

		$rows = Ticket::tickets_for_order( $order_id );
		if ( empty( $rows ) ) { return $ctx; }

		$tickets = [];
		foreach ( $rows as $row ) {
			$pid   = (int) ( $row['product_id'] ?? 0 );
			$url   = Ticket::validation_url( $row );
			if ( $url === '' ) { continue; }
			$prod  = $pid > 0 ? get_post( $pid ) : null;
			$title = $prod ? get_the_title( $prod ) : (string) ( $row['product_slug'] ?? '' );
			$desc  = '';
			if ( $prod && class_exists( '\\Pay4All\\Form\\Domain\\Product' ) ) {
				$raw = (string) \Pay4All\Form\Domain\Product::short_desc( $pid );
				if ( $raw !== '' ) {
					$desc = wp_kses( $raw, \Pay4All\Form\Domain\Product::ALLOWED_SHORT_DESC_HTML );
				}
			}
			$tickets[] = [
				'id'            => (int) ( $row['id'] ?? 0 ),
				'token'         => (string) ( $row['token'] ?? '' ),
				'product_id'    => $pid,
				'product_slug'  => (string) ( $row['product_slug'] ?? '' ),
				'title'         => $title,
				'desc'          => $desc,
				'validation_url' => $url,
				'qr_url'        => self::QR_ENDPOINT . rawurlencode( $url ),
			];
		}
		if ( ! empty( $tickets ) ) {
			$ctx['tickets'] = $tickets;
		}
		return $ctx;
	}
}
