<?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;

/**
 * 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.
 * Only allow <style> tags and inline styles on div/span for badges.
 */
if ( ! function_exists( 'cpbw_sanitize_badge_html' ) ) {
    function cpbw_sanitize_badge_html($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 );
}


if ( ! function_exists( 'cpbw_add_badge_loop_woodmart' ) ) {

    function cpbw_add_badge_loop_woodmart() {
        global $product;

        if ( ! $product ) return;

        if (
            Settings::get('show_badge_on') !== 'both' &&
            Settings::get('show_badge_on') !== 'list'
        ) {
            return;
        }

        $theme     = wp_get_theme();
        $name      = strtolower( $theme->get( 'Name' ) );
        $template  = strtolower( $theme->get( 'Template' ) );

        // ✅ WoodMart OR WoodMart child AND template is woodmart
        $is_woodmart = (
            strpos( $template, 'woodmart' ) !== false &&
            (
                strpos( $name, 'woodmart' ) !== false ||
                strpos( $template, 'woodmart' ) !== false
            )
        );

        if ( ! $is_woodmart ) {
            return;
        }

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

        echo '<div class="cpbw-product-badge-wrapper">';
        foreach ( $badges as $badge ) {
            echo cpbw_sanitize_badge_html( $badge );
        }
        echo '</div>';
    }

    add_action( 'woocommerce_before_shop_loop_item_title', 'cpbw_add_badge_loop_woodmart', 5 );
}


