
<center><h2><strong>Ubuntu</strong></h2>
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
/**
 * Enqueue script and styles for child theme
 */
function woodmart_child_enqueue_styles() {
	wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( 'woodmart-style' ), woodmart_get_theme_info( 'Version' ) );
}
add_action( 'wp_enqueue_scripts', 'woodmart_child_enqueue_styles', 10010 );

// Ajouter le support du format WebP pour les téléchargements d'images
function ajout_format_webp($mime_types) {
    $mime_types['webp'] = 'image/webp';
    return $mime_types;
}
add_filter('upload_mimes', 'ajout_format_webp');

// Convertir img to WebP
function convertir_en_webp($attachment_id) {
    $fichier = get_attached_file($attachment_id);
    
    $extensions_acceptees = array('jpg', 'jpeg', 'png'); 
    
    $extension = pathinfo($fichier, PATHINFO_EXTENSION);
    
    if (in_array(strtolower($extension), $extensions_acceptees)) {
        if (strtolower($extension) === 'jpg' || strtolower($extension) === 'jpeg') {
            $img = imagecreatefromjpeg($fichier);
        } elseif (strtolower($extension) === 'png') {
            $img = imagecreatefrompng($fichier);
        }
        
        $nouveau_fichier = substr($fichier, 0, -strlen($extension)) . 'webp';
        imagewebp($img, $nouveau_fichier, 95); // 95 est la qualité de l'image WebP (modifiable si nécessaire)
        imagedestroy($img);
        
        update_attached_file($attachment_id, $nouveau_fichier);
    }
}
add_action('add_attachment', 'convertir_en_webp');

/**
 * Ajoute un champ "Récompense" pour les produits WooCommerce.
 * Affiche le texte sur la fiche produit si rempli.
 */

add_action('woocommerce_product_options_general_product_data', function () {
    woocommerce_wp_text_input([
        'id'          => '_product_reward',
        'label'       => __('Récompense', 'woocommerce'),
        'placeholder' => __('Ex. : Médaille d’or 2024 au Concours de Mâcon', 'woocommerce'),
        'desc_tip'    => true,
        'description' => __('Indiquez ici la récompense ou médaille obtenue.', 'woocommerce'),
    ]);
});

add_action('woocommerce_admin_process_product_object', function ($product) {
    if (isset($_POST['_product_reward'])) {
        $reward = wp_strip_all_tags(wp_unslash($_POST['_product_reward']));
        $product->update_meta_data('_product_reward', $reward);
    }
});

add_action('woocommerce_single_product_summary', function () {
    global $product;
    if (!$product instanceof WC_Product) {
        return;
    }

    $reward = $product->get_meta('_product_reward');
    if (!empty($reward)) {
        echo '<div class="product-reward" style="margin-top:8px; font-size:16px; font-weight:500; color:#fff;background-color:#AE9B73;padding:8px;text-align:center">';
        echo esc_html($reward);
        echo '</div>';
    }
}, 6); 


/**
 * Capacité carton (6 unités) avec magnums comptant pour 2.
 * - Ajoute un champ admin "Unités carton" (1 pour 75cl, 2 pour magnum, etc.)
 * - Valide le panier : la somme (unités_carton * quantité) doit être un multiple de 6
 * - Message clair indiquant le nombre d'unités manquantes
 */
add_action('woocommerce_product_options_general_product_data', function () {
    woocommerce_wp_text_input([
        'id'          => '_carton_units',
        'label'       => __('Unités carton', 'your-textdomain'),
        'placeholder' => '1',
        'type'        => 'number',
        'custom_attributes' => [
            'min'  => '1',
            'step' => '1',
        ],
        'desc_tip'    => true,
        'description' => __('Nombre d’unités prises dans le carton (ex. 1 pour 75cl, 2 pour magnum).', 'your-textdomain'),
    ]);
});

add_action('woocommerce_admin_process_product_object', function (WC_Product $product) {
    if (isset($_POST['_carton_units'])) {
        $units = (int) wp_unslash($_POST['_carton_units']);
        if ($units < 1) { $units = 1; }
        $product->update_meta_data('_carton_units', $units);
    }
});

// Helper
function cayx_get_carton_units_for_product($product_id) {
    $units = (int) get_post_meta($product_id, '_carton_units', true);
    return $units > 0 ? $units : 1; // default = 1
}

