<?php

namespace WPIS;

class ThemeTemplateResolver
{
    public static function resolve(string $themeRelativePath, string $pluginAbsolutePath, string $filterName): string
    {
        $candidates = [get_stylesheet_directory()];

        if (get_stylesheet_directory() !== get_template_directory()) {
            $candidates[] = get_template_directory();
        }

        $path = $pluginAbsolutePath;

        foreach ($candidates as $directory) {
            $themePath = $directory . '/' . $themeRelativePath;

            if (file_exists($themePath)) {
                $path = $themePath;
                break;
            }
        }

        return apply_filters($filterName, $path, $themeRelativePath);
    }
}
