<?php

declare(strict_types=1);

namespace MyCustomizer\WooCommerce\Connector\Controller;

use MyCustomizer\WooCommerce\Connector\Libs\MczrPathResolver;
use WP_Post;

class MczrTemplateController
{
    /** @var MczrPathResolver */
    private $resolver;

    public function __construct()
    {
        $this->resolver = new MczrPathResolver();
    }

    public function init(): void
    {
        \add_filter('woocommerce_locate_template', [$this, 'mczrLocateTemplate'], 10, 3);
    }
    /*
     * For Mczr products type, Mczr templates takes precedence over
     * WooCommerce ones.
     * Look in : current theme folder or fallback to Mczr plugin templates.
     * This will not look in WooCommerce templates.
     * add_action('mczrIframe') to display Mczr iframe wherever you want.
     */

    public function mczrLocateTemplate(string $template, string $templateName, string $_templatePath): string
    {
        global $post;

        if (!$post instanceof WP_Post) {
            return $template;
        }

        $product = \wc_get_product();

        if (!$product instanceof \WC_Product) {
            return $template;
        }

        // This filter only apply on mczr product type
        if ('product' !== $post->post_type || !$product->is_type('mczr')) {
            return $template;
        }
        $pluginPath = $this->resolver->plugin() . '/src/Resources/MyCustomizer/';
        $themePath = $this->resolver->theme() . '/MyCustomizer';

        // Theme always takes precedence
        if (is_file("$themePath/$templateName")) {
            return "$themePath/$templateName";
        }

        if (is_file("$pluginPath/$templateName")) {
            return "$pluginPath/$templateName";
        }

        return $template;
    }
}
