<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Sifency_Addons_Frontend_Helper {

	private static $template_cache = array();

	public static function find_matching_template( $type ) {
		if ( isset( self::$template_cache[ $type ] ) ) {
			return self::$template_cache[ $type ];
		}

		$args = array(
			'post_type'      => 'themebuilder',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
			'tax_query'      => array(
				array(
					'taxonomy' => 'sifency_builder_type',
					'field'    => 'slug',
					'terms'    => $type,
				),
			),
			'meta_query'     => array(
				array(
					'key'   => '_sifency_builder_active',
					'value' => '1',
				),
			),
		);

		$templates = get_posts( $args );

		if ( empty( $templates ) ) {
			self::$template_cache[ $type ] = 0;
			return 0;
		}

		$highest_priority     = -1;
		$matching_template_id = 0;

		foreach ( $templates as $template ) {
			$conditions = get_post_meta( $template->ID, '_themebuilder_conditions', true );
			$priority   = self::check_conditions( $conditions );

			if ( $priority > $highest_priority && $priority > 0 ) {
				$highest_priority     = $priority;
				$matching_template_id = $template->ID;
			}
		}

		self::$template_cache[ $type ] = $matching_template_id;
		return $matching_template_id;
	}

	private static function check_conditions( $conditions ) {
		if ( empty( $conditions ) || ! is_array( $conditions ) ) {
			return -1;
		}

		$include_rules = $conditions['include'] ?? array();
		$exclude_rules = $conditions['exclude'] ?? array();

		foreach ( $exclude_rules as $rule ) {
			if ( self::is_rule_matched( $rule ) > 0 ) {
				return -1;
			}
		}
		if ( empty( $include_rules ) ) {
			return 0;
		}

		$highest_priority = 0;

		foreach ( $include_rules as $rule ) {
			$priority = self::is_rule_matched( $rule );
			if ( $priority > $highest_priority ) {
				$highest_priority = $priority;
			}
		}

		return $highest_priority;
	}

	private static function is_rule_matched( $rule ) {
		$type    = $rule['type'] ?? 'general';
		$subtype = $rule['subtype'] ?? 'none';
		$value   = $rule['value'] ?? null;

		if ( $type === 'general' ) {
			switch ( $subtype ) {
				case 'entire_site':
					return 10;
				case 'front_page':
					return is_front_page() ? 100 : 0;
				case 'search_results':
					return is_search() ? 40 : 0;
				case 'error_404':
					return is_404() ? 40 : 0;
			}
		}

		// SINGULAR
		if ( $type === 'singular' && is_singular() ) {
			$post_id   = get_queried_object_id();
			$post_type = get_post_type();

			$cpt_taxonomy_map = array(
				'product_in_category'   => 'product_cat',
				'product_in_tag'        => 'product_tag',
				'portfolio_in_category' => 'portfolio_category',
				'portfolio_in_tag'      => 'portfolio_tag',
				'service_in_category'   => 'service_category',
				'service_in_tag'        => 'service_tag',
				'team_in_category'      => 'team_category',
				'event_in_category'     => 'event_category',
				'doc_in_category'       => 'doc_category',
				'digital_in_category'   => 'digital_category',
			);

			if ( array_key_exists( $subtype, $cpt_taxonomy_map ) ) {
				$tax_name = $cpt_taxonomy_map[ $subtype ];
				return has_term( $value, $tax_name, $post_id ) ? 70 : 0;
			}
			switch ( $subtype ) {
				case 'all':
					return 50;
				case 'post_type':
					return ( $post_type === $value ) ? 60 : 0;

				case 'post':
				case 'page':
				case 'product':
				case 'service':
				case 'portfolio':
				case 'team':
				case 'event':
				case 'career':
				case 'doc':
				case 'digital':
				case 'download':
					return ( $post_type === $subtype && (int) $value === $post_id ) ? 110 : 0;

				case 'in_category':
					return has_category( $value, $post_id ) ? 70 : 0;

				case 'in_tag':
					return has_tag( $value, $post_id ) ? 70 : 0;

				case 'in_taxonomy':
					$taxonomy = $rule['taxonomy'] ?? null;
					return ( $taxonomy && has_term( $value, $taxonomy, $post_id ) ) ? 70 : 0;
			}
		}

		// ARCHIVE
		if ( $type === 'archive' && is_archive() ) {
			switch ( $subtype ) {
				case 'all':
					return 20;
				case 'post_type_archive':
					return is_post_type_archive( $value ) ? 30 : 0;
				case 'category':
					return is_category( $value ) ? 35 : 0;
				case 'tag':
					return is_tag( $value ) ? 35 : 0;
				case 'author':
					return is_author( $value ) ? 35 : 0;
				case 'taxonomy':
					return is_tax( $value ) ? 35 : 0;
				case 'date':
					return is_date() ? 30 : 0;

				// WooCommerce
				case 'shop':
					return function_exists( 'is_shop' ) && is_shop() ? 80 : 0;
				case 'product_archive':
					return function_exists( 'is_post_type_archive' ) && is_post_type_archive( 'product' ) ? 75 : 0;
				case 'product_category':
					return function_exists( 'is_product_category' ) && is_product_category( $value ) ? 70 : 0;
				case 'product_tag':
					return function_exists( 'is_product_tag' ) && is_product_tag( $value ) ? 70 : 0;

				// CPT archives
				case 'team':
					return is_post_type_archive( 'team' ) ? 75 : 0;
				case 'service':
					return is_post_type_archive( 'service' ) ? 75 : 0;
				case 'portfolio':
					return is_post_type_archive( 'portfolio' ) ? 75 : 0;
				case 'event':
					return is_post_type_archive( 'event' ) ? 75 : 0;
				case 'career':
					return is_post_type_archive( 'career' ) ? 75 : 0;
				case 'doc':
					return is_post_type_archive( 'doc' ) ? 75 : 0;
				case 'digital':
					return is_post_type_archive( 'digital' ) ? 75 : 0;
			}
		}

		return 0;
	}
	public static function render_elementor_content( $post_id, $with_css = false ) {
		if ( ! $post_id ) {
			return;
		}
		if ( ! did_action( 'elementor/loaded' ) ) {
			return;
		}
		if ( is_admin() && ! \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
			return;
		}

		if ( class_exists( '\Elementor\Core\Files\CSS\Post' ) ) {
			$css_file = \Elementor\Core\Files\CSS\Post::create( $post_id );
			$css_file->enqueue();
		}

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $post_id, $with_css );
	}
}
