<?php
/**
 * PDF rendering for contribution statements (Beitragsbescheinigungen).
 *
 * Local-only by design, same as Receipt Steward: member data never leaves the
 * site's server. dompdf is bundled in vendor/.
 */

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

class BSTEW_Pdf {

	/**
	 * Render one member's contribution statement to a PDF in storage.
	 *
	 * @param object $member Row from BSTEW_Store.
	 * @param string $year   e.g. '2026'.
	 * @param string $amount Formatted amount for the year.
	 * @return string Relative filename on success, '' on failure.
	 */
	public static function render_statement( $member, $year, $amount ) {
		$autoload = BSTEW_PATH . 'vendor/autoload.php';
		if ( ! file_exists( $autoload ) ) {
			return '';
		}
		require_once $autoload;

		$options = bstew_get_options();

		ob_start();
		$org = $options;
		include BSTEW_PATH . 'includes/templates/bescheinigung.php';
		$html = (string) ob_get_clean();
		if ( '' === $html ) {
			return '';
		}

		try {
			$pdf_options = new \Dompdf\Options();
			$pdf_options->set( 'isRemoteEnabled', false );
			$pdf_options->set( 'isPhpEnabled', false );
			$pdf_options->set( 'chroot', BSTEW_PATH );
			$dompdf = new \Dompdf\Dompdf( $pdf_options );
			$dompdf->loadHtml( $html, 'UTF-8' );
			$dompdf->setPaper( 'A4', 'portrait' );
			$dompdf->render();

			bstew_prepare_storage_dir();
			$file = sprintf(
				'bescheinigung-%s-%d-%s.pdf',
				sanitize_file_name( $year ),
				(int) $member->id,
				wp_generate_password( 12, false )
			);
			$path = trailingslashit( bstew_storage_dir() ) . $file;
			if ( false === file_put_contents( $path, $dompdf->output() ) ) { // phpcs:ignore
				return '';
			}
			return $file;
		} catch ( \Throwable $e ) {
			return '';
		}
	}
}
