<?php

function tulipwork_orderstock_settings_page() {
    $settings_message = '';

    wp_enqueue_style('tulipwork_orderstock-admin-css', plugins_url('orderstock/includes/css/orderstock-admin.css'), [], OrderStock::get_version());

    // Gestion de la sauvegarde des paramètres
    if (isset($_POST['tulipwork_orderstock_settings_save']) && 
        isset($_POST['nonce']) && 
        wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'tulipwork_orderstock_settings_nonce')) {
        if (isset($_POST['admin_emails'])) {
            update_option('tulipwork_orderstock_admin_emails', sanitize_text_field(wp_unslash($_POST['admin_emails'])));
        }
        if (isset($_POST['company_name'])) {
            update_option('tulipwork_orderstock_company_name', sanitize_text_field(wp_unslash($_POST['company_name'])));
        }
        if (isset($_POST['company_address'])) {
            update_option('tulipwork_orderstock_company_address', sanitize_textarea_field(wp_unslash($_POST['company_address'])));
        }
        if (isset($_POST['company_phone'])) {
            update_option('tulipwork_orderstock_company_phone', sanitize_text_field(wp_unslash($_POST['company_phone'])));
        }
        if (isset($_POST['company_email'])) {
            $email = sanitize_email(wp_unslash($_POST['company_email']));
            if (is_email($email)) {
                update_option('tulipwork_orderstock_company_email', $email);
            }
        }
        if (isset($_POST['company_siret'])) {
            update_option('tulipwork_orderstock_company_siret', sanitize_text_field(wp_unslash($_POST['company_siret'])));
        }
        if (isset($_POST['tax_rate_1'])) {
            $tax_rate_1 = str_replace(',', '.', sanitize_text_field(wp_unslash($_POST['tax_rate_1'])));
            $tax_rate_1 = floatval($tax_rate_1);
            if ($tax_rate_1 >= 0) {
                update_option('tulipwork_orderstock_tax_rate_1', $tax_rate_1);
            }
        }
        if (isset($_POST['tax_rate_2'])) {
            $tax_rate_2 = str_replace(',', '.', sanitize_text_field(wp_unslash($_POST['tax_rate_2'])));
            $tax_rate_2 = floatval($tax_rate_2);
            if ($tax_rate_2 >= 0) {
                update_option('tulipwork_orderstock_tax_rate_2', $tax_rate_2);
            }
        }
        if (isset($_POST['tax_rate_3'])) {
            $tax_rate_3 = str_replace(',', '.', sanitize_text_field(wp_unslash($_POST['tax_rate_3'])));
            $tax_rate_3 = floatval($tax_rate_3);
            if ($tax_rate_3 >= 0) {
                update_option('tulipwork_orderstock_tax_rate_3', $tax_rate_3);
            }
        }
        if (isset($_POST['order_mode']) && in_array($_POST['order_mode'], ['forecast', 'threshold'])) {
            update_option('orderstock_order_mode', sanitize_text_field(wp_unslash($_POST['order_mode'])));
        }
        if (!defined('TULIPWORK_SAAS_MODE') || !TULIPWORK_SAAS_MODE || is_super_admin()) {
            if (isset($_POST['delete_data_on_uninstall'])) {
                update_option('tulipwork_orderstock_delete_data_on_uninstall', 1);
            } else {
                update_option('tulipwork_orderstock_delete_data_on_uninstall', 0);
            }
        }
        $settings_message = '<div class="orderstock-notice orderstock-notice--success"><p>' . esc_html__('Settings saved!', 'orderstock') . '</p></div>';
    }

    // Gestion de la suppression immédiate
    if (isset($_POST['tulipwork_orderstock_delete_all']) && 
    isset($_POST['delete_nonce']) && 
    wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['delete_nonce'])), 'tulipwork_orderstock_delete_all_nonce') &&
    current_user_can('manage_options')) {
    tulipwork_orderstock_cleanup_site(get_current_blog_id(), true, true);
    // Rediriger vers la page d'accueil d'OrderStock pour éviter les erreurs de permissions
    wp_safe_redirect(admin_url('admin.php?page=tulipwork_orderstock'));
    exit;
    }

    if (isset($_POST['tulipwork_orderstock_pro_save']) && 
    isset($_POST['nonce']) && 
    wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'tulipwork_orderstock_settings_nonce')) {
    if (isset($_POST['orderstock_pro_central_kitchen_enabled'])) {
        update_option('orderstock_pro_central_kitchen_enabled', 1);
    } else {
        update_option('orderstock_pro_central_kitchen_enabled', 0);
    }
    if (isset($_POST['orderstock_pro_central_kitchen'])) {
        update_option('orderstock_pro_central_kitchen', sanitize_text_field(wp_unslash($_POST['orderstock_pro_central_kitchen'])));
    }
    $settings_message = '<div class="orderstock-notice orderstock-notice--success"><p>' . esc_html__('Pro Settings saved!', 'orderstock-pro') . '</p></div>';
    }

    $active_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'general';
    $admin_emails = get_option('tulipwork_orderstock_admin_emails', get_option('admin_email'));
    $company_name = get_option('tulipwork_orderstock_company_name', '');
    $company_address = get_option('tulipwork_orderstock_company_address', '');
    $company_phone = get_option('tulipwork_orderstock_company_phone', '');
    $company_email = get_option('tulipwork_orderstock_company_email', '');
    $company_siret = get_option('tulipwork_orderstock_company_siret', '');
    $tax_rate_1 = get_option('tulipwork_orderstock_tax_rate_1', 5.5);
    $tax_rate_2 = get_option('tulipwork_orderstock_tax_rate_2', 10.0);
    $tax_rate_3 = get_option('tulipwork_orderstock_tax_rate_3', 20.0);
    $is_premium = tulipwork_orderstock_is_premium();
    $pro_active = function_exists('is_plugin_active') && is_plugin_active('orderstock-pro/orderstock-pro.php');
    $is_saas = defined('TULIPWORK_SAAS_MODE') && TULIPWORK_SAAS_MODE;

    ?>
    <div class="wrap">
        <h1><?php esc_html_e('OrderStock Settings', 'orderstock'); ?></h1>

        <h2 class="nav-tab-wrapper">
            <a href="?page=tulipwork_orderstock-settings&tab=general" class="nav-tab <?php echo $active_tab === 'general' ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('General', 'orderstock'); ?></a>
            <?php if ($pro_active && !$is_saas) : ?>
                <a href="?page=tulipwork_orderstock-settings&tab=license" class="nav-tab <?php echo $active_tab === 'license' ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('License', 'orderstock'); ?></a>
            <?php endif; ?>
            <a href="?page=tulipwork_orderstock-settings&tab=pro" class="nav-tab <?php echo $active_tab === 'pro' ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('Pro Settings', 'orderstock'); ?></a>
            <?php if (!$is_saas) : ?>
                <a href="?page=tulipwork_orderstock-settings&tab=support" class="nav-tab <?php echo $active_tab === 'support' ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('Support the Plugin', 'orderstock'); ?></a>
            <?php endif; ?>
        </h2>

        <div class="settings-content">
            <?php if ($active_tab === 'general') : ?>
                <form method="post" action="">
                    <?php wp_nonce_field('tulipwork_orderstock_settings_nonce', 'nonce'); ?>
                    <?php echo wp_kses_post($settings_message); ?>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="admin_emails"><?php esc_html_e('Admin Emails (comma-separated)', 'orderstock'); ?></label></th>
                            <td>
                                <input type="text" id="admin_emails" name="admin_emails" value="<?php echo esc_attr($admin_emails); ?>" class="regular-text" />
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="company_name"><?php esc_html_e('Company Name', 'orderstock'); ?></label></th>
                            <td>
                                <input type="text" id="company_name" name="company_name" value="<?php echo esc_attr($company_name); ?>" class="regular-text" />
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="company_address"><?php esc_html_e('Delivery Address', 'orderstock'); ?></label></th>
                            <td>
                                <textarea id="company_address" name="company_address" rows="4" cols="50"><?php echo esc_textarea($company_address); ?></textarea>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="company_phone"><?php esc_html_e('Company Phone', 'orderstock'); ?></label></th>
                            <td>
                                <input type="text" id="company_phone" name="company_phone" value="<?php echo esc_attr($company_phone); ?>" class="regular-text" />
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="company_email"><?php esc_html_e('Company Email', 'orderstock'); ?></label></th>
                            <td>
                                <input type="email" id="company_email" name="company_email" value="<?php echo esc_attr($company_email); ?>" class="regular-text" />
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="company_siret"><?php esc_html_e('Company SIRET (optional)', 'orderstock'); ?></label></th>
                            <td>
                                <input type="text" id="company_siret" name="company_siret" value="<?php echo esc_attr($company_siret); ?>" class="regular-text" />
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="tax_rate_1"><?php esc_html_e('Tax Rate 1 (%)', 'orderstock'); ?></label></th>
                            <td>
                                <input type="text" id="tax_rate_1" name="tax_rate_1" value="<?php echo esc_attr($tax_rate_1); ?>" class="regular-text" />
                                <p class="description"><?php esc_html_e('e.g., 5.5', 'orderstock'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="tax_rate_2"><?php esc_html_e('Tax Rate 2 (%)', 'orderstock'); ?></label></th>
                            <td>
                                <input type="text" id="tax_rate_2" name="tax_rate_2" value="<?php echo esc_attr($tax_rate_2); ?>" class="regular-text" />
                                <p class="description"><?php esc_html_e('e.g., 10.0', 'orderstock'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="tax_rate_3"><?php esc_html_e('Tax Rate 3 (%)', 'orderstock'); ?></label></th>
                            <td>
                                <input type="text" id="tax_rate_3" name="tax_rate_3" value="<?php echo esc_attr($tax_rate_3); ?>" class="regular-text" />
                                <p class="description"><?php esc_html_e('e.g., 20.0', 'orderstock'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="order_mode"><?php esc_html_e('Order Calculation Mode', 'orderstock'); ?></label></th>
                            <td>
                                <select id="order_mode" name="order_mode">
                                    <option value="forecast" <?php selected(get_option('orderstock_order_mode', 'forecast'), 'forecast'); ?>><?php esc_html_e('Forecast Mode (Daily Sales × Replenishment Period)', 'orderstock'); ?></option>
                                    <option value="threshold" <?php selected(get_option('orderstock_order_mode', 'forecast'), 'threshold'); ?>><?php esc_html_e('Threshold Mode (Critical Threshold & Target Stock)', 'orderstock'); ?></option>
                                </select>
                                <p class="description"><?php esc_html_e('Choose how order quantities are calculated.', 'orderstock'); ?></p>
                            </td>
                        </tr>
                        <?php if (!defined('TULIPWORK_SAAS_MODE') || !TULIPWORK_SAAS_MODE || is_super_admin()) : ?>
                            <tr>
                                <th scope="row"><label for="delete_data_on_uninstall"><?php esc_html_e('Delete Data on Uninstall', 'orderstock'); ?></label></th>
                                <td>
                                    <input type="checkbox" id="delete_data_on_uninstall" name="delete_data_on_uninstall" value="1" <?php checked(get_option('tulipwork_orderstock_delete_data_on_uninstall', 0)); ?> />
                                    <p class="description">
                                        <?php
                                        printf(
                                            esc_html__('CAUTION: Enabling this option will %s when you uninstall the plugin from Plugins > Installed Plugins. This includes all products, suppliers, orders, and settings. If OrderStock Pro is installed, its data (stores, stock table, user roles) will also be erased. Once deleted, this data cannot be recovered—proceed with care!', 'orderstock'),
                                            '<span style="color: #d63638; font-weight: bold;">' . esc_html__('permanently delete ALL data', 'orderstock') . '</span>'
                                        );
                                        ?>
                                    </p>
                                </td>
                            </tr>
                        <?php endif; ?>
                            <tr>
                                <th scope="row"><label for="delete_all_data"><?php esc_html_e('Delete All Data Immediately', 'orderstock'); ?></label></th>
                                <td>
                                    <button type="submit" name="tulipwork_orderstock_delete_all" class="button button-secondary" onclick="return confirm('<?php esc_attr_e('Are you sure? This will permanently delete ALL OrderStock data (products, suppliers, orders, settings, and Pro data if applicable). This action cannot be undone!', 'orderstock'); ?>');"><?php esc_html_e('Delete All Data Now', 'orderstock'); ?></button>
                                    <?php wp_nonce_field('tulipwork_orderstock_delete_all_nonce', 'delete_nonce'); ?>
                                    <p class="description">
                                        <?php
                                        printf(
                                            esc_html__('CAUTION: Clicking this button will %s immediately, including all products, suppliers, orders, settings, and Pro data (stores, stock records, roles) if OrderStock Pro is installed. The database structure will be preserved for continued use. This action cannot be undone!', 'orderstock'),
                                            '<span style="color: #d63638; font-weight: bold;">' . esc_html__('permanently delete ALL data', 'orderstock') . '</span>'
                                        );
                                        ?>
                                    </p>
                                </td>
                            </tr>
                    </table>
                    <p class="submit">
                        <input type="submit" name="tulipwork_orderstock_settings_save" class="button-primary" value="<?php esc_attr_e('Save General Settings', 'orderstock'); ?>" />
                    </p>
                </form>
            <?php elseif ($active_tab === 'license' && $pro_active && !$is_saas) : ?>
                <form method="post" action="">
                    <?php wp_nonce_field('tulipwork_orderstock_settings_nonce', 'nonce'); ?>
                    <?php do_action('tulipwork_orderstock_premium_settings'); ?>
                </form>
            <?php elseif ($active_tab === 'pro') : ?>
                <div class="orderstock-pro-promo">
                    <h2><?php esc_html_e('Boost Your Inventory Management with OrderStock Pro!', 'orderstock'); ?></h2>
                    <?php if ($is_premium) : ?>
                        <?php echo wp_kses_post($settings_message); ?>
                        <form method="post" action="">
                            <?php wp_nonce_field('tulipwork_orderstock_settings_nonce', 'nonce'); ?>
                            <input type="hidden" name="tulipwork_orderstock_pro_save" value="1">
                            <?php do_action('tulipwork_orderstock_premium_options'); ?>
                            <p class="submit">
                                <input type="submit" name="submit" class="button-primary" value="<?php esc_attr_e('Save Pro Settings', 'orderstock'); ?>" />
                            </p>
                        </form>
                    <?php else : ?>
                        <p style="font-size: 16px;"><?php esc_html_e('Ready to supercharge your stock management? Upgrade to OrderStock Pro and unlock a suite of powerful tools built for efficiency, flexibility, and growth!', 'orderstock'); ?></p>
                        <ul style="list-style: none; padding-left: 0;">
                            <li><span style="color: #46b450; font-size: 18px;">✔</span> <?php esc_html_e('Import and export product data easily with CSV files for fast bulk updates.', 'orderstock'); ?></li>
                            <li><span style="color: #46b450; font-size: 18px;">✔</span> <?php esc_html_e('Track order history, update receptions, and monitor costs effortlessly.', 'orderstock'); ?></li>
                            <li><span style="color: #46b450; font-size: 18px;">✔</span> <?php esc_html_e('Save time with bulk editing for suppliers, tax rates, and more.', 'orderstock'); ?></li>
                            <li><span style="color: #46b450; font-size: 18px;">✔</span> <?php esc_html_e('Assign multiple suppliers per product for smarter sourcing options.', 'orderstock'); ?></li>
                            <li><span style="color: #46b450; font-size: 18px;">✔</span> <?php esc_html_e('Manage multiple stores with centralized inventory tracking from one dashboard.', 'orderstock'); ?></li>
                            <li><span style="color: #46b450; font-size: 18px;">✔</span> <?php esc_html_e('Streamline production with a Central Kitchen or warehouse system.', 'orderstock'); ?></li>
                            <li><span style="color: #46b450; font-size: 18px;">✔</span> <?php esc_html_e('Consolidate orders into a single prep list for maximum efficiency.', 'orderstock'); ?></li>
                            <li><span style="color: #46b450; font-size: 18px;">✔</span> <?php esc_html_e('Delegate tasks securely with custom user roles like stock editors or order managers.', 'orderstock'); ?></li>
                            <li><span style="color: #46b450; font-size: 18px;">✔</span> <?php esc_html_e('Gain deeper insights with advanced reports, snapshots, and real-time cost tracking.', 'orderstock'); ?></li>
                        </ul>
                        <p style="font-weight: bold;"><?php esc_html_e('Why upgrade? OrderStock Pro transforms your inventory management into a seamless, scalable solution!', 'orderstock'); ?></p>
                        <p>
                            <a href="https://tulipemedia.com/en/product/orderstock-pro/" target="_blank" class="button button-primary" style="font-size: 16px; padding: 10px 20px;">
                                <?php esc_html_e('Get OrderStock Pro Now!', 'orderstock'); ?>
                            </a>
                        </p>
                        <p><?php esc_html_e('Already have OrderStock Pro?', 'orderstock'); ?></p>
                        <ol>
                            <li><?php esc_html_e('Keep the free version installed and active.', 'orderstock'); ?></li>
                            <li><?php esc_html_e('Install and activate the OrderStock Pro plugin.', 'orderstock'); ?></li>
                            <li><?php esc_html_e('Enter your license key in the new "License" tab that will appear here.', 'orderstock'); ?></li>
                        </ol>
                    <?php endif; ?>
                </div>
            <?php elseif ($active_tab === 'support' && !$is_saas) : ?>
                <div class="orderstock-support-promo">
                    <h2><?php esc_html_e('Support OrderStock’s Future! 🌟', 'orderstock'); ?></h2>
                    <p style="font-size: 16px;"><?php esc_html_e('OrderStock is a tool built with passion to help merchants and organizations like you manage inventory effortlessly. Your support can make a huge difference in keeping it growing and improving!', 'orderstock'); ?></p>
                    
                    <div style="display: flex; flex-wrap: wrap; gap: 20px; margin-top: 20px;">
                        <!-- Donation -->
                        <div style="flex: 1; min-width: 300px; background: #f9f9f9; padding: 20px; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
                            <h3>☕ <?php esc_html_e('Buy Me a Coffee', 'orderstock'); ?></h3>
                            <p><?php esc_html_e('Love using OrderStock? A small donation can fuel my coffee cup and help me dedicate more time to enhancing this plugin for you!', 'orderstock'); ?></p>
                            <p>
                                <a href="https://paypal.me/ziyadbachalany" target="_blank" class="button button-primary" style="font-size: 16px; padding: 10px 20px; background: #007cba; border-color: #007cba;">
                                    <?php esc_html_e('Donate Now', 'orderstock'); ?> 💖
                                </a>
                            </p>
                        </div>

                        <!-- Traduction -->
                        <div style="flex: 1; min-width: 300px; background: #f9f9f9; padding: 20px; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
                            <h3>🌍 <?php esc_html_e('Help Translate', 'orderstock'); ?></h3>
                            <p><?php esc_html_e('Speak another language? Help make OrderStock accessible to more people around the world by contributing to its translations!', 'orderstock'); ?></p>
                            <p>
                                <a href="https://translate.wordpress.org/projects/wp-plugins/orderstock/" target="_blank" class="button button-primary" style="font-size: 16px; padding: 10px 20px; background: #46b450; border-color: #46b450;">
                                    <?php esc_html_e('Translate Now', 'orderstock'); ?> ✨
                                </a>
                            </p>
                        </div>

                        <!-- Revue -->
                        <div style="flex: 1; min-width: 300px; background: #f9f9f9; padding: 20px; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
                            <h3>⭐ <?php esc_html_e('Rate on WordPress', 'orderstock'); ?></h3>
                            <p><?php esc_html_e('Enjoying OrderStock? Share your feedback by rating it on WordPress—it helps others discover it and motivates me to keep improving!', 'orderstock'); ?></p>
                            <p>
                                <a href="https://wordpress.org/support/plugin/orderstock/reviews/#new-post" target="_blank" class="button button-primary" style="font-size: 16px; padding: 10px 20px; background: #f7c948; border-color: #f7c948; color: #000;">
                                    <?php esc_html_e('Rate Now', 'orderstock'); ?> 🌟
                                </a>
                            </p>
                        </div>

                        <!-- Support -->
                        <div style="flex: 1; min-width: 300px; background: #f9f9f9; padding: 20px; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
                            <h3>❓ <?php esc_html_e('Need Help?', 'orderstock'); ?></h3>
                            <p><?php esc_html_e('Have questions or need assistance? Visit our support page for resources and contact options.', 'orderstock'); ?></p>
                            <p>
                                <a href="https://tulipemedia.com/en/orderstock-wp-plugin/" target="_blank" class="button button-primary" style="font-size: 16px; padding: 10px 20px; background: #787878; border-color: #787878;">
                                    <?php esc_html_e('Get Support', 'orderstock'); ?> 🛠️
                                </a>
                            </p>
                        </div>
                    </div>

                    <!-- Réseaux sociaux -->
                    <div style="margin-top: 30px; text-align: center; background: #f9f9f9; padding: 20px; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
                        <h3>📱 <?php esc_html_e('Follow Me on Social Media!', 'orderstock'); ?></h3>
                        <p><?php esc_html_e('Stay updated on OrderStock news, tips, and more by following me on your favorite platforms!', 'orderstock'); ?></p>
                        <div style="display: flex; justify-content: center; flex-wrap: wrap; gap: 15px; margin-top: 15px;">
                            <a href="https://www.linkedin.com/in/ziyadbachalany/" target="_blank" style="text-decoration: none;">
                                <img src="<?php echo plugins_url('orderstock/includes/images/linkedin-icon.png'); ?>" alt="LinkedIn" style="width: 32px; height: 32px; vertical-align: middle;"> LinkedIn
                            </a>
                            <a href="https://x.com/ziyadbachalany" target="_blank" style="text-decoration: none;">
                                <img src="<?php echo plugins_url('orderstock/includes/images/x-icon.png'); ?>" alt="X" style="width: 32px; height: 32px; vertical-align: middle;"> X
                            </a>
                            <a href="https://www.instagram.com/ziyadbachalany/" target="_blank" style="text-decoration: none;">
                                <img src="<?php echo plugins_url('orderstock/includes/images/instagram-icon.png'); ?>" alt="Instagram" style="width: 32px; height: 32px; vertical-align: middle;"> Instagram
                            </a>
                            <a href="https://www.facebook.com/ziyadbachalany" target="_blank" style="text-decoration: none;">
                                <img src="<?php echo plugins_url('orderstock/includes/images/facebook-icon.png'); ?>" alt="Facebook" style="width: 32px; height: 32px; vertical-align: middle;"> Facebook
                            </a>
                            <a href="https://www.youtube.com/channel/UClMfre0hj-UCxGocDleZxTQ" target="_blank" style="text-decoration: none;">
                                <img src="<?php echo plugins_url('orderstock/includes/images/youtube-icon.png'); ?>" alt="YouTube" style="width: 32px; height: 32px; vertical-align: middle;"> YouTube
                            </a>
                            <a href="https://www.tiktok.com/@ziyadbachalany" target="_blank" style="text-decoration: none;">
                                <img src="<?php echo plugins_url('orderstock/includes/images/tiktok-icon.png'); ?>" alt="TikTok" style="width: 32px; height: 32px; vertical-align: middle;"> TikTok
                            </a>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div> <!-- Fin de .settings-content -->
    </div>
    <?php
}

// Métaboxes inchangées (supplier et product details)
function tulipwork_supplier_details_callback($post) {
    wp_nonce_field('tulipwork_supplier_save', 'tulipwork_supplier_nonce');
    $fields = [
        'address' => get_post_meta($post->ID, '_address', true),
        'phone' => get_post_meta($post->ID, '_phone', true),
        'email' => get_post_meta($post->ID, '_email', true),
        'min_order_threshold' => get_post_meta($post->ID, '_min_order_threshold', true),
    ];
    ?>
    <div class="tulipwork_orderstock-metabox">
        <table>
            <tr>
                <th><label for="address"><?php esc_html_e('Address', 'orderstock'); ?></label></th>
                <td><input type="text" id="address" name="address" value="<?php echo esc_attr($fields['address']); ?>" /></td>
            </tr>
            <tr>
                <th><label for="phone"><?php esc_html_e('Phone', 'orderstock'); ?></label></th>
                <td><input type="text" id="phone" name="phone" value="<?php echo esc_attr($fields['phone']); ?>" /></td>
            </tr>
            <tr>
                <th><label for="email"><?php esc_html_e('Emails (comma-separated)', 'orderstock'); ?></label></th>
                <td><input type="text" id="email" name="email" value="<?php echo esc_attr($fields['email']); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="min_order_threshold"><?php esc_html_e('Minimum Order Threshold', 'orderstock'); ?></label></th>
                <td><input type="number" id="min_order_threshold" name="min_order_threshold" value="<?php echo esc_attr($fields['min_order_threshold']); ?>" step="0.01" /></td>
            </tr>
        </table>
    </div>
    <?php
}

add_action('save_post_tulipwork_supplier', 'tulipwork_orderstock_save_supplier_details');
function tulipwork_orderstock_save_supplier_details($post_id) {
    if (!isset($_POST['tulipwork_supplier_nonce']) || 
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tulipwork_supplier_nonce'])), 'tulipwork_supplier_save')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('tulipwork_orderstock_access', $post_id)) return;
    $post = get_post($post_id);
    if ($post && !empty($post->post_title)) {
        update_post_meta($post_id, '_title_lowercase', strtolower($post->post_title));
    }
    $fields = ['address', 'phone', 'email', 'min_order_threshold'];
    foreach ($fields as $field) {
        if (isset($_POST[$field])) {
            if ($field === 'email') {
                // Nettoyer et valider les e-mails séparés par des virgules
                $emails = array_map('trim', explode(',', sanitize_text_field(wp_unslash($_POST[$field]))));
                $valid_emails = [];
                foreach ($emails as $email) {
                    if (is_email($email)) {
                        $valid_emails[] = $email;
                    }
                }
                // Stocker les e-mails valides sous forme de chaîne séparée par des virgules
                $value = implode(',', $valid_emails);
            } else {
                $value = $field === 'min_order_threshold' ? floatval(wp_unslash($_POST[$field])) : 
                        sanitize_text_field(wp_unslash($_POST[$field]));
                if ($field === 'min_order_threshold' && $value < 0) {
                    $value = 0;
                }
            }
            update_post_meta($post_id, '_' . $field, $value);
        }
    }
}

function tulipwork_product_details_callback($post) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'tulipwork_stocks';

    wp_nonce_field('tulipwork_product_save', 'tulipwork_product_nonce');
    $fields = [
        'stock' => get_post_meta($post->ID, '_stock', true),
        'replenishment_period' => get_post_meta($post->ID, '_replenishment_period', true),
        'daily_sales' => get_post_meta($post->ID, '_daily_sales', true),
        'packaging_unit' => get_post_meta($post->ID, '_packaging_unit', true),
        'packaging_quantity' => get_post_meta($post->ID, '_packaging_quantity', true) !== '' ? get_post_meta($post->ID, '_packaging_quantity', true) : '0',
        'max_quantity' => get_post_meta($post->ID, '_max_quantity', true),
        'decimal_precision' => get_post_meta($post->ID, '_decimal_precision', true) ?: 0,
        'tax_rate' => get_post_meta($post->ID, '_tax_rate', true),
        'critical_threshold' => get_post_meta($post->ID, '_critical_threshold', true),
        'target_stock' => get_post_meta($post->ID, '_target_stock', true),
        'product_order_mode' => get_post_meta($post->ID, '_product_order_mode', true) ?: 'default',
    ];

    $multi_store_enabled = tulipwork_orderstock_is_premium() && get_option('orderstock_pro_central_kitchen_enabled', 0);
    $assigned_stores = get_post_meta($post->ID, '_assigned_stores', true);
    $product_order_mode = $fields['product_order_mode'];

    // Déterminer le mode effectif pour l’affichage des champs dans "Product Details"
    $effective_mode = $product_order_mode !== 'default' ? $product_order_mode : null;
    if (!$effective_mode) {
        $modes = [];
        if ($multi_store_enabled && is_array($assigned_stores) && !empty($assigned_stores)) {
            foreach ($assigned_stores as $store_id) {
                $store_mode = get_post_meta($store_id, '_store_order_mode', true);
                if ($store_mode && in_array($store_mode, ['forecast', 'threshold'])) {
                    $modes[$store_mode] = true;
                } else {
                    $modes[get_option('orderstock_order_mode', 'forecast')] = true;
                }
            }
            $effective_mode = array_key_first($modes); // Prendre le premier mode trouvé
        } else {
            $effective_mode = get_option('orderstock_order_mode', 'forecast');
        }
    }

    $suppliers = get_posts(['post_type' => 'tulipwork_supplier', 'posts_per_page' => -1]);
    $tax_rate_1 = get_option('tulipwork_orderstock_tax_rate_1', 5.5);
    $tax_rate_2 = get_option('tulipwork_orderstock_tax_rate_2', 10.0);
    $tax_rate_3 = get_option('tulipwork_orderstock_tax_rate_3', 20.0);
    $tax_options = [
        '0' => esc_html__('No Tax', 'orderstock'),
        (string)$tax_rate_1 => sprintf(esc_html__('%s%% VAT', 'orderstock'), number_format($tax_rate_1, 1, '.', '')),
        (string)$tax_rate_2 => sprintf(esc_html__('%s%% VAT', 'orderstock'), number_format($tax_rate_2, 1, '.', '')),
        (string)$tax_rate_3 => sprintf(esc_html__('%s%% VAT', 'orderstock'), number_format($tax_rate_3, 1, '.', '')),
    ];
    $decimal_precision = intval($fields['decimal_precision']);
    $display_stock = number_format(floatval($fields['stock']), $decimal_precision, '.', '');
    $display_daily_sales = number_format(floatval($fields['daily_sales']), $decimal_precision, '.', '');
    $display_packaging_quantity = number_format(floatval($fields['packaging_quantity']), $fields['decimal_precision'], '.', '');
    $display_max_quantity = number_format(floatval($fields['max_quantity']), $decimal_precision, '.', '');
    $display_critical_threshold = number_format(floatval($fields['critical_threshold']), $decimal_precision, '.', '');
    $display_target_stock = number_format(floatval($fields['target_stock']), $decimal_precision, '.', '');
    $packaging_units = [
        'unit' => esc_html__('Unit', 'orderstock'),
        'pack' => esc_html__('Pack', 'orderstock'),
        'box' => esc_html__('Box', 'orderstock'),
        'kg' => esc_html__('kg', 'orderstock'),
        'L' => esc_html__('L', 'orderstock')
    ];

    ?>
    <div class="tulipwork_orderstock-metabox">
        <table>
            <?php 
            // Garde-fous pour les valeurs globales
            if ($effective_mode === 'threshold' && !$multi_store_enabled) : // Limité au monostore
                if ($fields['critical_threshold'] > $fields['target_stock']) : ?>
                    <tr>
                        <td colspan="2">
                            <p style="color: #d63638;"><?php esc_html_e('Warning: Critical Threshold is greater than Target Stock. No order will be suggested.', 'orderstock'); ?></p>
                        </td>
                    </tr>
                <?php endif; ?>
                <?php if ($fields['max_quantity'] && $fields['max_quantity'] < $fields['target_stock']) : ?>
                    <tr>
                        <td colspan="2">
                            <p style="color: #d63638;"><?php esc_html_e('Warning: Maximum Quantity is less than Target Stock. The target will not be reached.', 'orderstock'); ?></p>
                        </td>
                    </tr>
                <?php endif; ?>
                <?php if ($fields['critical_threshold'] > $fields['max_quantity'] && $fields['max_quantity'] > 0) : ?>
                    <tr>
                        <td colspan="2">
                            <p style="color: #d63638;"><?php esc_html_e('Warning: Critical Threshold exceeds Maximum Quantity. This may limit reordering.', 'orderstock'); ?></p>
                        </td>
                    </tr>
                <?php endif; ?>
            <?php endif; ?>
            <?php if ($effective_mode === 'forecast' && !$multi_store_enabled && ($fields['replenishment_period'] == 0 || $fields['daily_sales'] == 0)) : // Limité au monostore
                ?>
                <tr>
                    <td colspan="2">
                        <p style="color: #d63638;"><?php esc_html_e('Warning: Replenishment Period or Daily Average Sales is 0. No order will be suggested in Forecast mode.', 'orderstock'); ?></p>
                    </td>
                </tr>
            <?php endif; ?>
            <?php if ($multi_store_enabled && $effective_mode === 'threshold') : // Garde-fous en multistore avec clarification
                if ($fields['critical_threshold'] > $fields['target_stock']) : ?>
                    <tr>
                        <td colspan="2">
                            <p style="color: #d63638;"><?php esc_html_e('Warning: Default Critical Threshold is greater than Default Target Stock. This applies only if not overridden by store-specific settings.', 'orderstock'); ?></p>
                        </td>
                    </tr>
                <?php endif; ?>
                <?php if ($fields['max_quantity'] && $fields['max_quantity'] < $fields['target_stock']) : ?>
                    <tr>
                        <td colspan="2">
                            <p style="color: #d63638;"><?php esc_html_e('Warning: Default Maximum Quantity is less than Default Target Stock. This applies only if not overridden by store-specific settings.', 'orderstock'); ?></p>
                        </td>
                    </tr>
                <?php endif; ?>
                <?php if ($fields['critical_threshold'] > $fields['max_quantity'] && $fields['max_quantity'] > 0) : ?>
                    <tr>
                        <td colspan="2">
                            <p style="color: #d63638;"><?php esc_html_e('Warning: Default Critical Threshold exceeds Default Maximum Quantity. This applies only if not overridden by store-specific settings.', 'orderstock'); ?></p>
                        </td>
                    </tr>
                <?php endif; ?>
            <?php endif; ?>
            <?php if ($multi_store_enabled && $effective_mode === 'forecast' && $fields['replenishment_period'] == 0) : // Garde-fou spécifique pour multistore
                ?>
                <tr>
                    <td colspan="2">
                        <p style="color: #d63638;"><?php esc_html_e('Warning: Default Replenishment Period is 0. This applies only if not overridden by store-specific settings.', 'orderstock'); ?></p>
                    </td>
                </tr>
            <?php endif; ?>
            <?php if ($effective_mode === 'forecast') : ?>
                <tr>
                    <th><label for="replenishment_period"><?php esc_html_e('Replenishment Period (days)', 'orderstock'); ?></label></th>
                    <td><input type="number" id="replenishment_period" name="replenishment_period" value="<?php echo esc_attr($fields['replenishment_period']); ?>" step="0.01" min="0" /></td>
                    <!-- Ne pas remettre step="1" : les valeurs décimales (ex. 2.5, 2.75) sont nécessaires pour permettre une marge de sécurité dans la période de réapprovisionnement -->
                </tr>
                <?php if (!$multi_store_enabled) : ?>
                    <tr>
                        <th><label for="daily_sales"><?php esc_html_e('Daily Average Sales', 'orderstock'); ?></label></th>
                        <td><input type="number" id="daily_sales" name="daily_sales" value="<?php echo esc_attr($display_daily_sales); ?>" step="any" /></td>
                    </tr>
                <?php endif; ?>
            <?php endif; ?>
            <?php if ($effective_mode === 'threshold') : ?>
                <tr>
                    <th><label for="critical_threshold"><?php esc_html_e('Critical Threshold', 'orderstock'); ?></label></th>
                    <td><input type="number" id="critical_threshold" name="critical_threshold" value="<?php echo esc_attr($display_critical_threshold); ?>" step="any" /></td>
                </tr>
                <tr>
                    <th><label for="target_stock"><?php esc_html_e('Target Stock', 'orderstock'); ?></label></th>
                    <td><input type="number" id="target_stock" name="target_stock" value="<?php echo esc_attr($display_target_stock); ?>" step="any" /></td>
                </tr>
            <?php endif; ?>
            <?php if (!$multi_store_enabled) : ?>
                <tr>
                    <th><label for="stock"><?php esc_html_e('Stock', 'orderstock'); ?></label></th>
                    <td>
                        <input type="number" id="stock" name="stock" value="<?php echo esc_attr($display_stock); ?>" step="any" />
                    </td>
                </tr>
            <?php endif; ?>
            <tr>
                <th><label><?php esc_html_e('Packaging', 'orderstock'); ?></label></th>
                <td class="packaging-field">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <input type="number" id="packaging_quantity" name="packaging_quantity" value="<?php echo esc_attr($display_packaging_quantity); ?>" step="any" min="0" />
                        <select name="packaging_unit">
                            <?php foreach ($packaging_units as $value => $label) : ?>
                                <option value="<?php echo esc_attr($value); ?>" <?php selected($fields['packaging_unit'], $value); ?>><?php echo esc_html($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <p class="description" style="display: block; margin-top: 10px;"><?php esc_html_e('Set to 0 to allow free ordering without packaging constraints (e.g., any quantity in kg or units).', 'orderstock'); ?></p>
                    </div>
                </td>
            </tr>
            <tr>
                <th><label for="max_quantity"><?php esc_html_e('Maximum Quantity', 'orderstock'); ?></label></th>
                <td>
                    <input type="number" id="max_quantity" name="max_quantity" value="<?php echo esc_attr($display_max_quantity); ?>" step="any" />
                </td>
            </tr>
            <tr>
                <th><label for="decimal_precision"><?php esc_html_e('Decimal Precision', 'orderstock'); ?></label></th>
                <td>
                    <select id="decimal_precision" name="decimal_precision">
                        <option value="0" <?php selected($fields['decimal_precision'], '0'); ?>><?php esc_html_e('0 (whole numbers)', 'orderstock'); ?></option>
                        <option value="1" <?php selected($fields['decimal_precision'], '1'); ?>><?php esc_html_e('1 decimal (e.g., 3.5)', 'orderstock'); ?></option>
                        <option value="2" <?php selected($fields['decimal_precision'], '2'); ?>><?php esc_html_e('2 decimals (e.g., 3.75)', 'orderstock'); ?></option>
                        <option value="3" <?php selected($fields['decimal_precision'], '3'); ?>><?php esc_html_e('3 decimals (e.g., 3.875)', 'orderstock'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="tax_rate"><?php esc_html_e('Tax Rate', 'orderstock'); ?></label></th>
                <td>
                    <select id="tax_rate" name="tax_rate">
                        <?php foreach ($tax_options as $value => $label) : ?>
                            <option value="<?php echo esc_attr($value); ?>" <?php selected((string)$fields['tax_rate'], (string)$value); ?>><?php echo esc_html($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="product_order_mode"><?php esc_html_e('Order Calculation Mode', 'orderstock'); ?></label></th>
                <td>
                    <select id="product_order_mode" name="product_order_mode">
                        <option value="default" <?php selected($product_order_mode, 'default'); ?>><?php esc_html_e('Use Higher-Level Setting', 'orderstock'); ?></option>
                        <option value="forecast" <?php selected($product_order_mode, 'forecast'); ?>><?php esc_html_e('Forecast Mode (Daily Sales × Replenishment Period)', 'orderstock'); ?></option>
                        <option value="threshold" <?php selected($product_order_mode, 'threshold'); ?>><?php esc_html_e('Threshold Mode (Critical Threshold & Target Stock)', 'orderstock'); ?></option>
                    </select>
                    <p class="description"><?php esc_html_e('Overrides store or global mode for this product. Select "Use Higher-Level Setting" to follow the store or global mode.', 'orderstock'); ?></p>
                </td>
            </tr>
        </table>
        <?php if ($multi_store_enabled) : ?>
            <p class="description"><?php esc_html_e('These are default values. Per-store settings in "Settings per Store" below will override these if specified.', 'orderstock-pro'); ?></p>
        <?php endif; ?>
    </div>
    <?php
}

add_action('save_post_tulipwork_product', 'tulipwork_orderstock_save_product_details', 100);
function tulipwork_orderstock_save_product_details($post_id) {
    if (!isset($_POST['tulipwork_product_nonce']) || 
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tulipwork_product_nonce'])), 'tulipwork_product_save')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('tulipwork_orderstock_access', $post_id)) return;
    $post = get_post($post_id);
    if ($post && !empty($post->post_title)) {
        update_post_meta($post_id, '_title_lowercase', strtolower($post->post_title));
    }
    $multi_store_enabled = tulipwork_orderstock_is_premium() && get_option('orderstock_pro_central_kitchen_enabled', 0);
    $is_premium = tulipwork_orderstock_is_premium();
    $order_mode = get_option('orderstock_order_mode', 'forecast');
    $fields = [
        'stock' => 'floatval',
        'replenishment_period' => 'floatval',
        'daily_sales' => 'floatval',
        'packaging_unit' => 'sanitize_text_field',
        'packaging_quantity' => 'floatval',
        'max_quantity' => 'floatval',
        'decimal_precision' => 'intval',
        'tax_rate' => 'floatval',
        'critical_threshold' => 'floatval',
        'target_stock' => 'floatval',
        'product_order_mode' => 'sanitize_text_field',
    ];

    foreach ($fields as $field => $sanitize_func) {
        $value = isset($_POST[$field]) ? wp_unslash($_POST[$field]) : ($field === 'packaging_unit' ? 'unit' : 0);
        $value = sanitize_text_field($value);
        if (in_array($field, ['stock', 'replenishment_period', 'daily_sales', 'packaging_quantity', 'max_quantity', 'tax_rate', 'critical_threshold', 'target_stock'])) {
            $value = str_replace(',', '.', $value);
        }
        $sanitized_value = $sanitize_func($value);
        if (in_array($field, ['stock', 'daily_sales', 'packaging_quantity', 'max_quantity', 'critical_threshold', 'target_stock']) && $sanitized_value < 0) {
            $sanitized_value = 0;
        }
        if ($field === 'replenishment_period' && $sanitized_value < 0) {
            $sanitized_value = 0;
        }
        if ($field === 'decimal_precision' && ($sanitized_value < 0 || $sanitized_value > 3)) {
            $sanitized_value = 0;
        }
        if ($field === 'product_order_mode' && !in_array($sanitized_value, ['default', 'forecast', 'threshold'])) {
            $sanitized_value = 'default';
        }
        if ($multi_store_enabled && in_array($field, ['stock', 'daily_sales'])) {
            continue;
        }
        update_post_meta($post_id, '_' . $field, $sanitized_value);
    }

    $main_supplier = get_post_meta($post_id, '_supplier', true);
    $assigned_suppliers = get_post_meta($post_id, '_suppliers', true) ?: [];
    if (!is_array($assigned_suppliers)) $assigned_suppliers = $main_supplier ? [$main_supplier] : [];

    if (isset($_POST['prices_excl_tax']) && is_array($_POST['prices_excl_tax'])) {
        $prices_excl_tax = [];
        foreach ($_POST['prices_excl_tax'] as $supplier_id => $price) {
            $supplier_id = intval($supplier_id);
            $price = floatval(str_replace(',', '.', sanitize_text_field($price)));
            if ($price >= 0 && ($is_premium || $supplier_id == $main_supplier)) {
                $prices_excl_tax[$supplier_id] = $price;
            }
        }
        update_post_meta($post_id, '_prices_excl_tax', $prices_excl_tax);
    }
}

add_action('add_meta_boxes', 'tulipwork_orderstock_add_meta_boxes');
function tulipwork_orderstock_add_meta_boxes() {
    add_meta_box(
        'tulipwork_orderstock_supplier_details',
        __('Supplier Details', 'orderstock'),
        'tulipwork_supplier_details_callback',
        'tulipwork_supplier',
        'normal',
        'high'
    );
    add_meta_box(
        'tulipwork_orderstock_product_details',
        __('Product Details', 'orderstock'),
        'tulipwork_product_details_callback',
        'tulipwork_product',
        'normal',
        'high'
    );
}

add_action('add_meta_boxes', 'tulipwork_add_suppliers_meta_box');
function tulipwork_add_suppliers_meta_box() {
    add_meta_box(
        'tulipwork_suppliers_assignment',
        __('Suppliers', 'orderstock'),
        'tulipwork_suppliers_assignment_callback',
        'tulipwork_product',
        'side',
        'default'
    );
}

function tulipwork_suppliers_assignment_callback($post) {
    wp_nonce_field('tulipwork_suppliers_save', 'tulipwork_suppliers_nonce');
    $suppliers = get_posts(['post_type' => 'tulipwork_supplier', 'posts_per_page' => -1]);
    $assigned_suppliers = get_post_meta($post->ID, '_suppliers', true) ?: [];
    if (!is_array($assigned_suppliers)) $assigned_suppliers = [$assigned_suppliers];
    $main_supplier = get_post_meta($post->ID, '_supplier', true);
    $is_premium = tulipwork_orderstock_is_premium();

    if ($is_premium) {
        ?>
        <p><?php esc_html_e('Main Supplier:', 'orderstock'); ?></p>
        <select name="main_supplier" id="main-supplier">
            <option value=""><?php esc_html_e('Select a main supplier', 'orderstock'); ?></option>
            <?php foreach ($suppliers as $supplier) : ?>
                <option value="<?php echo esc_attr($supplier->ID); ?>" <?php selected($main_supplier, $supplier->ID); ?>><?php echo esc_html($supplier->post_title); ?></option>
            <?php endforeach; ?>
        </select>
        <p class="description"><?php esc_html_e('Select the primary supplier for ordering.', 'orderstock'); ?></p>
        <p><?php esc_html_e('Assign additional suppliers to this product:', 'orderstock'); ?></p>
        <ul style="max-height: 200px; overflow-y: auto;" id="additional-suppliers-list">
            <?php foreach ($suppliers as $supplier) : ?>
                <li>
                    <label>
                        <input type="checkbox" name="suppliers[]" value="<?php echo esc_attr($supplier->ID); ?>" <?php checked(in_array($supplier->ID, $assigned_suppliers)); ?> class="additional-supplier-checkbox" data-supplier="<?php echo esc_attr($supplier->ID); ?>" />
                        <?php echo esc_html($supplier->post_title); ?>
                    </label>
                </li>
            <?php endforeach; ?>
        </ul>
        <script>
            jQuery(document).ready(function($) {
                function updateSupplierCheckboxes() {
                    var mainSupplier = $('#main-supplier').val();
                    $('.additional-supplier-checkbox').each(function() {
                        var checkbox = $(this);
                        var supplierValue = checkbox.data('supplier');
                        if (supplierValue == mainSupplier) {
                            checkbox.prop('disabled', true).prop('checked', false);
                        } else {
                            checkbox.prop('disabled', false);
                        }
                    });
                }
                $('#main-supplier').on('change', updateSupplierCheckboxes);
                updateSupplierCheckboxes();
            });
        </script>
        <?php
    } else {
        ?>
        <p><?php esc_html_e('Main Supplier:', 'orderstock'); ?></p>
        <select name="main_supplier">
            <option value=""><?php esc_html_e('Select a supplier', 'orderstock'); ?></option>
            <?php foreach ($suppliers as $supplier) : ?>
                <option value="<?php echo esc_attr($supplier->ID); ?>" <?php selected($main_supplier, $supplier->ID); ?>><?php echo esc_html($supplier->post_title); ?></option>
            <?php endforeach; ?>
        </select>
        <p class="description"><?php esc_html_e('Upgrade to Pro to assign multiple suppliers.', 'orderstock'); ?></p>
        <?php
    }
}

add_action('save_post_tulipwork_product', 'tulipwork_save_suppliers_assignment');
function tulipwork_save_suppliers_assignment($post_id) {
    if (!isset($_POST['tulipwork_suppliers_nonce']) || !wp_verify_nonce($_POST['tulipwork_suppliers_nonce'], 'tulipwork_suppliers_save')) return;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('tulipwork_orderstock_access')) return;

    $is_premium = tulipwork_orderstock_is_premium();
    $main_supplier = isset($_POST['main_supplier']) ? intval($_POST['main_supplier']) : '';

    if ($is_premium) {
        $suppliers = isset($_POST['suppliers']) ? array_map('intval', $_POST['suppliers']) : [];
        
        if (!empty($main_supplier) && empty($suppliers)) {
            update_post_meta($post_id, '_suppliers', [$main_supplier]);
            update_post_meta($post_id, '_supplier', $main_supplier);
        } elseif (!empty($suppliers)) {
            if (!empty($main_supplier) && !in_array($main_supplier, $suppliers)) {
                $suppliers[] = $main_supplier;
            }
            update_post_meta($post_id, '_suppliers', $suppliers);
            update_post_meta($post_id, '_supplier', $main_supplier ?: $suppliers[0]);
        } elseif (empty($main_supplier) && empty($suppliers)) {
            update_post_meta($post_id, '_suppliers', []);
            delete_post_meta($post_id, '_supplier');
        }
    } else {
        update_post_meta($post_id, '_supplier', $main_supplier);
    }
}

add_action('add_meta_boxes', 'tulipwork_add_prices_per_supplier_meta_box');
function tulipwork_add_prices_per_supplier_meta_box() {
    add_meta_box(
        'tulipwork_prices_per_supplier',
        __('Prices per Supplier', 'orderstock'),
        'tulipwork_prices_per_supplier_callback',
        'tulipwork_product',
        'normal',
        'default'
    );
}

function tulipwork_prices_per_supplier_callback($post) {
    wp_nonce_field('tulipwork_product_save', 'tulipwork_product_nonce');
    $is_premium = tulipwork_orderstock_is_premium();
    $main_supplier = get_post_meta($post->ID, '_supplier', true);
    $assigned_suppliers = get_post_meta($post->ID, '_suppliers', true) ?: [];
    if (!is_array($assigned_suppliers)) $assigned_suppliers = $main_supplier ? [$main_supplier] : [];
    $prices_excl_tax = get_post_meta($post->ID, '_prices_excl_tax', true) ?: [];
    if (!is_array($prices_excl_tax)) $prices_excl_tax = [];
    $suppliers = get_posts(['post_type' => 'tulipwork_supplier', 'posts_per_page' => -1]);

    ?>
    <div class="tulipwork_orderstock-metabox">
        <table>
            <?php 
            $displayed_suppliers = $is_premium ? $assigned_suppliers : ($main_supplier ? [$main_supplier] : []);
            if (empty($displayed_suppliers)) : ?>
                <p><?php esc_html_e('Assign a main supplier first to set prices.', 'orderstock'); ?></p>
            <?php else : ?>
                <?php foreach ($suppliers as $supplier) :
                    if (in_array($supplier->ID, $displayed_suppliers)) : ?>
                        <tr>
                            <th><label for="price_excl_tax_<?php echo esc_attr($supplier->ID); ?>"><?php echo esc_html($supplier->post_title); ?></label></th>
                            <td>
                                <input type="number" id="price_excl_tax_<?php echo esc_attr($supplier->ID); ?>" name="prices_excl_tax[<?php echo esc_attr($supplier->ID); ?>]" value="<?php echo esc_attr($prices_excl_tax[$supplier->ID] ?? ''); ?>" step="0.001" min="0" />
                                <br><small><?php esc_html_e('Price per unit (e.g., per bottle, liter, kg).', 'orderstock'); ?></small>
                            </td>
                        </tr>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php endif; ?>
        </table>
    </div>
    <?php
}

add_action('admin_notices', 'tulipwork_orderstock_supplier_assignment_warning');
function tulipwork_orderstock_supplier_assignment_warning() {
    // Avertissement général existant
    if (isset($_GET['supplier_assignment_warning']) && $_GET['supplier_assignment_warning'] == 1) {
        echo '<div class="notice notice-warning is-dismissible"><p>' . esc_html__('Warning: You selected a Main Supplier but did not assign any suppliers in "Assign suppliers to this product". No changes were made to the suppliers.', 'orderstock') . '</p></div>';
    }

    // Nouveau message d’erreur spécifique
    if (isset($_GET['supplier_assignment_error']) && $_GET['supplier_assignment_error'] == 1 && isset($_GET['main_supplier'])) {
        $main_supplier = urldecode(sanitize_text_field($_GET['main_supplier']));
        echo '<div class="notice notice-error is-dismissible"><p>' . 
             sprintf(esc_html__('Error: The selected Main Supplier "%s" must be checked in "Assign suppliers to this product" first. No changes were made to the suppliers.', 'orderstock'), esc_html($main_supplier)) . 
             '</p></div>';
    }
}

add_action('save_post_tulipwork_supplier', 'tulipwork_orderstock_update_products_on_supplier_change', 10, 3);
function tulipwork_orderstock_update_products_on_supplier_change($post_id, $post, $update) {
    if (!$update || $post->post_type !== 'tulipwork_supplier') {
        return;
    }

    // Pas besoin de mettre à jour les métadonnées, car nous utilisons les IDs.
    // Cette fonction est conservée pour d'éventuelles extensions futures.
}