<?php
/**
 * Dompdf autoloader for Limb Chatbot plugin.
 *
 * Lazy-loads Dompdf and its dependencies (Masterminds HTML5, php-font-lib, php-svg-lib)
 * without requiring Composer. Follows the same pattern as the pdfparser autoloader.
 *
 * @package Limb_Chatbot
 * @since   1.0.0
 */

// Bail if Dompdf is already loaded (e.g. by another plugin / Composer).
if ( class_exists( 'Dompdf\Dompdf', false ) ) {
	return;
}

/**
 * PSR-4 style autoloader for Dompdf and its bundled dependencies.
 *
 * Namespace → directory mappings (relative to this file's lib/ and src/ dirs):
 *  - Dompdf\          → src/          (main library)
 *  - Dompdf\          → lib/Cpdf.php  (canvas backend, same namespace, lives in lib/)
 *  - Masterminds\     → lib/          (html5-php)
 *  - FontLib\         → lib/FontLib/  (php-font-lib)
 *  - Svg\             → lib/Svg/      (php-svg-lib)
 */
spl_autoload_register( function ( $class ) {
	// Only handle namespaces we care about.
	$namespace_map = [
		'Dompdf\\'       => null, // resolved below (src/ + lib/)
		'Masterminds\\'  => __DIR__ . '/lib/',
		'FontLib\\'      => __DIR__ . '/lib/FontLib/',
		'Svg\\'          => __DIR__ . '/lib/Svg/',
	];

	// --- Dompdf namespace (split between src/ and lib/) ---
	if ( strpos( $class, 'Dompdf\\' ) === 0 ) {
		$relative = substr( $class, 7 ); // strip "Dompdf\"
		$path     = str_replace( '\\', '/', $relative ) . '.php';

		// Try src/ first.
		$file = __DIR__ . '/src/' . $path;
		if ( file_exists( $file ) ) {
			require_once $file;
			return;
		}

		// Fallback to lib/ (Cpdf lives here).
		$file = __DIR__ . '/lib/' . $path;
		if ( file_exists( $file ) ) {
			require_once $file;
			return;
		}

		return;
	}

	// --- Masterminds namespace ---
	if ( strpos( $class, 'Masterminds\\' ) === 0 ) {
		$relative = substr( $class, 12 );
		$path     = str_replace( '\\', '/', $relative ) . '.php';
		$file     = __DIR__ . '/lib/' . $path;
		if ( file_exists( $file ) ) {
			require_once $file;
		}
		return;
	}

	// --- FontLib namespace ---
	if ( strpos( $class, 'FontLib\\' ) === 0 ) {
		$relative = substr( $class, 8 );
		$path     = str_replace( '\\', '/', $relative ) . '.php';
		$file     = __DIR__ . '/lib/FontLib/' . $path;
		if ( file_exists( $file ) ) {
			require_once $file;
		}
		return;
	}

	// --- Svg namespace ---
	if ( strpos( $class, 'Svg\\' ) === 0 ) {
		$relative = substr( $class, 4 );
		$path     = str_replace( '\\', '/', $relative ) . '.php';
		$file     = __DIR__ . '/lib/Svg/' . $path;
		if ( file_exists( $file ) ) {
			require_once $file;
		}
		return;
	}
} );

