<?php

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

require_once TX_PLUGIN_PATH . 'themebuilder/classes/utilities.php'; // utilities

/**
 * Conditions Manager setup
 *
 * @since 1.0
 */
class TX_Conditions_Manager {

    /**
    ** Header & Footer Conditions
    */
    public static function header_footer_display_conditions( $conditions ) {
        $template = NULL;

        // Archive Pages (includes search)
        if ( ! is_null( self::archive_templates_conditions( $conditions ) ) ) {
            $template = self::archive_templates_conditions( $conditions );
        }

        // Single Pages
        if ( ! is_null( self::single_templates_conditions( $conditions ) ) ) {
            $template = self::single_templates_conditions( $conditions );
        }

        // Elementor preview safety
        if ( \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
            $template_type = Utilities::get_tx_template_type( get_the_ID() );
            if ( 'header' === $template_type || 'footer' === $template_type ) {
                $template = NULL;
            }
        }

        // Maintenance / Coming soon
        if ( ! current_user_can( 'administrator' )
            && ( 'maintenance' === get_option( 'elementor_maintenance_mode_mode' )
              || 'coming_soon' === get_option( 'elementor_maintenance_mode_mode' ) ) ) {
            $template = NULL;
        }

        // --- Language-aware preferencing -------------------------------------

        // Polylang
        if ( function_exists( 'pll_current_language' ) && function_exists( 'pll_get_post_language' ) ) {
            $current_lang = pll_current_language( 'slug' );
            $template = self::match_template_by_language( $conditions, $template, $current_lang, 'polylang' );
        }

        // WPML
        if ( defined( 'ICL_SITEPRESS_VERSION' ) ) {
            $current_lang = apply_filters( 'wpml_current_language', null );
            $template = self::match_template_by_language( $conditions, $template, $current_lang, 'wpml' );
        }

        return $template;
    }

    /**
     * Language matching helper (Polylang + WPML)
     */
    private static function match_template_by_language( $conditions, $template, $current_lang, $mode = 'polylang' ) {
        if ( empty( $conditions ) || ! is_array( $conditions ) || ! $current_lang ) {
            return $template;
        }

        // If nothing matched, try to find a "global" for current language
        if ( is_null( $template ) ) {
            foreach ( $conditions as $candidate_slug => $rules ) {
                if ( in_array( 'global', (array) $rules, true ) ) {
                    $candidate_id = Utilities::get_template_id( $candidate_slug );

                    if ( $mode === 'polylang' && $candidate_id && function_exists( 'pll_get_post_language' ) ) {
                        if ( pll_get_post_language( $candidate_id ) === $current_lang ) {
                            return $candidate_slug;
                        }
                    }

                    if ( $mode === 'wpml' && $candidate_id ) {
                        $tr_id = apply_filters( 'wpml_object_id', $candidate_id, 'tx_templates', false, $current_lang );
                        if ( $tr_id && $tr_id !== $candidate_id ) {
                            return get_post_field( 'post_name', $tr_id );
                        }
                    }
                }
            }
        }

        // If matched template exists but wrong language → try to swap
        if ( ! is_null( $template ) ) {
            $matched_id = Utilities::get_template_id( $template );

            if ( $mode === 'polylang' && $matched_id && function_exists( 'pll_get_post_language' ) ) {
                if ( pll_get_post_language( $matched_id ) !== $current_lang ) {
                    return self::match_template_by_language( $conditions, null, $current_lang, $mode );
                }
            }

            if ( $mode === 'wpml' && $matched_id ) {
                $tr_id = apply_filters( 'wpml_object_id', $matched_id, 'tx_templates', false, $current_lang );
                if ( $tr_id && $tr_id !== $matched_id ) {
                    return get_post_field( 'post_name', $tr_id );
                }
            }
        }

        return $template;
    }

