<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

class Utilities {

	/**
	 * Get Library Template ID (Polylang-first; safe fallbacks)
	 */
	public static function get_template_id( $slug ) {
		if ( empty( $slug ) ) {
			return false;
		}

		// 1) Try current Polylang language (if present)
		$args = [
			'post_type'      => 'tx_templates',
			'name'           => $slug,
			'post_status'    => 'publish',
			'posts_per_page' => 1,
		];

		if ( function_exists( 'pll_current_language' ) ) {
			$args['lang'] = pll_current_language( 'slug' ); // en, ar, etc.
		}

		$posts = get_posts( $args );
		if ( ! empty( $posts ) ) {
			return $posts[0]->ID;
		}

		// 2) Fallback: any language, then map to current Polylang if available
		$any = get_posts( [
			'post_type'        => 'tx_templates',
			'name'             => $slug,
			'post_status'      => 'publish',
			'posts_per_page'   => 1,
			'suppress_filters' => true,
		] );

		if ( ! empty( $any ) ) {
			// Map to current Polylang language if possible
			if ( function_exists( 'pll_get_post' ) && function_exists( 'pll_current_language' ) ) {
				$target = pll_current_language( 'slug' );
				if ( $target ) {
					$tr_id = pll_get_post( $any[0]->ID, $target );
					if ( $tr_id ) {
						return $tr_id;
					}
				}
			}
			// Last fallback: return the found one (acts like “global”)
			return $any[0]->ID;
		}

		return false;
	}

	/**
	 * Get Available Custom Post Types or Taxonomies
	 */
	public static function get_custom_types_of( $query, $exclude_defaults = true ) {
		// Taxonomies
		if ( 'tax' === $query ) {
			$custom_types = get_taxonomies( [ 'show_in_nav_menus' => true ], 'objects' );
		// Post Types
		} else {
			$custom_types = get_post_types( [ 'show_in_nav_menus' => true ], 'objects' );
		}

		$custom_type_list = [];

		foreach ( $custom_types as $key => $value ) {
			if ( $exclude_defaults ) {
				if ( $key != 'post' && $key != 'page' && $key != 'category' && $key != 'post_tag' ) {
					$custom_type_list[ $key ] = $value->label;
				}
			} else {
				$custom_type_list[ $key ] = $value->label;
			}
		}

		return $custom_type_list;
	}

	/**
	 * Get Elementor Template Type
	 */
	public static function get_elementor_template_type( $id ) {
		$post_meta     = get_post_meta( $id );
		$template_type = isset( $post_meta['_elementor_template_type'][0] ) ? $post_meta['_elementor_template_type'][0] : false;

		return $template_type;
	}

	/**
	 * Render Elementor Template
	 *
	 * Note: we resolve the final template ID, then pass it through
	 * maybe_translate_template_id() so WPML (if present) receives
	 * its correct-language post ID as well. This is a no-op on
	 * single-language sites and keeps Polylang behavior intact.
	 */
	public static function render_elementor_template( $slug ) {
		$template_id = Utilities::get_template_id( $slug );
		if ( ! $template_id ) {
			return;
		}

		// Final translation pass (safe for Polylang / WPML / single-language)
		$template_id = Utilities::maybe_translate_template_id( $template_id );
		if ( ! $template_id ) {
			return;
		}

		$get_elementor_content = \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $template_id, false );

		if ( '' === $get_elementor_content ) {
			return;
		}

		// Render Elementor Template Content
		echo $get_elementor_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}

	/**
	 * Theme Builder Template Check
	 */
	public static function is_theme_builder_template() {
		$current_page = get_post( get_the_ID() );

		if ( $current_page ) {
			return strpos( $current_page->post_name, 'user-archive' ) !== false
				|| strpos( $current_page->post_name, 'user-single' ) !== false
				|| strpos( $current_page->post_name, 'user-product' ) !== false;
		} else {
			return false;
		}
	}

	/**
	 * Blog Archive Page Check
	 */
	public static function is_blog_archive() {
		$result     = false;
		$front_page = get_option( 'page_on_front' );
		$posts_page = get_option( 'page_for_posts' );

		if ( is_home() && '0' === $front_page && '0' === $posts_page
			|| ( intval( $posts_page ) === get_queried_object_id() && ! is_404() ) ) {
			$result = true;
		}

		return $result;
	}

	/**
	 * Get Library Template Slug (Polylang-aware existence check)
	 *
	 * Keeps your existing logic; only the final existence check
	 * adds a Polylang 'lang' arg if available. We do NOT add any
	 * WPML param here to avoid changing your stable behavior.
	 */
	public static function get_template_slug( $data, $page, $post_id = '' ) {
		if ( is_null( $data ) ) {
			return;
		}

		$template = null;

		// Find a Custom Condition
		foreach ( $data as $id => $conditions ) {
			if ( in_array( $page . '/' . $post_id, $conditions ) ) {
				$template = $id;
			} elseif ( in_array( $page . '/all', $conditions ) ) {
				$template = $id;
			} elseif ( in_array( $page, $conditions ) ) {
				$template = $id;
			}
		}

		// If a Custom NOT Found, use Global
		if ( is_null( $template ) ) {
			foreach ( $data as $id => $conditions ) {
				if ( in_array( 'global', $conditions ) ) {
					$template = $id;
				}
			}
		}

		// Verify template exists in current language
		$args = [
			'post_type'      => 'tx_templates',
			'name'           => $template,
			'posts_per_page' => 1,
			'post_status'    => 'publish',
		];

		if ( function_exists( 'pll_current_language' ) ) {
			$args['lang'] = pll_current_language( 'slug' );
		}

		$templates_loop = new \WP_Query( $args );

		if ( ! $templates_loop->have_posts() ) {
			return null;
		} else {
			return $template;
		}
	}

	/**
	 * Get Template Type
	 */
	public static function get_tx_template_type( $id ) {
		$post_meta     = get_post_meta( $id );
		$template_type = isset( $post_meta['_tx_template_type'][0] ) ? $post_meta['_tx_template_type'][0] : false;

		return $template_type;
	}

	/**
	 * Final translation pass for a resolved template ID
	 * - Keeps Polylang behavior intact (mostly already handled by get_template_id)
	 * - Adds safe WPML support (only runs if WPML is active)
	 * - No effect on single-language sites
	 */
	public static function maybe_translate_template_id( $template_id ) {
		if ( ! $template_id ) {
			return false;
		}

		// Polylang (usually already resolved above; this is a safe double-check)
		if ( function_exists( 'pll_get_post' ) && function_exists( 'pll_current_language' ) ) {
			$lang = pll_current_language( 'slug' );
			if ( $lang ) {
				$tr_id = pll_get_post( $template_id, $lang );
				if ( $tr_id ) {
					return $tr_id;
				}
			}
		}

		// WPML (safe optional translation)
		if ( defined( 'ICL_SITEPRESS_VERSION' ) ) {
			$lang  = apply_filters( 'wpml_current_language', null );
			$tr_id = apply_filters( 'wpml_object_id', $template_id, 'tx_templates', false, $lang );
			if ( $tr_id ) {
				return $tr_id;
			}
		}

		return $template_id;
	}
}

new Utilities();