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

class Sifency_Frontend_Helper {

    private static $template_cache = [];

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

        $args = [
            'post_type'      => 'themebuilder',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'tax_query'      => [
                [
                    'taxonomy' => 'sifency_builder_type',
                    'field'    => 'slug',
                    'terms'    => $type,
                ]
            ],
            'meta_query' => [
                [
                    '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'] ?? [];
        $exclude_rules = $conditions['exclude'] ?? [];

        // Exclude rules take absolute priority
        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;

        // GENERAL
        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();

            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 ) {
        if ( ! class_exists('\Elementor\Plugin') || ! $post_id ) return;

        $css_file = null;
        
        if ( class_exists( '\Elementor\Core\Files\CSS\Post' ) ) {
            $css_file = new \Elementor\Core\Files\CSS\Post( $post_id );
        } elseif ( class_exists( '\Elementor\Post_CSS_File' ) ) {
            $css_file = new \Elementor\Post_CSS_File( $post_id );
        }
        if ( $css_file ) {
            $css_file->enqueue();
        }
        echo \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $post_id, true );
    }
}