/* 
Theme Name: Hello Child
Theme URI: https://elementor-site.ir/
Description: 
Author: Elementor Site
Author URI: https://elementor-site.ir/
Template: hello-elementor
Version: 1.0.1
Text Domain: hello-elementor-child
License: GNU General Public License v3 or later.
License URI: https://www.gnu.org/licenses/gpl-3.0.html
Tags: flexible-header, custom-colors, custom-menu, custom-logo, editor-style, featured-images, rtl-language-support, threaded-comments, translation-ready
*/

 // Shortcode: [product_sale_percent]
add_shortcode( 'product_sale_percent', function() {

    global $product;

    if ( ! $product ) return '';

    // اگر محصول متغیر هست، باید از بیشترین تخفیف متغیرها استفاده کنیم
    if ( $product->is_type('variable') ) {
        $available_variations = $product->get_available_variations();
        $max_discount = 0;

        foreach ( $available_variations as $variation ) {
            $regular = $variation['display_regular_price'];
            $sale    = $variation['display_price'];

            if ( $regular > 0 && $sale < $regular ) {
                $percent = round( ( ( $regular - $sale ) / $regular ) * 100 );
                if ( $percent > $max_discount ) {
                    $max_discount = $percent;
                }
            }
        }

        return $max_discount > 0 ? $max_discount . '%' : '';
    }

    // محصولات ساده
    $regular_price = (float) $product->get_regular_price();
    $sale_price    = (float) $product->get_sale_price();

    if ( $regular_price > 0 && $sale_price < $regular_price ) {
        $percent = round( ( ( $regular_price - $sale_price ) / $regular_price ) * 100 );
        return $percent . '%';
    }

    return '';
});