<?php

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

class AIEO_DMM_Badge_Renderer {

    const FLAG_OPTION = 'aieo_dmm_badges_unified_renderer';

    
    private static $hooks_registered = false;

    public static function bootstrap() {
        if (self::$hooks_registered) { return; }
        self::$hooks_registered = true;

        
        
        add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_styles'));

        if (!self::is_enabled()) { return; }

        
        add_action('woocommerce_before_shop_loop_item_title', array(__CLASS__, 'render_archive'), 11);

        
        
        
        add_filter('render_block_woocommerce/product-image-gallery', array(__CLASS__, 'inject_pdp_gallery'), 10, 2);
    }

    public static function is_enabled() {
        return (bool) get_option(self::FLAG_OPTION, 0);
    }

    public static function enqueue_styles() {
        
        
        
        
        if (self::is_enabled()) {
            $rel = 'assets/css/aieo-badge-system.css';
            $abs = dirname(AIEO_FILE) . '/' . $rel;
            $ver = file_exists($abs) ? filemtime($abs) : (defined('AIEO_VERSION') ? AIEO_VERSION : '1.0');
            wp_enqueue_style('aieo-badge-system', plugins_url($rel, AIEO_FILE), array(), $ver);
        }

        
        
        
        
        
        
        
        
        if (class_exists('AIEO_DMM_Badges')) {
            $settings = AIEO_DMM_Badges::get_settings();
            if (!empty($settings['hide_wc_onsale'])) {
                $css = '.woocommerce span.onsale,'
                     . '.woocommerce .onsale,'
                     . 'ul.products li.product .onsale,'
                     . '.products .product .onsale,'
                     . '.wc-block-grid__product-onsale,'
                     . '.wc-block-grid__product .onsale,'
                     . '.wp-block-woocommerce-product-sale-badge,'
                     . '.wc-block-product-template .onsale,'
                     . '.wp-block-woocommerce-product-template .onsale,'
                     . '.om-ppe-product-labels,'
                     . '.om-ppe-label'
                     . '{display:none !important;}';
                
                
                
                if (self::is_enabled()) {
                    wp_add_inline_style('aieo-badge-system', $css);
                } else {
                    wp_register_style('aieo-badge-onsale-hide', false);
                    wp_enqueue_style('aieo-badge-onsale-hide');
                    wp_add_inline_style('aieo-badge-onsale-hide', $css);
                }
            }
        }
    }

    
    
    

    
    public static function resolve_for_product($product, $surface = 'archive', $audience = null) {
        if (!class_exists('AIEO_DMM_Badges')) { return array(); }
        $settings = AIEO_DMM_Badges::get_settings();

        $product_id = is_object($product) && method_exists($product, 'get_id')
            ? (int) $product->get_id() : (int) $product;
        if ($product_id <= 0) { return array(); }

        if ($audience === null) {
            $audience = class_exists('AIEO_Identity_Bridge')
                ? AIEO_Identity_Bridge::audience_key_for_current_user()
                : 'guest';
        }

        $price_row = class_exists('AIEO_Effective_Prices')
            ? AIEO_Effective_Prices::get_for($product_id, $audience)
            : null;

        $out = array();

        
        if (self::family_visible('sale', $surface, $settings)) {
            
            
            
            $on_sale = self::runtime_is_on_sale($product_id);
            if ($on_sale) {
                $out[] = self::dto('sale', $settings, array(
                    'discount_pct' => is_array($price_row) ? ($price_row['sale_discount_pct'] ?? null) : null,
                ));
            }
        }

        
        if (self::family_visible('monthly_offer', $surface, $settings)) {
            $mo = is_array($price_row) ? !empty($price_row['monthly_offer_active'])
                : (class_exists('AIEO_DMM_Brand_Discounts') && AIEO_DMM_Brand_Discounts::is_monthly_offer_active($product_id));
            if ($mo) { $out[] = self::dto('monthly_offer', $settings); }
        }

        
        
        
        if (self::family_visible('pro', $surface, $settings)) {
            $role_applied = is_array($price_row) && !empty($price_row['role_price_applied']);
            if ($role_applied) { $out[] = self::dto('pro', $settings); }
        }

        
        if (self::family_visible('new', $surface, $settings)) {
            $is_new = class_exists('AIEO_DMM_Brand_Discounts')
                && AIEO_DMM_Brand_Discounts::is_new_product($product_id);
            if ($is_new) { $out[] = self::dto('new', $settings); }
        }

        
        
        
        if (self::family_visible('gift', $surface, $settings)) {
            $gift_row = class_exists('AIEO_Effective_Eligibility')
                ? AIEO_Effective_Eligibility::get_for(AIEO_Effective_Eligibility::SURFACE_BRAND_GIFT, $audience, $product_id)
                : null;
            if (!is_array($gift_row) && class_exists('AIEO_DMM_Brand_Gifts')) {
                $rt = AIEO_DMM_Brand_Gifts::is_eligible_for($product_id, $audience);
                if (!empty($rt['eligible'])) {
                    $gift_row = array(
                        'eligible' => 1,
                        'offer_id' => $rt['offer_id'] ?? null,
                        'payload'  => $rt['payload'] ?? array(),
                    );
                }
            }
            if (is_array($gift_row) && !empty($gift_row['eligible'])) {
                $out[] = self::dto('gift', $settings, array(
                    'offer_label' => isset($gift_row['payload']['label']) ? (string) $gift_row['payload']['label'] : '',
                ));
            }
        }

        
        usort($out, function($a, $b) { return (int) $a['order'] - (int) $b['order']; });
        return $out;
    }

    private static function family_visible($key, $surface, array $settings) {
        $f = isset($settings['families'][$key]) ? $settings['families'][$key] : null;
        if (!$f || empty($f['enabled'])) { return false; }
        return !empty($f['surfaces'][$surface]);
    }

