<?php
/**
 * Abstract base class for plugin integrations.
 *
 * @package PDFDraft_WooCommerce
 */

namespace PDFDraft\Woocommerce\Abstracts;

use PDFDraft\Traits\Hooks;

/**
 * Base integration class providing template rendering and hook registration.
 */
abstract class AbstractIntegration {

	use Hooks;

	/**
	 * Register WordPress hooks for this integration.
	 *
	 * @return void
	 */
	abstract public function initHooks();

	/**
	 * Render a template file with the given arguments.
	 *
	 * @param string $templateName Template file name relative to templates directory.
	 * @param array  $args         Variables to extract into the template scope.
	 * @return void
	 */
	protected function renderTemplate( $templateName, $args = array() ) {
		$templatePath = $this->locateTemplate( $templateName );
		if ( $templatePath ) {
			$render = function () use ( $templatePath, $args ) {
				foreach ( $args as $key => $value ) {
					$$key = $value;
				}
				include $templatePath;
			};
			$render();
		}
	}

	/**
	 * Locate a template file checking theme directories first, then plugin directory.
	 *
	 * @param string $templateName Template file name to locate.
	 * @return string|false Full path to the template file, or false if not found.
	 */
	private function locateTemplate( $templateName ) {
		$locations = array(
			get_stylesheet_directory() . '/pdfdraft-pdf-invoices-for-woocommerce/' . $templateName,
			get_template_directory() . '/pdfdraft-pdf-invoices-for-woocommerce/' . $templateName,
			PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_DIR . '/templates/' . $templateName,
		);

		foreach ( $locations as $location ) {
			if ( file_exists( $location ) ) {
				return $location;
			}
		}

		return false;
	}
}
