<?php
/**
 * Ensure the file is not accessed directly.
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Badge
 *
 * @package   Store Manager
 * @author    ShopManagerX
 * @link      http://domain.tld
 * @license   GPL 2.0+
 * @copyright 2024 ShopManagerX
 */

use CPBW\App\Badge;
use CPBW\App\Utilities\Settings;

/**
 * Cache settings to avoid repeated database calls.
 * This significantly improves performance on product loops.
 */
if ( ! function_exists( 'cpbw_get_cached_settings' ) ) {
    function cpbw_get_cached_settings() {
        static $cached_settings = null;

        if ( $cached_settings === null ) {
            $cached_settings = [
                    'show_badge_on'   => Settings::get('show_badge_on'),
                    'custom_wrapper'  => Settings::get('custom_wrapper'),
                    'is_pro'          => Badge::is_pro(),
            ];
        }

        return $cached_settings;
    }
}

/**
 * Apply badge to a product.
 */
if ( ! function_exists( 'cpbw_apply_product_badges' ) ) {
    function cpbw_apply_product_badges($product) {

        // Skip AJAX and admin screens
        if (wp_doing_ajax() || is_admin()) {
            return [];
        }

        $badges = (new Badge)->apply_product_badges($product);

        // Ensure it's an array
        return is_array($badges) ? $badges : [];
    }
}

/**
 * Sanitize badge HTML safely.
 * Minifies <style> blocks to prevent wpautop() from injecting <p> tags
 * into multiline CSS, which breaks badge styling on the frontend.
 */
if ( ! function_exists( 'cpbw_sanitize_badge_html' ) ) {
    function cpbw_sanitize_badge_html($html) {
        // Minify <style> blocks to single line to prevent wpautop interference
        $html = preg_replace_callback( '/<style\b[^>]*>(.*?)<\/style>/is', function( $match ) {
            $css = preg_replace( '/\s+/', ' ', $match[1] );
            return '<style>' . trim( $css ) . '</style>';
        }, $html );

        return wp_kses_post($html);
    }
}

if( ! function_exists( 'cpbw_allow_style_tags') ) {
    /**
     * Allow <style> tags with attributes in wp_kses.
     *
     * @param array  $tags    Allowed HTML tags.
     * @param string $context Context for allowed tags.
     * @return array Modified allowed tags.
     */
    function cpbw_allow_style_tags( $tags, $context ) {
        if ( 'post' === $context ) {
            $tags['style'] = [
                    'type'   => true,
                    'media'  => true,
                    'scoped' => true,
            ];
        }

        return $tags;
    }

    add_filter( 'wp_kses_allowed_html', 'cpbw_allow_style_tags', 10, 2 );
}


/**
 * Add badge overlays on WooCommerce shop/listing pages.
 */
if ( ! function_exists( 'cpbw_add_badge_to_shop_product_image' ) ) {

    add_action( 'wp', function () {

        $settings = cpbw_get_cached_settings();

        if ( $settings['show_badge_on'] !== 'both' && $settings['show_badge_on'] !== 'list' ) {
            return;
        }

        function cpbw_add_badge_to_shop_product_image( $image, $product ) {

            // Skip if inside a blocked shortcode (e.g. review sliders)
            if ( cpbw_shortcode_context() || cpbw_block_context() ) {
                return $image;
            }

            $badges = cpbw_apply_product_badges( $product );

            if ( empty( $badges ) ) {
                return $image;
            }

            // Skip widgets, AJAX fragments, mini-cart, sticky add-to-cart
            if (
                wp_doing_ajax() ||
                ( function_exists( 'is_cart' )     && is_cart() ) ||
                ( function_exists( 'is_checkout' ) && is_checkout() ) ||
                ( function_exists( 'is_account_page' ) && is_account_page() ) ||
                did_action( 'woocommerce_widget_product_item_start' ) ||
                did_action( 'woocommerce_widget_product_item_end' ) ||
                doing_action( 'woocommerce_after_mini_cart' ) ||
                doing_action( 'woocommerce_widget_shopping_cart_before_buttons' ) ||
                doing_action( 'woocommerce_before_mini_cart' ) ||
                doing_action( 'woocommerce_widget_shopping_cart_before' ) ||
                doing_action( 'wp_footer' )
            ) {
                return $image;
            }

            $badges_html = '';
            foreach ( $badges as $badge_html ) {
                $badges_html .= cpbw_sanitize_badge_html( $badge_html );
            }

            $settings = cpbw_get_cached_settings();

            if ( $settings['custom_wrapper'] ) {
                return '<div class="cpbw-product-badge-wrapper">' . $image . $badges_html . '</div>';
            }

            return $image . $badges_html;
        }

        add_filter( 'woocommerce_product_get_image',     'cpbw_add_badge_to_shop_product_image', PHP_INT_MAX, 2 );
        add_filter( 'woocommerce_get_product_thumbnail', 'cpbw_add_badge_to_shop_product_image', 10, 3 );
    } );
}