    private static function dto($key, array $settings, array $extra = array()) {
        $f = $settings['families'][$key];
        $label = (string) $f['label'];
        if ($key === 'sale' && !empty($extra['discount_pct'])) {
            
            if (strpos($label, '{sale}') !== false) {
                $label = str_replace('{sale}', round((float) $extra['discount_pct']) . '%', $label);
            }
        }
        if ($key === 'gift' && !empty($extra['offer_label'])) {
            $label = (string) $extra['offer_label'];
        }
        return array(
            'family'    => $key,
            'label'     => $label,
            'icon'      => isset($f['icon']) ? (string) $f['icon'] : '',
            
            
            
            
            'icon_image_url' => isset($f['icon_image_url']) ? (string) $f['icon_image_url'] : '',
            'tooltip'   => isset($f['tooltip']) ? (string) $f['tooltip'] : '',
            'bg'        => (string) $f['bg'],
            'fg'        => (string) $f['fg'],
            'order'     => (int) $f['order'],
        );
    }

    
    
    

    
    public static function render_for_product($product, $surface) {
        $badges = self::resolve_for_product($product, $surface);
        if (empty($badges)) { return ''; }

        
        
        
        
        
        $stack_style = '';
        if (class_exists('AIEO_DMM_Badges')) {
            $settings = AIEO_DMM_Badges::get_settings();
            $sz       = isset($settings['sizes'][$surface]) ? $settings['sizes'][$surface] : array();
            $d = is_array($sz) && isset($sz['desktop']) ? (int) $sz['desktop'] : 0;
            $m = is_array($sz) && isset($sz['mobile'])  ? (int) $sz['mobile']  : 0;
            $vars = array();
            if ($d > 0) { $vars[] = '--aieo-badge-fs-d:' . $d . 'px'; }
            if ($m > 0) { $vars[] = '--aieo-badge-fs-m:' . $m . 'px'; }
            if (!empty($vars)) { $stack_style = ' style="' . implode(';', $vars) . ';"'; }
        }

        $stack = '<div class="aieo-badge-stack" data-surface="' . esc_attr($surface) . '"' . $stack_style . '>';
        foreach ($badges as $b) {
            $style = sprintf(
                '--aieo-badge-bg:%s;--aieo-badge-fg:%s;order:%d;',
                esc_attr($b['bg']), esc_attr($b['fg']), (int) $b['order']
            );
            $cls = 'aieo-badge aieo-badge--' . sanitize_html_class($b['family']);
            $title_attr = $b['tooltip'] !== '' ? ' title="' . esc_attr($b['tooltip']) . '"' : '';

            $img_url = isset($b['icon_image_url']) ? (string) $b['icon_image_url'] : '';
            if ($img_url !== '') {
                
                
                
                $alt = $b['label'] !== '' ? $b['label'] : $b['family'];
                $stack .= '<span class="' . esc_attr($cls) . ' has-icon-image" style="' . $style . '"' . $title_attr . '>'
                       . '<img class="aieo-badge__image" src="' . esc_url($img_url) . '" alt="' . esc_attr($alt) . '" loading="lazy" decoding="async">'
                       . '</span>';
            } else {
                $icon = $b['icon'] !== '' ? '<span class="aieo-badge__icon">' . esc_html($b['icon']) . '</span>' : '';
                $stack .= '<span class="' . esc_attr($cls) . '" style="' . $style . '"' . $title_attr . '>'
                       . $icon
                       . '<span class="aieo-badge__label">' . esc_html($b['label']) . '</span>'
                       . '</span>';
            }
        }
        $stack .= '</div>';
        return $stack;
    }

    public static function render_archive() {
        global $product;
        if (!$product) { return; }
        $html = self::render_for_product($product, 'archive');
        if ($html === '') { return; }
        
        echo $html;
    }

    public static function inject_pdp_gallery($block_content, $block) {
        if (!is_singular('product')) { return $block_content; }
        global $product;
        if (!$product) { return $block_content; }
        $stack = self::render_for_product($product, 'pdp');
        if ($stack === '') { return $block_content; }
        
        
        return preg_replace(
            '/(<div\s[^>]*wp-block-woocommerce-product-image-gallery[^>]*>)/',
            '$1' . $stack,
            $block_content,
            1
        );
    }

    
    public static function dto_for_product($product, $surface) {
        $badges = self::resolve_for_product($product, $surface);
        $compact = array();
        foreach ($badges as $b) {
            $compact[] = array(
                'f' => $b['family'],
                'l' => $b['label'],
                'i' => $b['icon'],
                
                
                
                
                'm' => isset($b['icon_image_url']) ? (string) $b['icon_image_url'] : '',
                'b' => $b['bg'],
                'g' => $b['fg'],
                'o' => $b['order'],
            );
        }
        return $compact;
    }

    
    
    

    private static function runtime_is_on_sale($product_id) {
        
        
        
        
        
        
        $live_below_regular = static function ($pid) {
            $reg  = get_post_meta((int) $pid, '_regular_price', true);
            $live = get_post_meta((int) $pid, '_price', true);
            if ($reg === '' || $live === '') { return false; }
            
            
            $reg  = (float) str_replace(',', '.', (string) $reg);
            $live = (float) str_replace(',', '.', (string) $live);
            return ($live > 0 && $live < $reg);
        };
        if ($live_below_regular($product_id)) { return true; }
        $p = function_exists('wc_get_product') ? wc_get_product($product_id) : null;
        if ($p && method_exists($p, 'is_type') && $p->is_type('variable')) {
            foreach ((array) $p->get_children() as $vid) {
                if ($live_below_regular($vid)) { return true; }
            }
        }
        return false;
    }
}
