<?php
/**
 * Sifency Frontend Helper Classes
 *
 * This file contains the primary helper classes responsible for
 * retrieving and rendering Elementor theme builder templates.
 *
 * It has been fully refactored to work with the new Sifency Metabox framework,
 * which saves each meta field individually for better performance and easier querying.
 *
 * @package Sifency
 */

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

if ( ! class_exists( 'Sifency_Plugin_Helper' ) ) {

	/**
	 * Sifency Plugin Helper Class
	 *
	 * Provides utility functions for getting template lists and rendering them.
	 */
	class Sifency_Plugin_Helper {

		/**
		 * The core function to find templates of a specific type.
		 *
		 * @param string $template_key The value of the 'sifency_template_type' meta field (e.g., 'header', 'single_team').
		 * @return array An associative array of [ post_id => 'Post Title' ].
		 */
		private static function get_template_types( $template_key ) {
			$templates = array( '' => esc_html__( 'Default', 'sifency-addons' ) );

			$posts = get_posts(
				array(
					'posts_per_page' => -1,
					'post_type'      => 'sifency_template',
					'orderby'        => 'title',
					'order'          => 'ASC',
					'post_status'    => 'publish',
					'meta_query'     => array(
						array(
							'key'   => 'sifency_template_type',
							'value' => $template_key,
						),
					),
				)
			);

			if ( ! empty( $posts ) && ! is_wp_error( $posts ) ) {
				foreach ( $posts as $post ) {
					$templates[ (int) $post->ID ] = $post->post_title;
				}
			}

			return $templates;
		}

		/*
		==============================================*/
		// Template Type Getters (Used in Metaboxes/Elementor Controls)
		/*==============================================*/
		public static function get_header_types() {
			return self::get_template_types( 'header' ); }
		public static function get_footer_types() {
			return self::get_template_types( 'footer' ); }
		public static function get_404_page_template() {
			return self::get_template_types( '404' ); }
		public static function get_coming_soon_page_template() {
			return self::get_template_types( 'coming_soon' ); }
		public static function get_subheader_template() {
			return self::get_template_types( 'subheader' ); }
		public static function get_cta_template() {
			return self::get_template_types( 'cta' ); }
		public static function get_team_single_types() {
			return self::get_template_types( 'single_team' ); }
		public static function get_career_single_types() {
			return self::get_template_types( 'single_career' ); }
		public static function get_services_single_types() {
			return self::get_template_types( 'single_service' ); }
		public static function get_portfolio_single_types() {
			return self::get_template_types( 'single_portfolio' ); }
		public static function get_event_single_types() {
			return self::get_template_types( 'single_event' ); }
		public static function get_product_single_types() {
			return self::get_template_types( 'single_product' ); }

		/**
		 * Render an Elementor template by its ID.
		 * (This function was already correct and requires no changes).
		 */
		public static function render_template( $template_id ) {
			if ( (int) $template_id > 0 && class_exists( '\Elementor\Plugin' ) && did_action( 'elementor/loaded' ) ) {
				return \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( (int) $template_id );
			}
			return '';
		}

		/*
		==============================================*/
		// Template Renderers (These are just wrappers and need no changes)
		/*==============================================*/
		public static function sifency_render_header( $header_style ) {
			return self::render_template( $header_style ); }
		public static function sifency_render_footer( $footer_style ) {
			return self::render_template( $footer_style ); }
		public static function sifency_render_subheader( $subheader_style ) {
			return self::render_template( $subheader_style ); }
		public static function sifency_render_cta( $cta_style ) {
			return self::render_template( $cta_style ); }
		public static function sifency_render_team_single_template( $template_id ) {
			return self::render_template( $template_id ); }
		public static function sifency_render_career_single_template( $template_id ) {
			return self::render_template( $template_id ); }
		public static function sifency_render_services_single_template( $template_id ) {
			return self::render_template( $template_id ); }
		public static function sifency_render_portfolio_single_template( $template_id ) {
			return self::render_template( $template_id ); }
		public static function sifency_render_event_single_template( $template_id ) {
			return self::render_template( $template_id ); }
		public static function sifency_render_product_single_template( $template_id ) {
			return self::render_template( $template_id ); }

		/*
		==============================================*/
		// Taxonomy Getters
		/*==============================================*/
		public static function sifency_blog_category() {
			$terms    = get_terms(
				array(
					'taxonomy'   => 'category',
					'hide_empty' => true,
				)
			);
			$cat_list = array();
			if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
				foreach ( $terms as $term ) {
					$cat_list[ $term->slug ] = $term->name;
				}
			}
			return $cat_list;
		}
		public static function sifency_portfolio_category() {
			$terms    = get_terms(
				array(
					'taxonomy'   => 'portfolio_cat',
					'hide_empty' => true,
				)
			);
			$cat_list = array();
			if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
				foreach ( $terms as $term ) {
					$cat_list[ $term->slug ] = $term->name;
				}
			}
			return $cat_list;
		}
	}
}