/**
 * Add badge overlays on WooCommerce single product pages.
 */
if ( ! function_exists( 'cpbw_add_badge_to_single_product_image_pro' ) ) {
    function cpbw_add_badge_to_single_product_image_pro() {
        global $product;
        if ( ! $product ) return;

        // ✅ SIMPLE PRODUCT
        if ( $product->get_type() !== 'variable' ) {
            $badges = cpbw_apply_product_badges( $product );
            if ( empty( $badges ) ) return;

            $badge_html = '';
            foreach ( $badges as $badge ) {
                $badge_html .= cpbw_sanitize_badge_html( $badge );
            }

            add_action( 'wp_footer', function() use ( $badge_html ) {
                ?>
                <script>
                    // Run after all scripts (Flatsome, WooCommerce, etc.)
                    window.addEventListener("load", function() {
                        setTimeout(function() {

                            let galleryImages = document.querySelectorAll(".woocommerce-product-gallery__image");

                            if (!galleryImages.length) {
                                galleryImages = document.querySelectorAll(".woocommerce-product-gallery__wrapper");
                            }
                            if (!galleryImages.length) {
                                galleryImages = document.querySelectorAll(".woocommerce-product-gallery");
                            }

                            galleryImages.forEach(function(imgWrap) {
                                if (!imgWrap.querySelector(".cpbw-badge-wrapper")) {
                                    const wrapper = document.createElement('div');
                                    wrapper.className = 'cpbw-badge-wrapper';
                                    wrapper.innerHTML = <?php echo wp_json_encode($badge_html); ?>;
                                    imgWrap.appendChild(wrapper);
                                }
                            });
                        }, 100);
                    });
                </script>
                <?php
            });
            return; // stop here for simple product
        }

        // ✅ VARIABLE PRODUCT
        // Parent product badge (for fallback)
        $parent_badges = cpbw_apply_product_badges( $product );
        $parent_html   = '';
        if ( ! empty( $parent_badges ) ) {
            foreach ( $parent_badges as $badge ) {
                $parent_html .= cpbw_sanitize_badge_html( $badge );
            }
        }

        // Variation-specific badges
        $variation_badges = [];
        foreach ( $product->get_children() as $var_id ) {
            $variation = wc_get_product( $var_id );
            if ( ! $variation ) continue;

            $badges = cpbw_apply_product_badges( $variation );
            if ( empty( $badges ) ) continue;

            $html = '';
            foreach ( $badges as $badge ) {
                $html .= cpbw_sanitize_badge_html( $badge );
            }

            if ( $html ) {
                $variation_badges[ $var_id ] = $html;
            }
        }

        // Inject JS
        add_action( 'wp_footer', function() use ( $variation_badges, $parent_html ) {
            ?>
            <script>
                // Wait until all scripts (including Flatsome gallery) are loaded
                window.addEventListener("load", function() {
                    setTimeout(function() {
                        const variationBadges = <?php echo wp_json_encode($variation_badges); ?>;
                        const parentBadgeHtml = <?php echo wp_json_encode($parent_html); ?>;

                        let galleryImages = document.querySelectorAll(".woocommerce-product-gallery__image");

                        if (!galleryImages.length) {
                            galleryImages = document.querySelectorAll(".woocommerce-product-gallery__wrapper");
                        }
                        if (!galleryImages.length) {
                            galleryImages = document.querySelectorAll(".woocommerce-product-gallery");
                        }

                        function setBadge(html) {
                            galleryImages.forEach(imgWrap => {
                                let wrapper = imgWrap.querySelector(".cpbw-badge-wrapper");
                                if (!wrapper) {
                                    wrapper = document.createElement('div');
                                    wrapper.className = 'cpbw-badge-wrapper';
                                    imgWrap.appendChild(wrapper);
                                }
                                wrapper.innerHTML = html || '';
                            });
                        }

                        // On page load: show variation badge if default selected, else parent badge
                        const defaultVariation = document.querySelector("input.variation_id");
                        if (defaultVariation && defaultVariation.value && variationBadges[defaultVariation.value]) {
                            setBadge(variationBadges[defaultVariation.value]);
                        } else {
                            setBadge(parentBadgeHtml);
                        }

                        // On variation change
                        jQuery('form.variations_form').on('found_variation', function(event, variation) {
                            setBadge(variationBadges[variation.variation_id]);
                        });

                        // On reset variation → fallback to parent badge
                        jQuery('form.variations_form').on('reset_data', function() {
                            setBadge(parentBadgeHtml);
                        });
                    }, 100);
                });
            </script>
            <?php
        });
    }

    // Use cached settings
    $settings = cpbw_get_cached_settings();

    if ( ( $settings['show_badge_on'] === 'both' || $settings['show_badge_on'] === 'single' ) && $settings['is_pro'] ) {
        add_action( 'woocommerce_before_single_product_summary', 'cpbw_add_badge_to_single_product_image_pro', 5 );
        add_action( 'woocommerce_before_single_product', 'cpbw_add_badge_to_single_product_image', 5 );
        add_action( 'flatsome_before_single_product_custom', 'cpbw_add_badge_to_single_product_image_pro', 5 );
        // Breakdance Builder support
        add_action( 'breakdance_after_product_images', 'cpbw_add_badge_to_single_product_image', 5 );
        add_action( 'woocommerce_product_thumbnails', 'cpbw_add_badge_to_single_product_image', 5 );
    }
}

