<?php

/**
 * Apply Shop Addon → Shop Details → Page Templates (Elementor library) to WooCommerce views.
 *
 * @package storzen
 */

if (! defined('ABSPATH')) {
	exit;
}

/**
 * Maps WC conditions to admin field keys (admin-panel.php templates tab).
 */
class Storzen_WC_Elementor_Templates
{

	const OPTION_KEY = 'pk_storzen_templates_page_templates';

	/** @var int Assigned shop template post ID when shell template is used. */
	private static $shop_template_id = 0;

	/** @var int Assigned single-product template post ID when shell template is used. */
	private static $single_template_id = 0;

	/** @var bool */
	private static $hooks_registered = false;

	/**
	 * Boot hooks (once per request).
	 */
	public static function init()
	{
		if (self::$hooks_registered) {
			return;
		}
		self::$hooks_registered = true;
		// Shop + single product need a full template swap; WC does not use the_content for those layouts.
		add_filter('template_include', array(__CLASS__, 'filter_template_include_wc_shells'), 99);
		add_filter('the_content', array(__CLASS__, 'filter_the_content'), 999);
	}

	/**
	 * Saved template IDs (shop_tpl, single_tpl, …).
	 *
	 * @return array<string, mixed>
	 */
	public static function get_settings()
	{
		return (array) get_option(self::OPTION_KEY, array());
	}

	/**
	 * @param string $key Field slug e.g. shop_tpl.
	 * @return int Post ID or 0.
	 */
	public static function get_template_post_id($key)
	{
		$vals = self::get_settings();
		$id   = isset($vals[$key]) ? absint($vals[$key]) : 0;
		return $id > 0 ? $id : 0;
	}

	/**
	 * @param int $post_id Post ID.
	 * @return bool
	 */
	public static function is_valid_elementor_library($post_id)
	{
		return 'elementor_library' === get_post_type($post_id) && 'publish' === get_post_status($post_id);
	}

	/**
	 * @return bool
	 */
	private static function skip_because_elementor_editor_or_preview()
	{
		if (! class_exists('\Elementor\Plugin')) {
			return false;
		}
		$api = \Elementor\Plugin::$instance;
		if ($api->editor && method_exists($api->editor, 'is_edit_mode') && $api->editor->is_edit_mode()) {
			return true;
		}
		if ($api->preview && method_exists($api->preview, 'is_preview_mode') && $api->preview->is_preview_mode()) {
			return true;
		}
		return false;
	}

	/**
	 * Shop archive and single product: replace theme template so Elementor is the only layout (avoids WC hooks + the_content mismatch).
	 *
	 * @param string $template Path.
	 * @return string
	 */
	public static function filter_template_include_wc_shells($template)
	{
		if (! class_exists('\Elementor\Plugin') || ! class_exists('WooCommerce')) {
			return $template;
		}
		if (self::skip_because_elementor_editor_or_preview()) {
			return $template;
		}

		// Shop archive — not the same as product category archives.
		if (function_exists('is_shop') && is_shop()) {
			$id = self::get_template_post_id('shop_tpl');
			if (! $id || ! self::is_valid_elementor_library($id)) {
				return $template;
			}
			$shell = STORZEN_ROOT_PATH . 'templates/szp-elementor-wc-shop-shell.php';
			if (! is_readable($shell)) {
				return $template;
			}
			self::$shop_template_id = $id;
			return $shell;
		}

		// Single product — WC builds the page from template parts / hooks, not the main the_content.
		if (function_exists('is_product') && is_product()) {
			$id = self::get_template_post_id('single_tpl');
			if (! $id || ! self::is_valid_elementor_library($id)) {
				return $template;
			}
			$shell = STORZEN_ROOT_PATH . 'templates/szp-elementor-wc-single-shell.php';
			if (! is_readable($shell)) {
				return $template;
			}
			self::$single_template_id = $id;
			return $shell;
		}

		return $template;
	}

	/**
	 * @return int
	 */
	public static function get_shop_template_id()
	{
		return (int) self::$shop_template_id;
	}

	/**
	 * @return int
	 */
	public static function get_single_template_id()
	{
		return (int) self::$single_template_id;
	}

	/**
	 * Replace main post content with rendered Elementor template for product / cart / checkout / thank you / account.
	 *
	 * @param string $content Post content.
	 * @return string
	 */
	public static function filter_the_content($content)
	{
		if (is_admin() || ! class_exists('\Elementor\Plugin') || ! class_exists('WooCommerce')) {
			return $content;
		}
		if (defined('REST_REQUEST') && REST_REQUEST) {
			return $content;
		}
		if (wp_doing_ajax()) {
			return $content;
		}
		if (! in_the_loop() || ! is_main_query()) {
			return $content;
		}
		if (self::skip_because_elementor_editor_or_preview()) {
			return $content;
		}

		$key = null;
		// Single product uses template_include shell only (see filter_template_include_wc_shells).
		if (function_exists('is_cart') && is_cart()) {
			$key = 'cart_tpl';
		} elseif (function_exists('is_checkout') && is_checkout()) {
			if (function_exists('is_order_received_page') && is_order_received_page()) {
				$key = 'thankyou_tpl';
			} else {
				$key = 'checkout_tpl';
			}
		} elseif (function_exists('is_account_page') && is_account_page()) {
			$key = 'myaccount_tpl';
		}

		if (! $key) {
			return $content;
		}

		$id = self::get_template_post_id($key);
		if (! $id || ! self::is_valid_elementor_library($id)) {
			return $content;
		}

		$rendered = \Elementor\Plugin::instance()->frontend->get_builder_content_for_display($id, true);
		return $rendered ? $rendered : $content;
	}
}

add_action(
	'wp',
	static function () {
		Storzen_WC_Elementor_Templates::init();
	},
	5
);