if ( ! class_exists( 'Sifency_Helper' ) ) {
	/**
	 * Sifency Helper Class
	 * Handles theme options and resolves which template to display on the front-end.
	 */
	class Sifency_Helper {

		private static $cached_options = null;

		private static function get_options() {
			if ( null === self::$cached_options ) {
				self::$cached_options = get_option( 'sifency-options', array() );
				if ( ! is_array( self::$cached_options ) ) {
					self::$cached_options = array(); }
			}
			return self::$cached_options;
		}

		private static function get_valid_post( $post_id ) {
			$post_id = (int) $post_id;
			if ( $post_id <= 0 ) {
				return false; }
			$post = get_post( $post_id );
			return ( $post instanceof WP_Post && 'publish' === $post->post_status ) ? $post : false;
		}

		/**
		 * The core logic for choosing which template to display.
		 *
		 * REFACTORED: Now uses your sifency_get_field() helper to get individual meta values,
		 * making it much cleaner and more consistent with your new framework.
		 *
		 * @param string     $meta_type_key        The meta key for the 'Default' vs 'Custom' switcher.
		 * @param string     $meta_template_id_key The meta key for the template ID select dropdown.
		 * @param int|string $global_template_id The template ID from the global theme options.
		 * @return int|string The final template ID to render, or 'default'.
		 */
		private static function template_id( $meta_type_key, $meta_template_id_key, $global_template_id ) {
			// Get the value directly using your helper function.
			$meta_type = sifency_get_field( $meta_type_key );

			if ( 'default' === $meta_type ) {
				return 'default';
			}

			if ( 'custom' === $meta_type || 'enabled' === $meta_type ) {
				$meta_template_id = sifency_get_field( $meta_template_id_key );
				if ( is_numeric( $meta_template_id ) && (int) $meta_template_id > 0 ) {
					return (int) $meta_template_id;
				}
				// If 'custom' is selected but no template is chosen, fall back to the theme's default.
				if ( '' === $meta_template_id || 'default' === $meta_template_id ) {
					return 'default';
				}
			}

			// If meta is disabled or not set, use the global theme option.
			if ( is_numeric( $global_template_id ) && (int) $global_template_id > 0 ) {
				return (int) $global_template_id;
			}
			return 'default';
		}

		public static function sifency_header_template() {
			$options     = self::get_options();
			$template_id = self::template_id( 'meta_header_type', 'meta_header_style', $options['header_style'] ?? '' );
			if ( 'default' !== $template_id && self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::sifency_render_header( $template_id ); // phpcs:ignore
			} else {
				get_template_part( 'template-parts/header/header-global', 'sifency-addons' );
			}
		}

		public static function sifency_footer_template() {
			$options     = self::get_options();
			$template_id = self::template_id( 'meta_footer_type', 'meta_footer_style', $options['footer_template_style'] ?? '' );
			if ( 'default' !== $template_id && self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::sifency_render_footer( $template_id ); // phpcs:ignore
			} else {
				get_template_part( 'template-parts/footer/footer', 'all' );
			}
		}

		public static function sifency_404_template() {
			$options     = self::get_options();
			$template_id = $options['custom_404_style'] ?? '';
			if ( self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::render_template( $template_id ); // phpcs:ignore
			} else {
				get_template_part( 'template-parts/404', 'sifency-addons' );
			}
		}

		public static function sifency_coming_soon_template() {
			$options     = self::get_options();
			$template_id = $options['coming_soon_template_style'] ?? '';
			if ( self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::render_template( $template_id ); // phpcs:ignore
			} else {
				get_template_part( 'template-parts/coming-soon', 'sifency-addons' );
			}
		}

		public static function sifency_subheader_template() {
			$options     = self::get_options();
			$template_id = self::template_id( 'meta_subheader_type', 'meta_subheader_style', $options['subheader_style'] ?? '' );
			if ( 'default' !== $template_id && self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::sifency_render_subheader( $template_id ); // phpcs:ignore
			} else {
				get_template_part( 'template-parts/header/subheader/breadcrumb-default', 'sifency-addons' );
			}
		}

		public static function sifency_cta_template() {
			$options     = self::get_options();
			$template_id = self::template_id( 'meta_cta_type', 'meta_cta_style', $options['cta_style'] ?? '' );
			if ( 'default' !== $template_id && self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::sifency_render_cta( $template_id ); // phpcs:ignore
			} elseif ( function_exists( 'display_cta_section' ) ) {
				display_cta_section();
			}
		}

		public static function sifency_team_single_template() {
			if ( ! is_singular( 'team' ) ) {
				return; }
			$options     = self::get_options();
			$template_id = self::template_id( 'meta_team_single_type', 'meta_team_single_style', $options['team_single_template'] ?? '' );
			if ( 'default' !== $template_id && self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::sifency_render_team_single_template( $template_id ); // phpcs:ignore
			} elseif ( function_exists( 'render_default_team_template' ) ) {
				render_default_team_template();
			}
		}

		public static function sifency_career_single_template() {
			if ( ! is_singular( 'career' ) ) {
				return; }
			$options     = self::get_options();
			$template_id = self::template_id( 'meta_career_single_type', 'meta_career_single_style', $options['career_single_template'] ?? '' );
			if ( 'default' !== $template_id && self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::sifency_render_career_single_template( $template_id ); // phpcs:ignore
			} elseif ( function_exists( 'render_default_career_template' ) ) {
				render_default_career_template();
			}
		}

		public static function sifency_service_single_template() {
			if ( ! is_singular( 'service' ) ) {
				return; }
			$options     = self::get_options();
			$template_id = self::template_id( 'meta_services_single_type', 'meta_services_single_style', $options['service_single_template'] ?? '' );
			if ( 'default' !== $template_id && self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::sifency_render_services_single_template( $template_id ); // phpcs:ignore
			} elseif ( function_exists( 'render_default_service_template' ) ) {
				render_default_service_template();
			}
		}

		public static function sifency_portfolio_single_template() {
			if ( ! is_singular( 'portfolio' ) ) {
				return; }
			$options     = self::get_options();
			$template_id = self::template_id( 'meta_portfolio_single_type', 'meta_portfolio_single_style', $options['portfolio_single_template'] ?? '' );
			if ( 'default' !== $template_id && self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::sifency_render_portfolio_single_template( $template_id ); // phpcs:ignore
			} elseif ( function_exists( 'render_default_portfolio_template' ) ) {
				render_default_portfolio_template();
			}
		}

		public static function sifency_event_single_template() {
			if ( ! is_singular( 'event' ) ) {
				return; }
			$options     = self::get_options();
			$template_id = self::template_id( 'meta_event_single_type', 'meta_event_single_style', $options['event_single_template'] ?? '' );
			if ( 'default' !== $template_id && self::get_valid_post( $template_id ) ) {
				echo Sifency_Plugin_Helper::sifency_render_event_single_template( $template_id ); // phpcs:ignore
			} elseif ( function_exists( 'render_default_event_template' ) ) {
				render_default_event_template();
			}
		}

		public static function sifency_product_single_template() {
			if ( ! class_exists( 'WooCommerce' ) || ! is_singular( 'product' ) ) {
				return; }
			global $post;
			$options     = self::get_options();
			$template_id = self::template_id( 'meta_product_single_type', 'meta_product_single_style', $options['product_single_template'] ?? '' );
			if ( 'default' !== $template_id && self::get_valid_post( $template_id ) ) {
				if ( $post instanceof WP_Post && function_exists( 'wc_setup_product_data' ) ) {
					wc_setup_product_data( $post ); }
				echo Sifency_Plugin_Helper::sifency_render_product_single_template( $template_id ); // phpcs:ignore
				wp_reset_postdata();
			} else {
				get_template_part( 'woocommerce/single', 'product' );
			}
		}
	}
}