    /**
    ** Canvas Content Conditions
    */
    public static function canvas_page_content_display_conditions() {
        $template = NULL;

        $archives = json_decode( get_option( 'tx_archive_conditions' ), true );
        $singles  = json_decode( get_option( 'tx_single_conditions' ), true );

        if ( empty( $archives ) && empty( $singles ) ) {
            return NULL;
        }

        // Archive Pages (includes search)
        if ( ! is_null( self::archive_templates_conditions( $archives ) ) ) {
            $template = self::archive_templates_conditions( $archives );
        }

        // Single Pages
        if ( ! is_null( self::single_templates_conditions( $singles ) ) ) {
            $template = self::single_templates_conditions( $singles );
        }

        return $template;
    }

    /**
    ** Archive Pages Templates Conditions
    */
    public static function archive_templates_conditions( $conditions ) {
        $term_id = '';
        $queried_object = get_queried_object();

        if ( ! is_null( $queried_object ) ) {
            if ( isset( $queried_object->term_id ) && isset( $queried_object->taxonomy ) ) {
                $term_id = $queried_object->term_id;
            }
        }

        $template = NULL;

        if ( is_archive() || is_search() ) {
            if ( ! is_search() ) {
                if ( is_author() ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/author' );
                } elseif ( is_date() ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/date' );
                } elseif ( is_category() ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/categories', $term_id );
                } elseif ( is_tag() ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/tags', $term_id );
                } elseif ( is_post_type_archive( 'service' ) ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/archive-service', $term_id );
                } elseif ( is_tax( 'service-category' ) ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/service-category', $term_id );
                } elseif ( is_post_type_archive( 'portfolio' ) ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/archive-portfolio', $term_id );
                } elseif ( is_tax( 'portfolio-category' ) ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/portfolio-category', $term_id );
                } elseif ( is_post_type_archive( 'team' ) ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/archive-team', $term_id );
                } elseif ( is_tax( 'team-category' ) ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/team-category', $term_id );
                } elseif ( is_post_type_archive( 'product' ) ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/archive-product', $term_id );
                } elseif ( is_tax( 'product_cat' ) ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/product_cat', $term_id );
                } elseif ( is_tax( 'product_tag' ) ) {
                    $template = Utilities::get_template_slug( $conditions, 'archive/product_tag', $term_id );
                }
            } else {
                $template = Utilities::get_template_slug( $conditions, 'archive/search' );
            }
        } elseif ( Utilities::is_blog_archive() ) {
            $template = Utilities::get_template_slug( $conditions, 'archive/posts' );
        }

        if ( is_null( $template ) ) {
            $all_archives = Utilities::get_template_slug( $conditions, 'archive/all_archives' );
            if ( ! is_null( $all_archives ) ) {
                if ( class_exists( 'WooCommerce' ) && is_shop() ) {
                    $template = null;
                } else {
                    if ( is_archive() || is_search() || Utilities::is_blog_archive() ) {
                        $template = $all_archives;
                    }
                }
            }
        }

        return $template;
    }

    /**
    ** Single Pages Templates Conditions
    */
    public static function single_templates_conditions( $conditions ) {
        global $post;

        $post_id   = is_null( $post ) ? '' : $post->ID;
        $post_type = is_null( $post ) ? '' : $post->post_type;

        $template = NULL;

        if ( is_single() || is_front_page() || is_page() || is_404() ) {
            if ( is_single() ) {
                if ( 'post' === $post_type ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/posts', $post_id );
                } elseif ( 'portfolio' === $post_type ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/portfolio', $post_id );
                } elseif ( 'service' === $post_type ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/service', $post_id );
                } elseif ( 'team' === $post_type ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/team', $post_id );
                } elseif ( 'product' === $post_type ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/product', $post_id );
                } elseif ( 'tribe_events' === $post_type ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/tribe_events', $post_id );
                } elseif ( 'lp_course' === $post_type ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/lp_course', $post_id );
                } elseif ( 'properties' === $post_type ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/properties', $post_id );
                }
            } else {
                if ( is_front_page() && ! Utilities::is_blog_archive() ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/front_page' );
                } elseif ( is_404() ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/page_404' );
                } elseif ( is_page() ) {
                    $template = Utilities::get_template_slug( $conditions, 'single/pages', $post_id );
                }
            }
        }

        return $template;
    }
}

new TX_Conditions_Manager();