/**
 * Add badge overlays on WooCommerce single product pages.
 */
if ( ! function_exists( 'cpbw_add_badge_to_single_product_image' ) ) {
    function cpbw_add_badge_to_single_product_image() {
        global $product;
        if ( ! $product ) return;

        // Get badges for this product
        $badges = cpbw_apply_product_badges( $product );
        if ( empty( $badges ) ) return;

        // Sanitize badges
        $badge_html = '';
        foreach ( $badges as $badge ) {
            $badge_html .= cpbw_sanitize_badge_html( $badge );
        }

        // Inject badges via inline JS in footer
        add_action( 'wp_footer', function() use ( $badge_html ) {
            ?>
            <script>
                window.addEventListener("load", function() {
                    // Wait a short moment after all scripts have run (Flatsome, Woo, etc.)
                    setTimeout(function() {
                        let galleryImages = document.querySelectorAll(".woocommerce-product-gallery__image");

                        if (!galleryImages.length) {
                            galleryImages = document.querySelectorAll(".woocommerce-product-gallery__wrapper");
                        }
                        if (!galleryImages.length) {
                            galleryImages = document.querySelectorAll(".woocommerce-product-gallery");
                        }
                        galleryImages.forEach(function(imgWrap) {
                            if (!imgWrap.querySelector(".cpbw-badge-wrapper")) {
                                const wrapper = document.createElement('div');
                                wrapper.className = 'cpbw-badge-wrapper';
                                wrapper.innerHTML = <?php echo wp_json_encode($badge_html); ?>;
                                imgWrap.appendChild(wrapper);
                            }
                        });
                    }, 100);
                });
            </script>
            <?php
        });
    }

    // Use cached settings
    $settings = cpbw_get_cached_settings();

    if ( $settings['show_badge_on'] === 'both' || $settings['show_badge_on'] === 'single' ) {
        add_action( 'woocommerce_before_single_product_summary', 'cpbw_add_badge_to_single_product_image', 5 );
        add_action( 'woocommerce_before_single_product', 'cpbw_add_badge_to_single_product_image', 5 );

        // Breakdance Builder support
        add_action( 'breakdance_after_product_images', 'cpbw_add_badge_to_single_product_image', 5 );
        add_action( 'woocommerce_product_thumbnails', 'cpbw_add_badge_to_single_product_image', 5 );
    }
}


/**
 * Add badge overlays for OceanWP theme product archive images.
 */
if ( ! function_exists( 'cpbw_add_badge_oceanwp' ) ) {
    function cpbw_add_badge_oceanwp() {
        global $product;
        if (!$product) return;

        $badges = cpbw_apply_product_badges($product);
        if (empty($badges)) return;

        $badge_html = '';
        foreach ($badges as $badge) {
            $badge_html .= cpbw_sanitize_badge_html($badge);
        }

        echo '<div class="store-manager-product-badge">' . wp_kses_post($badge_html) . '</div>';
    }

    // Use cached settings
    $settings = cpbw_get_cached_settings();

    if ($settings['show_badge_on'] === 'both' || $settings['show_badge_on'] === 'list') {
        add_action('ocean_after_archive_product_image', 'cpbw_add_badge_oceanwp');
    }
}