
<center><h2><strong>Ubuntu</strong></h2>
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
/**
 * Plugin Name: WooCommerce Unit-Based Shipping
 * Description: Shipping by Classes
 * Version: 1.0.1
 * Author: Yoma Web
 * Text Domain: wc-unit-shipping
 */

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

class WC_Unit_Based_Shipping {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('plugins_loaded', array($this, 'init'));
    }
    
    public function init() {
        if (!class_exists('WooCommerce')) {
            return;
        }
        
        // Add settings to WooCommerce
        add_filter('woocommerce_shipping_settings', array($this, 'add_settings'));
        
        // Calculate shipping
        add_filter('woocommerce_package_rates', array($this, 'calculate_shipping'), 20, 2);
        
        // Add admin notice for configuration
        add_action('admin_notices', array($this, 'admin_notices'));
    }
    
    public function add_settings($settings) {
        $custom_settings = array();
        
        // Section title
        $custom_settings[] = array(
            'title' => __('Unit-Based Shipping Calculator', 'wc-unit-shipping'),
            'type'  => 'title',
            'desc'  => __('Configure shipping costs based on bottle units. Classes: bottle-75cl (1 unit), magnum-150cl (2 units)', 'wc-unit-shipping'),
            'id'    => 'wc_unit_shipping_section'
        );
        
        // Enable/Disable
        $custom_settings[] = array(
            'title'   => __('Enable Unit Calculation', 'wc-unit-shipping'),
            'desc'    => __('Enable automatic shipping cost calculation based on units', 'wc-unit-shipping'),
            'id'      => 'wc_unit_shipping_enabled',
            'default' => 'yes',
            'type'    => 'checkbox',
        );
        
        // Debug mode
        $custom_settings[] = array(
            'title'   => __('Debug Mode', 'wc-unit-shipping'),
            'desc'    => __('Show calculation details in shipping label', 'wc-unit-shipping'),
            'id'      => 'wc_unit_shipping_debug',
            'default' => 'no',
            'type'    => 'checkbox',
        );
        
        // Country
        $custom_settings[] = array(
            'title'    => __('Target Country', 'wc-unit-shipping'),
            'desc'     => __('Country code (e.g., FR for France)', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_country',
            'default'  => 'FR',
            'type'     => 'text',
            'css'      => 'width: 80px;',
        );
        
        // Shipping method to modify
        $custom_settings[] = array(
            'title'    => __('Shipping Method', 'wc-unit-shipping'),
            'desc'     => __('Shipping method ID to modify (e.g., flat_rate)', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_method',
            'default'  => 'flat_rate',
            'type'     => 'text',
        );
        
        // Shipping class units
        $custom_settings[] = array(
            'title' => __('Shipping Class Units', 'wc-unit-shipping'),
            'type'  => 'title',
            'desc'  => __('Define how many units each shipping class represents', 'wc-unit-shipping'),
            'id'    => 'wc_unit_shipping_class_units'
        );
        
        $custom_settings[] = array(
            'title'    => __('bottle-75cl units', 'wc-unit-shipping'),
            'desc'     => __('Number of units for 75cl bottles', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_class_bottle_75cl',
            'default'  => '1',
            'type'     => 'number',
            'custom_attributes' => array('min' => '1', 'step' => '1'),
        );
        
        $custom_settings[] = array(
            'title'    => __('magnum-150cl units', 'wc-unit-shipping'),
            'desc'     => __('Number of units for Magnum 1.5L', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_class_magnum_150cl',
            'default'  => '2',
            'type'     => 'number',
            'custom_attributes' => array('min' => '1', 'step' => '1'),
        );
        
        $custom_settings[] = array(
            'type' => 'sectionend',
            'id'   => 'wc_unit_shipping_class_units'
        );
        
        // Free shipping threshold
        $custom_settings[] = array(
            'title' => __('Free Shipping', 'wc-unit-shipping'),
            'type'  => 'title',
            'id'    => 'wc_unit_shipping_free'
        );
        
        $custom_settings[] = array(
            'title'    => __('Free Shipping Threshold', 'wc-unit-shipping'),
            'desc'     => __('Minimum order amount (incl. tax) for free shipping. Set to 0 to disable.', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_free_threshold',
            'default'  => '390',
            'type'     => 'number',
            'custom_attributes' => array('min' => '0', 'step' => '0.01'),
        );
        
        $custom_settings[] = array(
            'title'    => __('Free Shipping Label', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_free_label',
            'default'  => __('Free shipping (orders ≥ €{amount} incl. tax)', 'wc-unit-shipping'),
            'type'     => 'text',
            'desc'     => __('Use {amount} as placeholder for the threshold amount', 'wc-unit-shipping'),
        );
        
        $custom_settings[] = array(
            'type' => 'sectionend',
            'id'   => 'wc_unit_shipping_free'
        );
        
        // Shipping tiers
        $custom_settings[] = array(
            'title' => __('Shipping Cost Tiers', 'wc-unit-shipping'),
            'type'  => 'title',
            'desc'  => __('Define shipping costs based on total units in cart', 'wc-unit-shipping'),
            'id'    => 'wc_unit_shipping_tiers'
        );
        
        // Tier 1
        $custom_settings[] = array(
            'title'    => __('Tranche 1 : jusqu\'à X unités', 'wc-unit-shipping'),
            'desc'     => __('Maximum units for tier 1 (e.g., 12)', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_tier1_max',
            'default'  => '12',
            'type'     => 'number',
            'custom_attributes' => array('min' => '1', 'step' => '1'),
        );
        
        $custom_settings[] = array(
            'title'    => __('Tranche 1: Shipping Cost', 'wc-unit-shipping'),
            'desc'     => __('Shipping cost in €', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_tier1_cost',
            'default'  => '29',
            'type'     => 'number',
            'custom_attributes' => array('min' => '0', 'step' => '0.01'),
        );
        
        // Tier 2
        $custom_settings[] = array(
            'title'    => __('Tranche 2 : jusqu\'à X unités', 'wc-unit-shipping'),
            'desc'     => __('Maximum units for tier 2 (e.g., 18)', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_tier2_max',
            'default'  => '18',
            'type'     => 'number',
            'custom_attributes' => array('min' => '1', 'step' => '1'),
        );
        
        $custom_settings[] = array(
            'title'    => __('Tranche 2 : Shipping Cost', 'wc-unit-shipping'),
            'desc'     => __('Shipping cost in €', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_tier2_cost',
            'default'  => '37',
            'type'     => 'number',
            'custom_attributes' => array('min' => '0', 'step' => '0.01'),
        );
        
        // Tier 3+
        $custom_settings[] = array(
            'title'    => __('Tranche 3 : +de > bouteilles', 'wc-unit-shipping'),
            'desc'     => __('Shipping cost for orders exceeding tier 2', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_tier3_cost',
            'default'  => '45',
            'type'     => 'number',
            'custom_attributes' => array('min' => '0', 'step' => '0.01'),
        );
        
        $custom_settings[] = array(
            'type' => 'sectionend',
            'id'   => 'wc_unit_shipping_tiers'
        );
        
        // Labels
        $custom_settings[] = array(
            'title' => __('Labels', 'wc-unit-shipping'),
            'type'  => 'title',
            'id'    => 'wc_unit_shipping_labels'
        );
        
        $custom_settings[] = array(
            'title'    => __('Standard Shipping Label', 'wc-unit-shipping'),
            'id'       => 'wc_unit_shipping_standard_label',
            'default'  => __('Shipping - Metropolitan France', 'wc-unit-shipping'),
            'type'     => 'text',
        );
        
        $custom_settings[] = array(
            'type' => 'sectionend',
            'id'   => 'wc_unit_shipping_labels'
        );
        
        // Insert at the end of shipping settings
        return array_merge($settings, $custom_settings);
    }
    
    public function calculate_shipping($rates, $package) {
        // Check if enabled
        if (get_option('wc_unit_shipping_enabled', 'yes') !== 'yes') {
            return $rates;
        }
        
        // Check country
        $target_country = strtoupper(get_option('wc_unit_shipping_country', 'FR'));
        $dest_country = isset($package['destination']['country']) ? strtoupper($package['destination']['country']) : '';
        
        if ($dest_country !== $target_country) {
            return $rates;
        }
        
        // Calculate total units
        $total_units = $this->calculate_cart_units();
        
        // Get order total (TTC) - CORRIGÉ
        $order_total = $this->get_cart_total_with_tax();
        
        // Debug mode
        $debug_mode = get_option('wc_unit_shipping_debug', 'no') === 'yes';
        
        // Determine shipping cost
        $shipping_cost = $this->get_shipping_cost($total_units, $order_total);
        
        // Get target shipping method
        $target_method = get_option('wc_unit_shipping_method', 'flat_rate');
        
        // Apply to rates
        foreach ($rates as $rate_id => $rate) {
            if ($rate->get_method_id() === $target_method) {
                $rates[$rate_id]->set_cost($shipping_cost);
                
                // Set label
                if ($shipping_cost == 0) {
                    $free_threshold = get_option('wc_unit_shipping_free_threshold', 390);
                    $label_template = get_option('wc_unit_shipping_free_label', 
                        __('Free shipping (orders ≥ €{amount} incl. tax)', 'wc-unit-shipping'));
                    $label = str_replace('{amount}', number_format($free_threshold, 2), $label_template);
                    $rates[$rate_id]->set_label($label);
                } else {
                    $label = get_option('wc_unit_shipping_standard_label', 
                        __('Shipping - Metropolitan France', 'wc-unit-shipping'));
                    
                    // Add debug info if enabled
                    if ($debug_mode) {
                        $label .= sprintf(' [Total: %.2f€ TTC / Units: %d]', $order_total, $total_units);
                    }
                    
                    $rates[$rate_id]->set_label($label);
                }
            }
        }
        
        return $rates;
    }
    
    /**
     * Calculate cart total INCLUDING TAX (after discounts)
     * CORRECTION PRINCIPALE
     */
    private function get_cart_total_with_tax() {
        if (!WC()->cart) {
            return 0;
        }
        
        // Méthode fiable : calculer à partir des lignes du panier
        $total = 0;
        
        foreach (WC()->cart->get_cart() as $cart_item) {
            // line_total = prix HT total de la ligne
            // line_tax = TVA de la ligne
            $total += $cart_item['line_total'] + $cart_item['line_tax'];
        }
        
        return $total;
    }
    
    private function calculate_cart_units() {
        $total_units = 0;
        
        if (!WC()->cart) {
            return $total_units;
        }
        
        foreach (WC()->cart->get_cart() as $cart_item) {
            if (empty($cart_item['data']) || !$cart_item['data'] instanceof WC_Product) {
                continue;
            }
            
            $product = $cart_item['data'];
            $quantity = intval($cart_item['quantity']);
            
            // Get shipping class
            $shipping_class = $product->get_shipping_class();
            
            if (empty($shipping_class)) {
                // No shipping class = 1 unit by default
                $units_per_item = 1;
            } else {
                // Get units from settings based on shipping class
                $setting_key = 'wc_unit_shipping_class_' . sanitize_key($shipping_class);
                $units_per_item = intval(get_option($setting_key, 1));
            }
            
            $total_units += $units_per_item * $quantity;
        }
        
        return $total_units;
    }
    
    private function get_shipping_cost($total_units, $order_total) {
        // Check free shipping threshold
        $free_threshold = floatval(get_option('wc_unit_shipping_free_threshold', 390));
        if ($free_threshold > 0 && $order_total >= $free_threshold) {
            return 0;
        }
        
        // Get tier settings
        $tier1_max = intval(get_option('wc_unit_shipping_tier1_max', 12));
        $tier1_cost = floatval(get_option('wc_unit_shipping_tier1_cost', 29));
        
        $tier2_max = intval(get_option('wc_unit_shipping_tier2_max', 18));
        $tier2_cost = floatval(get_option('wc_unit_shipping_tier2_cost', 37));
        
        $tier3_cost = floatval(get_option('wc_unit_shipping_tier3_cost', 45));
        
        // Determine cost based on units
        if ($total_units <= $tier1_max) {
            return $tier1_cost;
        } elseif ($total_units <= $tier2_max) {
            return $tier2_cost;
        } else {
            return $tier3_cost;
        }
    }
    
    public function admin_notices() {
        $screen = get_current_screen();
        if ($screen->id !== 'woocommerce_page_wc-settings') {
            return;
        }
        
        // Check if shipping classes exist
        $shipping_classes = WC()->shipping->get_shipping_classes();
        $has_bottle = false;
        $has_magnum = false;
        
        foreach ($shipping_classes as $class) {
            if ($class->slug === 'bottle-75cl') $has_bottle = true;
            if ($class->slug === 'magnum-150cl') $has_magnum = true;
        }
        
        if (!$has_bottle || !$has_magnum) {
            ?>
            <div class="notice notice-warning">
                <p><strong><?php _e('Unit-Based Shipping:', 'wc-unit-shipping'); ?></strong></p>
                <p><?php _e('Please create the following shipping classes:', 'wc-unit-shipping'); ?></p>
                <ul style="list-style: disc; margin-left: 20px;">
                    <?php if (!$has_bottle): ?>
                    <li><strong>bottle-75cl</strong> - <?php _e('Bouteille 75cl (1 unité)', 'wc-unit-shipping'); ?></li>
                    <?php endif; ?>
                    <?php if (!$has_magnum): ?>
                    <li><strong>magnum-150cl</strong> - <?php _e('Magnum 1,5L (2 unités)', 'wc-unit-shipping'); ?></li>
                    <?php endif; ?>
                </ul>
                <p>
                    <a href="<?php echo admin_url('admin.php?page=wc-settings&tab=shipping&section=classes'); ?>" class="button button-primary">
                        <?php _e('Manage Shipping Classes', 'wc-unit-shipping'); ?>
                    </a>
                </p>
            </div>
            <?php
        }
    }
}

// Initialize plugin
WC_Unit_Based_Shipping::get_instance();