add_action('woocommerce_check_cart_items', function () {
    if (is_admin() && ! defined('DOING_AJAX')) return;
    
    $total_units = 0;
    foreach (WC()->cart->get_cart() as $cart_item) {
        $product   = $cart_item['data'];
        if (! $product instanceof WC_Product) continue;
        $units     = cayx_get_carton_units_for_product($product->get_id());
        $qty       = (int) $cart_item['quantity'];
        $total_units += $units * $qty;
    }
    
    // Multiples by 6
    $carton_size = 6;
    $remainder   = $total_units % $carton_size;
    
    if ($remainder !== 0) {
        $missing = $carton_size - $remainder; // unités à ajouter pour compléter le carton
        
        // Suggestions rapides : équivalents en 75cl (1) ou magnum (2)
        $suggest_75cl = $missing;                           // nb de 75cl à ajouter
        $suggest_mag  = (int) ceil($missing / 2);           // nb de magnums pour compléter
        
        // Message français
        $message_fr = sprintf(
            'Votre sélection occupe <strong>%1$d unité(s)</strong> de carton. Les cartons se vendent par 6 unités. ' .
            'Il vous manque <strong>%2$d unité(s)</strong> pour compléter votre carton. ' .
            'Par exemple, ajoutez %3$d bouteille(s) 75cl ou %4$d magnum(s).',
            $total_units,
            $missing,
            $suggest_75cl,
            $suggest_mag
        );
        
        // Message anglais
        $message_en = sprintf(
            'Your selection uses <strong>%1$d unit(s)</strong> of carton. Cartons are sold in sets of 6 units. ' .
            'You need <strong>%2$d more unit(s)</strong> to complete your carton. ' .
            'For example, add %3$d bottle(s) 75cl or %4$d magnum(s).',
            $total_units,
            $missing,
            $suggest_75cl,
            $suggest_mag
        );
        
        // Détection de la langue (ajustez selon votre plugin multilingue)
        $current_lang = get_locale(); // ou pll_current_language() pour Polylang, ou ICL_LANGUAGE_CODE pour WPML
        
        $message = ($current_lang === 'fr_FR') ? $message_fr : $message_en;
        
        wc_add_notice($message, 'error');
    }
});
/*
add_filter('woocommerce_package_rates', function ($rates, $package) {
    // Apply only to Metropolitan France
    $dest_country = isset($package['destination']['country']) ? $package['destination']['country'] : '';
    if (strtoupper($dest_country) !== 'FR') {
        return $rates; // do not modify for other countries
    }

    // Calculate the total "bottle-units" in the cart (magnum = 2, 75cl = 1)
    $total_units = 0;
    if (!empty(WC()->cart)) {
        foreach (WC()->cart->get_cart() as $item) {
            if (empty($item['data']) || ! $item['data'] instanceof WC_Product) continue;
            $product_id = $item['data']->get_id();
            $qty        = (int) $item['quantity'];
            $units      = (int) get_post_meta($product_id, '_carton_units', true);
            if ($units < 1) $units = 1; // safety check
            $total_units += $units * $qty;
        }
    }
    $order_total_ttc = WC()->cart ? WC()->cart->get_total('edit') : 0; // TTC
    $shipping_cost = 0;
    if ($order_total_ttc >= 390) {
        $shipping_cost = 0;
    } else {
        if ($total_units <= 12) {
            $shipping_cost = 29;
        } elseif ($total_units <= 18) {
            $shipping_cost = 37;
        } else {
            $shipping_cost = 45;
        }
    }
    foreach ($rates as $rate_id => $rate) {
        if ($rate->get_method_id() === 'flat_rate') {
            $rates[$rate_id]->set_cost($shipping_cost);
            if ($shipping_cost == 0 && $order_total_ttc >= 390) {
                $rates[$rate_id]->set_label(__('Free shipping (orders ≥ €390 incl. tax)', 'your-textdomain'));
            } else {
                $rates[$rate_id]->set_label(__('Shipping - Metropolitan France', 'your-textdomain'));
            }
        }
    }

    return $rates;
}, 20, 2);*/

remove_action('woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10);
// Supprimer le champ coupon de la page de paiement/checkout
add_filter('woocommerce_coupons_enabled', '__return_false');
// Supprimer le champ coupon du panier
add_filter('woocommerce_cart_totals_coupon_html', '__return_empty_string');

// Shortcode pour texte multilingue dans les modèles
function ml_text_shortcode($atts) {
    $atts = shortcode_atts(array(
        'fr' => '',
        'en' => '',
    ), $atts);
    
    // Détection langue (ajustez selon votre plugin)
    $current_lang = get_locale();
    
    // Pour Polylang
    // $current_lang = function_exists('pll_current_language') ? pll_current_language() : 'fr';
    
    // Pour WPML
    // $current_lang = defined('ICL_LANGUAGE_CODE') ? ICL_LANGUAGE_CODE : 'fr';
    
    if (strpos($current_lang, 'en') !== false || $current_lang === 'en') {
        return $atts['en'];
    }
    
    return $atts['fr'];
}
add_shortcode('ml', 'ml_text_shortcode');