<?php
/**
 * Template controller for TCPDF.
 *
 * @since 1.0
 */

declare( strict_types=1 );
namespace FeData\FastEvents\RestAPI\Public\Download;

defined( 'ABSPATH' ) || exit;

use FeData\FastEvents\Logging\LoggerFactory;
use setasign\Fpdi\Tcpdf\Fpdi;
use Throwable;

/**
 * Extend Fpdi to use templates in TCPDF.
 */
class EventPdf extends Fpdi {
	/**
	 * Template identifier.
	 *
	 * @since 1.0
	 * @var string
	 */
	private string $tpl_idx = '';


	/**
	 * Load the template PDF file.
	 *
	 * @param int $media_id The name of the template file.
	 *
	 * @since 2.2.0 Return http error 500 in case of errors.
	 *
	 * @since 1.0
	 */
	public function load_template( int $media_id ): void {
		global $fevt_container;

		$template = '';
		try {
			$template = get_attached_file( $media_id );
			if ( ! $template ) {
				$logger = $fevt_container->get( LoggerFactory::class );
				$logger->emergency(
					'Cannot find PDF template id ' . $media_id . '. Change the ticket types by selecting an existing PDF template.',
					array(
						'type'     => 'PDF',
						'media_id' => $media_id,
					)
				);
				http_response_code( 500 );
				die();
			}
			$this->setSourceFile( $template );
			$this->tpl_idx = $this->importPage( 1 );
		} catch ( Throwable $e ) {
			$logger = $fevt_container->get( LoggerFactory::class );
			$logger->emergency(
				'Pdf template: ' . $template . ', error: ' . $e->getMessage(),
				array(
					'type'     => 'PDF',
					'media_id' => $media_id,
					'template' => $template,
				)
			);
			http_response_code( 500 );
			die();
		}
	}


	/**
	 * Use the template PDF file.
	 *
	 * @since 1.0
	 */
	public function use_template(): void {
		$this->useTemplate( $this->tpl_idx );
	}


	/**
	 * Header stub.
	 *
	 * @return void
	 * @since 1.0
	 */
	public function Header(): void {}


	/**
	 * Footer stub.
	 *
	 * @return void
	 * @since 1.0
	 */
	public function Footer(): void {}
}
