<?php

namespace CelerSearch\Views;

defined( 'ABSPATH' ) || exit;

/**
 * Template loading with theme override support
 *
 * Priority: child theme > parent theme > plugin templates.
 * Theme templates go in: yourtheme/celersearch/views/{template}.php
 */
class ViewRenderer {

	/**
	 * Plugin template directory (relative to plugin root)
	 */
	const PLUGIN_TEMPLATE_DIR = 'templates/views';

	/**
	 * Theme template directory
	 */
	const THEME_TEMPLATE_DIR = 'celersearch/views';

	/**
	 * Render a template and return the output
	 *
	 * @param string        $template Template path relative to views dir (e.g. 'search/search').
	 * @param array         $args     Variables to pass to the template.
	 * @param AbstractView|null $view The view instance rendering this template.
	 *
	 * @return string
	 */
	public static function render( string $template, array $args = [], ?AbstractView $view = null ): string {
		$file = self::locate_template( $template );

		if ( ! $file ) {
			return '';
		}

		ob_start();

		$template_args = $args;
		unset( $args );

		include $file;

		$html = ob_get_clean();

		/**
		 * Filter the rendered template HTML
		 *
		 * @param string             $html          The rendered HTML.
		 * @param string             $template      Template name.
		 * @param AbstractView|null  $view          The view instance.
		 */
		return apply_filters( 'celersearch_view_template_html', $html, $template, $view );
	}

	/**
	 * Locate a template file with theme override priority
	 *
	 * @param string $template Template path (without .php).
	 *
	 * @return string|null Full path to template or null if not found.
	 */
	public static function locate_template( string $template ): ?string {
		$template_file = $template . '.php';

		$locations = [
			get_stylesheet_directory() . '/' . self::THEME_TEMPLATE_DIR . '/' . $template_file,
			get_template_directory() . '/' . self::THEME_TEMPLATE_DIR . '/' . $template_file,
			\CELERSEARCH_PLUGIN_PATH . self::PLUGIN_TEMPLATE_DIR . '/' . $template_file,
		];

		/**
		 * Filter template lookup locations
		 *
		 * @param array  $locations List of file paths to check.
		 * @param string $template  Template name.
		 */
		$locations = apply_filters( 'celersearch_view_template_path', $locations, $template );

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

		return null;
	}
}
