<?php
namespace Pay4All\Pro\Frontend;

use Pay4All\Pro\Domain\Ticket;
use Pay4All\Pro\License\LicenseManager;

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

/**
 * Issues one ticket row per seat sold whenever the free plugin fires
 * `p4all_after_order_created`. The hook payload carries the line items,
 * so we don't have to touch the order-storage layer — Order::customer()
 * is fetched from the free plugin's Domain\Order to hydrate the
 * ticket's `customer_data` blob (rendered on the validation page).
 *
 * Runs unconditionally when the licence check passes; on an expired
 * trial the ticket rows just don't get created and the merchant's
 * Billets admin list stays empty. Existing tickets are unaffected.
 */
final class TicketIssuer {

	public static function register() : void {
		add_action( 'p4all_after_order_created', [ self::class, 'issue_tickets' ], 10, 2 );
	}

	/**
	 * @param int                     $order_id
	 * @param array<string,mixed>     $context [ 'form_id', 'payment_method', 'total', 'items' ]
	 */
	public static function issue_tickets( int $order_id, array $context ) : void {
		if ( ! LicenseManager::is_feature_allowed() ) { return; }

		$items = (array) ( $context['items'] ?? [] );
		if ( empty( $items ) ) { return; }

		// Order::customer() reads the customer meta the free plugin already
		// persisted at Submission time. Keeping this fetch lazy avoids a
		// round-trip when the order has no ticket lines.
		$customer = class_exists( '\\Pay4All\\Form\\Domain\\Order' )
			? (array) \Pay4All\Form\Domain\Order::customer( $order_id )
			: [];

		foreach ( $items as $it ) {
			$pid = (int) ( $it['product_id'] ?? 0 );
			$qty = (int) ( $it['qty']        ?? 0 );
			if ( $pid <= 0 || $qty <= 0 ) { continue; }
			if ( ! class_exists( '\\Pay4All\\Form\\Domain\\Product' ) ) { continue; }
			if ( \Pay4All\Form\Domain\Product::type( $pid ) !== \Pay4All\Form\Domain\Product::TYPE_TICKET ) { continue; }
			// One ticket per seat sold. Ticket::create() generates a fresh
			// 40-char token per row (short URL uses an 18-char prefix).
			for ( $i = 0; $i < $qty; $i++ ) {
				Ticket::create( $order_id, $pid, $customer );
			}
		}
	}
}
