<?php

namespace CPBW\App;

use CPBW\App\Utilities\BadgeHelper;
use CPBW\App\Multilingual\Wpml;
use CPBW\App\Multilingual\TranslatePress;
use CPBW_PRO\App\Utilities\Conditions;

class Badge {

    /**
     * Check if the product passes the filter conditions for applying a badge.
     *
     * This function checks the product against the filter conditions defined in the badge configuration.
     * If the filter is 'all', the product passes. If it's a numeric value, further filtering logic can be applied.
     * If it's an array, the function checks if the product ID matches any of the filter criteria.
     *
     * @param \WC_Product $product      The WooCommerce product object.
     * @param array       $badge_config The configuration array for the badge, including the 'filter' field.
     *
     * @return bool True if the product passes the filter conditions, false otherwise.
     */ 
    public function apply_product_badges( $product ) {
        if ( ! ( $product instanceof \WC_Product ) ) {
            return false;
        }
    
        // Get all active badges
        $active_badges = BadgeHelper::get_badges_for_apply(1);
        $applied_badges = [];
    
        foreach ( $active_badges as $badge_config ) {
            // Check product filter condition
            if ( ! self::is_product_passed( $product, $badge_config ) ) {
                continue;
            }
    
            // Check date validity
            if ( ! self::is_in_valid_date( $badge_config ) ) {
                continue;
            }
    
            // Add the applied badge (you can decide what structure to store)
            $applied_badges[] = self::apply_badge_style( $badge_config, $product );
        }
    
        // Return all applied badge data (can be rendered in template)
        return ! empty( $applied_badges ) ? $applied_badges : false;
    }
    

    /**
     * Apply badge style as an overlay on the product image.
     *
     * This function adds a styled badge overlay on top of the product image using the badge configuration.
     *
     * @param string $badge        The original product image HTML.
     * @param array  $badge_config The configuration array for the badge, including the 'badge_style' field.
     *
     * @return string The product image HTML with the badge overlay applied.
     */ 
    public static function apply_badge_style( $badge_config, $product ) {

        $is_pro = is_plugin_active( 'custom-product-badge-for-woocommerce-pro/custom-product-badge-for-woocommerce-pro.php' );

        // Apply translation via whichever multilingual plugin is active.
        if ( Wpml::is_active() ) {
            $badge = Wpml::translate_badge_style( $badge_config );
        } elseif ( TranslatePress::is_active() ) {
            $badge = TranslatePress::translate_badge_style( $badge_config );
        } else {
            $badge = maybe_unserialize( $badge_config['badge_style'] );
        }
    
        $dynamic_badge = [
            '{{discount_percentage}}', 
            '{{discount_value}}', 
            '{{regular_price}}', 
            '{{sale_price}}',
            '{{category_name}}',
            '{{tag_name}}',
            '{{brand_name}}',
            '{{regular_price_with_tax}}',
            '{{sale_price_with_tax}}',
            '{{stock_quantity}}'
        ];
    
        // Create a regex pattern that matches any of the dynamic placeholders
        $badge_pattern = '/(' . implode('|', array_map('preg_quote', $dynamic_badge)) . ')/';
    
        $is_dynamic_badge = preg_match( $badge_pattern, $badge );

        if( $is_pro && $is_dynamic_badge ) {
            $badge = apply_filters( 'cpbw_pro_badge', $badge_config, $product );
        }
    
        return $badge;
    }
    

   /**
     * Check if the product passes the filter conditions for applying a badge.
     *
     * This function checks the product against the filter conditions defined in the badge configuration.
     * If the filter is 'all', the product passes. If it's a numeric value, further filtering logic can be applied.
     * If it's an array, the function checks if the product ID matches any of the filter criteria.
     *
     * @param \WC_Product $product      The WooCommerce product object.
     * @param array       $badge_config The configuration array for the badge, including the 'filter' field.
     *
     * @return bool True if the product passes the filter conditions, false otherwise.
     */
    public static function is_product_passed( $product, $badge_config ){

        $filter = maybe_unserialize($badge_config['filter']);

        if( $filter == 'all' ) {
            return true;
        }

        if( is_numeric( $filter ) && is_plugin_active( 'custom-product-badge-for-woocommerce-pro/custom-product-badge-for-woocommerce-pro.php' ) ) {
            // Filter the product.
		    $info = array( 'product' => $product );
            $condition = new Filter();
            $condition = $condition->get_row($filter);

            if ( empty( $condition ) ) {
                return false;
            }
            

            if ( ( new Conditions( $condition, $info ) )->is_passed() ) {
                return true;
            }
        }

        if ( is_array( $filter ) ) {
            foreach ( $filter as $filter_product ) {
                if ( is_array( $filter_product ) && ( $product->get_id() == $filter_product['id'] ) ) {
                    return true;
                }
            }
        }
    }

    /**
     * Check if the current date is within the valid date range for a badge.
     *
     * This function checks the `valid_from` and `valid_to` dates in the badge configuration 
     * to determine if the badge is valid for the current date. If no date range is specified, 
     * the badge is considered valid by default.
     *
     * @param array $badge_config An associative array containing badge configuration, 
     *                            which may include 'valid_from' and 'valid_to' dates.
     *
     * @return bool True if the current date is within the valid range, or if no valid date 
     *              range is specified. False if the current date is outside the valid range.
     */
    public static function is_in_valid_date( $badge_config ) {

        $now = time(); // UTC-safe current timestamp

        $has_from = ! empty( $badge_config['valid_from'] )
            && strtotime( $badge_config['valid_from'] ) !== false;

        $has_to = ! empty( $badge_config['valid_to'] )
            && strtotime( $badge_config['valid_to'] ) !== false;

        // No date limits → always valid
        if ( ! $has_from && ! $has_to ) {
            return true;
        }

        // Only start date
        if ( $has_from && ! $has_to ) {
            return $now >= strtotime( $badge_config['valid_from'] );
        }

        // Only end date
        if ( ! $has_from && $has_to ) {
            return $now <= strtotime( $badge_config['valid_to'] );
        }

        // Start + end date
        if ( $has_from && $has_to ) {
            $start = strtotime( $badge_config['valid_from'] );
            $end   = strtotime( $badge_config['valid_to'] );

            return ( $now >= $start ) && ( $now <= $end );
        }

        return false;
    }


    /**
     * Check if the Pro version of the plugin is active.
     *
     * @return bool True if the Pro version is active, false otherwise.
     */
    public static function is_pro() {
        return is_plugin_active( 'custom-product-badge-for-woocommerce-pro/custom-product-badge-for-woocommerce-pro.php' );
    }

    /**
     * Check if pro active license is valid.
     * 
     * @return bool True if the license is valid, false otherwise.
     */

    public static function is_license_active() {
        if ( ! function_exists( 'cpbfw_fs' ) ) {
            return false;
        }

        $fs = cpbfw_fs();

        return (
            $fs->is_registered() &&
            $fs->is_premium() &&
            $fs->has_active_valid_license()
        );
    }

}