<?php
/*
Plugin Name: OrderStock by TulipWork
Description: Simple stock and order management for merchants and organizations
Version: 2.1
Author: Tulipe Media
Author URI: https://tulipemedia.com
Text Domain: orderstock
Requires at least: 5.0
Tested up to: 7.0
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/

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

class OrderStock {
    public static function get_version() {
        // Si appelé depuis un sous-fichier, __FILE__ = ce fichier
        // On veut le fichier principal → on le détecte dynamiquement
        $main_file = WP_PLUGIN_DIR . '/orderstock/orderstock.php';
        if (file_exists($main_file)) {
            $plugin_data = get_file_data($main_file, array('Version' => 'Version'));
            return $plugin_data['Version'] ?? '1.0';
        }
        return '1.0'; // fallback
    }
}

// Initialisation
add_action('tulipwork_orderstock_init', 'tulipwork_orderstock_init_hook');
function tulipwork_orderstock_init_hook() {
}

// Charger le domaine de texte pour les traductions
add_action('plugins_loaded', 'orderstock_load_textdomain');
function orderstock_load_textdomain() {
    load_plugin_textdomain('orderstock', false, dirname(plugin_basename(__FILE__)) . '/languages/');
}

// Vérification de la version Premium
function tulipwork_orderstock_is_premium() {
    static $is_premium = null;
    if ($is_premium !== null) {
        return $is_premium;
    }

    // Vérifier d'abord si l'add-on Pro est actif
    if (function_exists('is_plugin_active') && is_plugin_active('orderstock-pro/orderstock-pro.php')) {
        $is_premium = apply_filters('tulipwork_orderstock_is_premium', true);
        return $is_premium;
    }

    // Mode SaaS ou tulipwork.com nécessite l'add-on Pro
    if (defined('TULIPWORK_SAAS_MODE') && TULIPWORK_SAAS_MODE && is_plugin_active('orderstock-pro/orderstock-pro.php')) {
        $is_premium = true;
        return true;
    }
    if (isset($_SERVER['HTTP_HOST']) && strpos($_SERVER['HTTP_HOST'], 'tulipwork.com') !== false && is_plugin_active('orderstock-pro/orderstock-pro.php')) {
        $is_premium = true;
        return true;
    }

    $is_premium = false;
    return apply_filters('tulipwork_orderstock_is_premium', false);
}

// Charger les fichiers inclus
require_once plugin_dir_path(__FILE__) . 'includes/admin-settings.php';
require_once plugin_dir_path(__FILE__) . 'includes/stock-page.php';
require_once plugin_dir_path(__FILE__) . 'includes/order-page.php';
require_once plugin_dir_path(__FILE__) . 'includes/functions.php';

// Charger Dompdf si disponible
if (file_exists(plugin_dir_path(__FILE__) . 'vendor/autoload.php')) {
    require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
} else {
    add_action('admin_notices', function() {
        echo '<div class="error"><p>' . esc_html__('Error: Dompdf library not found. Please install it via Composer in the plugin folder.', 'orderstock') . '</p></div>';
    });
}
use Dompdf\Dompdf;

function tulipwork_orderstock_dashboard_page() {
    ?>
    <div class="wrap">
        <h1><?php esc_html_e('OrderStock Dashboard', 'orderstock'); ?></h1>
        <p><?php esc_html_e('Welcome to OrderStock! Use the menu on the left to manage your stock, place orders, or configure settings.', 'orderstock'); ?></p>
    </div>
    <?php
}

function tulipwork_orderstock_user_can_access_menu() {
    return current_user_can('tulipwork_orderstock_access') || 
           current_user_can('tulipwork_orderstock_access_stock') || 
           current_user_can('tulipwork_orderstock_access_orders') ||
           current_user_can('tulipwork_orderstock_access_inventories') ||
           current_user_can('tulipwork_orderstock_access_history') ||
           current_user_can('tulipwork_orderstock_access_reports') ||
           current_user_can('tulipwork_orderstock_access_products') ||
           current_user_can('tulipwork_orderstock_access_suppliers') ||
           current_user_can('tulipwork_orderstock_access_import_export') ||
           current_user_can('tulipwork_orderstock_access_users') ||
           current_user_can('tulipwork_orderstock_access_settings');
}

function tulipwork_orderstock_menu() {
    if (tulipwork_orderstock_user_can_access_menu()) {
        add_menu_page(
            esc_html__('OrderStock', 'orderstock'),
            'OrderStock',
            'read',
            'tulipwork_orderstock',
            'tulipwork_orderstock_dashboard_page',
            'dashicons-store'
        );

        if (current_user_can('tulipwork_orderstock_access_stock')) {
            add_submenu_page(
                'tulipwork_orderstock',
                esc_html__('Stock', 'orderstock'),
                esc_html__('Stock', 'orderstock'),
                'tulipwork_orderstock_access_stock',
                'tulipwork_orderstock',
                'tulipwork_orderstock_stock_page'
            );
        }

        if (current_user_can('tulipwork_orderstock_access_orders')) {
            add_submenu_page(
                'tulipwork_orderstock',
                esc_html__('Place an Order', 'orderstock'),
                esc_html__('Place an Order', 'orderstock'),
                'tulipwork_orderstock_access_orders',
                'tulipwork_orderstock-order',
                'tulipwork_orderstock_order_page'
            );
        }

        if (current_user_can('tulipwork_orderstock_access_products')) {
            add_submenu_page(
                'tulipwork_orderstock',
                esc_html__('Products', 'orderstock'),
                esc_html__('Products', 'orderstock'),
                'tulipwork_orderstock_access_products',
                'edit.php?post_type=tulipwork_product'
            );
            add_submenu_page(
                'tulipwork_orderstock',
                esc_html__('Categories', 'orderstock'),
                esc_html__('Categories', 'orderstock'),
                'tulipwork_orderstock_access_products',
                'edit-tags.php?taxonomy=tulipwork_prod_cat&post_type=tulipwork_product'
            );
        }

        if (current_user_can('tulipwork_orderstock_access_suppliers')) {
            add_submenu_page(
                'tulipwork_orderstock',
                esc_html__('Suppliers', 'orderstock'),
                esc_html__('Suppliers', 'orderstock'),
                'tulipwork_orderstock_access_suppliers',
                'edit.php?post_type=tulipwork_supplier'
            );
        }

        if (current_user_can('tulipwork_orderstock_access_settings')) {
            add_submenu_page(
                'tulipwork_orderstock',
                esc_html__('Settings', 'orderstock'),
                esc_html__('Settings', 'orderstock'),
                'tulipwork_orderstock_access_settings',
                'tulipwork_orderstock-settings',
                'tulipwork_orderstock_settings_page'
            );
        }
    }

    $user = wp_get_current_user();
}
add_action('admin_menu', 'tulipwork_orderstock_menu');

// Ajout des capacités de base dans la version gratuite
add_action('admin_init', 'tulipwork_orderstock_add_base_capabilities');
function tulipwork_orderstock_add_base_capabilities() {
    $admin_role = get_role('administrator');
    if ($admin_role) {
        $admin_role->add_cap('tulipwork_orderstock_access');
        $admin_role->add_cap('tulipwork_orderstock_access_stock');
        $admin_role->add_cap('tulipwork_orderstock_access_orders');
        $admin_role->add_cap('tulipwork_orderstock_access_products');
        $admin_role->add_cap('tulipwork_orderstock_access_suppliers');
        $admin_role->add_cap('tulipwork_orderstock_access_settings');
    }

    $member_role = get_role('tulipworkmember');
    if ($member_role) {
        $member_role->add_cap('tulipwork_orderstock_access');
    }
}

// Enfiler les assets
add_action('admin_enqueue_scripts', 'tulipwork_orderstock_enqueue_assets');
function tulipwork_orderstock_enqueue_assets($hook) {
    // Mise à jour temps réel des quantités sur la page de commande.
    // En premium, c'est order-pro.js (OrderStock Pro) qui s'en charge.
    if ($hook === 'orderstock_page_tulipwork_orderstock-order' && !tulipwork_orderstock_is_premium()) {
        wp_enqueue_script('tulipwork-orderstock-order', plugin_dir_url(__FILE__) . 'includes/js/order.js', ['jquery'], OrderStock::get_version(), true);
    }
    if (in_array($hook, ['post.php', 'post-new.php'])) {
        if (isset($_GET['post']) || isset($_GET['post_type'])) {
            $nonce_valid = true;
            if (isset($_GET['_wpnonce'])) {
                $nonce_valid = wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'tulipwork_orderstock_enqueue');
            }
            $post_id = isset($_GET['post']) ? intval($_GET['post']) : 0;
            $post_type = $post_id ? get_post_type($post_id) : (isset($_GET['post_type']) ? sanitize_text_field(wp_unslash($_GET['post_type'])) : '');
            if (!$post_type && $hook === 'post-new.php') {
                return;
            }
            if ($post_type === 'tulipwork_product') {
                wp_enqueue_style('tulipwork_orderstock-product-details-css', plugin_dir_url(__FILE__) . 'includes/css/product-details.css', array(), OrderStock::get_version());
            } elseif ($post_type === 'tulipwork_supplier') {
                wp_enqueue_style('tulipwork_orderstock-supplier-details-css', plugin_dir_url(__FILE__) . 'includes/css/supplier-details.css', array(), OrderStock::get_version());
            }
        }
    }
}

// Enregistrer les CPTs
add_action('init', 'tulipwork_orderstock_register_cpts');
function tulipwork_orderstock_register_cpts() {
    register_post_type('tulipwork_product', [
        'labels' => [
            'name' => __('Products', 'orderstock'),
            'singular_name' => __('Product', 'orderstock'),
            'add_new' => __('Add New Product', 'orderstock'),
            'add_new_item' => __('Add New Product', 'orderstock'),
            'edit_item' => __('Edit Product', 'orderstock'),
            'new_item' => __('New Product', 'orderstock'),
            'view_item' => __('View Product', 'orderstock'),
            'search_items' => __('Search Products', 'orderstock'),
            'not_found' => __('No products found', 'orderstock'),
            'not_found_in_trash' => __('No products found in Trash', 'orderstock'),
        ],
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => false,
        'menu_position' => 25,
        'menu_icon' => 'dashicons-products',
        'supports' => ['title'],
        'capabilities' => [
            'edit_post' => 'tulipwork_orderstock_access',
            'edit_posts' => 'tulipwork_orderstock_access',
            'edit_others_posts' => 'tulipwork_orderstock_access',
            'publish_posts' => 'tulipwork_orderstock_access',
            'read_post' => 'tulipwork_orderstock_access',
            'read_private_posts' => 'tulipwork_orderstock_access',
            'delete_post' => 'tulipwork_orderstock_access',
            'delete_posts' => 'tulipwork_orderstock_access',
            'create_posts' => 'tulipwork_orderstock_access',
        ],
    ]);

    register_taxonomy('tulipwork_prod_cat', 'tulipwork_product', [
        'labels' => [
            'name' => __('Product Categories', 'orderstock'),
            'singular_name' => __('Product Category', 'orderstock'),
            'search_items' => __('Search Categories', 'orderstock'),
            'all_items' => __('All Categories', 'orderstock'),
            'parent_item' => __('Parent Category', 'orderstock'),
            'parent_item_colon' => __('Parent Category:', 'orderstock'),
            'edit_item' => __('Edit Category', 'orderstock'),
            'update_item' => __('Update Category', 'orderstock'),
            'add_new_item' => __('Add New Category', 'orderstock'),
            'new_item_name' => __('New Category Name', 'orderstock'),
            'menu_name' => __('Categories', 'orderstock'),
        ],
        'hierarchical' => true,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => ['slug' => 'tulipwork-prod-cat'],
        'capabilities' => [
            'manage_terms' => 'tulipwork_orderstock_access',
            'edit_terms' => 'tulipwork_orderstock_access',
            'delete_terms' => 'tulipwork_orderstock_access',
            'assign_terms' => 'tulipwork_orderstock_access',
        ],
    ]);

    register_post_type('tulipwork_supplier', [
        'labels' => [
            'name' => __('Suppliers', 'orderstock'),
            'singular_name' => __('Supplier', 'orderstock'),
            'add_new' => __('Add New Supplier', 'orderstock'),
            'add_new_item' => __('Add New Supplier', 'orderstock'),
            'edit_item' => __('Edit Supplier', 'orderstock'),
            'new_item' => __('New Supplier', 'orderstock'),
            'view_item' => __('View Supplier', 'orderstock'),
            'search_items' => __('Search Suppliers', 'orderstock'),
            'not_found' => __('No suppliers found', 'orderstock'),
            'not_found_in_trash' => __('No suppliers found in Trash', 'orderstock'),
        ],
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => false,
        'menu_position' => 30,
        'menu_icon' => 'dashicons-businessman',
        'supports' => ['title'],
        'capabilities' => [
            'edit_post' => 'tulipwork_orderstock_access',
            'edit_posts' => 'tulipwork_orderstock_access',
            'edit_others_posts' => 'tulipwork_orderstock_access',
            'publish_posts' => 'tulipwork_orderstock_access',
            'read_post' => 'tulipwork_orderstock_access',
            'read_private_posts' => 'tulipwork_orderstock_access',
            'delete_post' => 'tulipwork_orderstock_access',
            'delete_posts' => 'tulipwork_orderstock_access',
            'create_posts' => 'tulipwork_orderstock_access',
        ],
    ]);

    register_post_type('tulipwork_order', [
        'labels' => [
            'name' => __('Orders', 'orderstock'),
            'singular_name' => __('Order', 'orderstock'),
        ],
        'public' => false,
        'show_ui' => false,
        'supports' => ['title'],
        'capabilities' => [
            'edit_post' => 'tulipwork_orderstock_access',
            'edit_posts' => 'tulipwork_orderstock_access',
            'edit_others_posts' => 'tulipwork_orderstock_access',
            'publish_posts' => 'tulipwork_orderstock_access',
            'read_post' => 'tulipwork_orderstock_access',
            'read_private_posts' => 'tulipwork_orderstock_access',
            'delete_post' => 'tulipwork_orderstock_access',
            'delete_posts' => 'tulipwork_orderstock_access',
            'create_posts' => 'tulipwork_orderstock_access',
        ],
    ]);
}

// Ajout des autres fonctions (duplicate, columns, etc.) inchangées
add_filter('post_row_actions', 'tulipwork_orderstock_add_duplicate_action', 10, 2);
function tulipwork_orderstock_add_duplicate_action($actions, $post) {
    if ($post->post_type === 'tulipwork_product' && current_user_can('edit_posts')) {
        $actions['duplicate'] = '<a href="' . wp_nonce_url(admin_url('edit.php?post_type=tulipwork_product&action=duplicate_product&product_id=' . $post->ID), 'duplicate_product_' . $post->ID) . '">' . esc_html__('Duplicate', 'orderstock') . '</a>';
    }
    return $actions;
}

add_action('admin_init', 'tulipwork_orderstock_handle_duplicate_product');
function tulipwork_orderstock_handle_duplicate_product() {
    if (!isset($_GET['action']) || $_GET['action'] !== 'duplicate_product' || !isset($_GET['product_id'])) return;
    
    $product_id = intval($_GET['product_id']);
    if (!current_user_can('edit_posts') || !check_admin_referer('duplicate_product_' . $product_id)) {
        wp_die(esc_html__('You do not have permission to duplicate this product.', 'orderstock'));
    }

    $original_product = get_post($product_id);
    if (!$original_product || $original_product->post_type !== 'tulipwork_product') {
        wp_die(esc_html__('Invalid product ID.', 'orderstock'));
    }

    $new_product_id = wp_insert_post([
        'post_title' => $original_product->post_title . ' (Copy)',
        'post_type' => 'tulipwork_product',
        'post_status' => 'publish',
        'post_author' => get_current_user_id(),
    ]);

    if ($new_product_id) {
        $meta_keys = [
            '_stock', '_supplier', '_daily_sales', '_replenishment_period', '_critical_threshold', 
            '_target_stock', '_packaging_unit', '_packaging_quantity', '_max_quantity', 
            '_decimal_precision', '_tax_rate', '_suppliers', '_prices_excl_tax', '_assigned_stores'
        ];
        foreach ($meta_keys as $key) {
            $value = get_post_meta($product_id, $key, true);
            if ($value !== '') update_post_meta($new_product_id, $key, $value);
        }

        $terms = wp_get_post_terms($product_id, 'tulipwork_prod_cat', ['fields' => 'ids']);
        if (!is_wp_error($terms)) wp_set_post_terms($new_product_id, $terms, 'tulipwork_prod_cat');

        wp_redirect(admin_url('edit.php?post_type=tulipwork_product&duplicated=1'));
        exit;
    }
}

add_action('admin_notices', 'tulipwork_orderstock_duplicate_notice');
function tulipwork_orderstock_duplicate_notice() {
    if (isset($_GET['duplicated']) && $_GET['duplicated'] == 1) {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Product duplicated successfully!', 'orderstock') . '</p></div>';
    }
}

add_filter('manage_tulipwork_product_posts_columns', 'tulipwork_orderstock_add_suppliers_column');
function tulipwork_orderstock_add_suppliers_column($columns) {
    $categories = isset($columns['taxonomy-tulipwork_prod_cat']) ? $columns['taxonomy-tulipwork_prod_cat'] : '';
    unset($columns['taxonomy-tulipwork_prod_cat']);
    
    $new_columns = [];
    foreach ($columns as $key => $value) {
        $new_columns[$key] = $value;
        if ($key === 'title') {
            if ($categories) {
                $new_columns['taxonomy-tulipwork_prod_cat'] = $categories;
            }
            $new_columns['suppliers'] = __('Suppliers', 'orderstock');
        }
    }
    
    if (!isset($new_columns['taxonomy-tulipwork_prod_cat']) && $categories) {
        $new_columns['taxonomy-tulipwork_prod_cat'] = $categories;
    }
    if (!isset($new_columns['suppliers'])) {
        $new_columns['suppliers'] = __('Suppliers', 'orderstock');
    }
    
    return $new_columns;
}

add_action('manage_tulipwork_product_posts_custom_column', 'tulipwork_orderstock_fill_suppliers_column', 10, 2);
function tulipwork_orderstock_fill_suppliers_column($column, $post_id) {
    if ($column === 'suppliers') {
        $is_premium = tulipwork_orderstock_is_premium();
        $is_internal_recipe = $is_premium ? get_post_meta($post_id, '_is_internal_recipe', true) ? 1 : 0 : 0;
        $main_supplier_id = get_post_meta($post_id, '_supplier', true);
        
        // Ajouter les attributs data pour JavaScript
        echo '<div class="suppliers-cell" data-supplier-id="' . esc_attr($main_supplier_id ?: '-1') . '" data-is-internal-recipe="' . esc_attr($is_internal_recipe) . '">';
        
        if ($is_premium) {
            $supplier_ids = get_post_meta($post_id, '_suppliers', true);
            
            if (is_array($supplier_ids) && !empty($supplier_ids)) {
                $display_suppliers = array_map(function($supplier_id) use ($main_supplier_id) {
                    $supplier_post = get_post($supplier_id);
                    $supplier_name = $supplier_post ? $supplier_post->post_title : '—';
                    return $supplier_id == $main_supplier_id ? '<strong>' . esc_html($supplier_name) . '</strong>' : esc_html($supplier_name);
                }, $supplier_ids);
                echo implode(', ', $display_suppliers);
            } elseif ($main_supplier_id) {
                $main_supplier_post = get_post($main_supplier_id);
                echo '<strong>' . esc_html($main_supplier_post ? $main_supplier_post->post_title : '—') . '</strong>';
            } else {
                echo '—';
            }
            $multi_store_enabled = get_option('orderstock_pro_central_kitchen_enabled', 0);
            if ($is_internal_recipe && $multi_store_enabled) {
                echo '<br><span style="color: green;">' . esc_html__('Internal Recipe', 'orderstock-pro') . '</span>';
            }
        } else {
            $main_supplier_post = $main_supplier_id ? get_post($main_supplier_id) : null;
            echo $main_supplier_post ? esc_html($main_supplier_post->post_title) : '—';
        }

        echo '</div>';
    }
}

add_filter('manage_edit-tulipwork_product_sortable_columns', 'tulipwork_orderstock_make_suppliers_sortable');
function tulipwork_orderstock_make_suppliers_sortable($columns) {
    $columns['suppliers'] = 'supplier';
    return $columns;
}

add_action('pre_get_posts', 'tulipwork_orderstock_sort_suppliers_column');
function tulipwork_orderstock_sort_suppliers_column($query) {
    if (!is_admin() || !$query->is_main_query()) return;
    if ($query->get('post_type') !== 'tulipwork_product') return;

    $orderby = $query->get('orderby');
    if ($orderby === 'supplier') {
        $query->set('meta_key', '_supplier');
        $query->set('orderby', 'meta_value');
    }
}

add_action('pre_get_posts', 'tulipwork_orderstock_product_filter_query');
function tulipwork_orderstock_product_filter_query($query) {
    if (!is_admin() || !$query->is_main_query() || $query->get('post_type') !== 'tulipwork_product') {
        return;
    }

    if (!current_user_can('tulipwork_orderstock_access') || !isset($_GET['nonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'tulipwork_orderstock_product_filter')) {
        return;
    }

    $meta_query = [];
    $tax_query = [];

    // Filtre par fournisseur
    if (isset($_GET['supplier_filter']) && $_GET['supplier_filter'] !== '') {
        $meta_query[] = [
            'key' => '_supplier',
            'value' => sanitize_text_field(wp_unslash($_GET['supplier_filter'])),
            'compare' => '='
        ];
    }

    // Filtre par catégorie
    if (isset($_GET['product_category']) && $_GET['product_category'] !== '') {
        $tax_query[] = [
            'taxonomy' => 'tulipwork_prod_cat',
            'field' => 'term_id',
            'terms' => intval($_GET['product_category'])
        ];
    }

    // Appliquer les requêtes si nécessaire
    if (!empty($meta_query)) {
        $meta_query['relation'] = 'AND';
        $query->set('meta_query', $meta_query);
    }
    if (!empty($tax_query)) {
        $tax_query['relation'] = 'AND';
        $query->set('tax_query', $tax_query);
    }
}

add_action('save_post_tulipwork_product', 'tulipwork_orderstock_save_bulk_and_quick_edit');
function tulipwork_orderstock_save_bulk_and_quick_edit($post_id) {
    if (!current_user_can('tulipwork_orderstock_access')) return;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

    $nonce_verified = false;
    $is_quick_edit = false;
    if (isset($_POST['_inline_edit'])) {
        $is_quick_edit = true;
        $nonce_verified = wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_inline_edit'])), 'inlineeditnonce');
    } elseif (isset($_REQUEST['tulipwork_orderstock_nonce'])) {
        $nonce_verified = wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['tulipwork_orderstock_nonce'])), 'tulipwork_orderstock_save_edit');
    }

    if (!$nonce_verified) return;

    $is_premium = tulipwork_orderstock_is_premium();

    $supplier_quick = isset($_POST['tulipwork_orderstock_supplier_quick']) && $_POST['tulipwork_orderstock_supplier_quick'] !== '-1' ?
        sanitize_text_field(wp_unslash($_POST['tulipwork_orderstock_supplier_quick'])) : null;
    $tax_rate_quick = isset($_POST['tax_rate_quick']) && $_POST['tax_rate_quick'] !== '-1' ?
        floatval($_POST['tax_rate_quick']) : null;
    $assigned_stores_quick = isset($_POST['tulipwork_orderstock_assigned_stores_quick']) && is_array($_POST['tulipwork_orderstock_assigned_stores_quick']) ?
        array_map('intval', (array)$_POST['tulipwork_orderstock_assigned_stores_quick']) : null;
    $is_internal_recipe_quick = isset($_POST['is_internal_recipe_quick']) && $_POST['is_internal_recipe_quick'] !== '-1' ?
        intval($_POST['is_internal_recipe_quick']) : null;

    $supplier = isset($_POST['tulipwork_orderstock_supplier']) && $_POST['tulipwork_orderstock_supplier'] !== '-1' ?
        sanitize_text_field(wp_unslash($_POST['tulipwork_orderstock_supplier'])) : null;
    $suppliers = isset($_POST['tulipwork_orderstock_suppliers']) && is_array($_POST['tulipwork_orderstock_suppliers']) ?
        array_map('sanitize_text_field', (array)$_POST['tulipwork_orderstock_suppliers']) : [];
    $tax_rate = isset($_POST['tax_rate']) && $_POST['tax_rate'] !== '-1' ?
        floatval($_POST['tax_rate']) : null;
    $assigned_stores = isset($_POST['tulipwork_orderstock_assigned_stores']) && is_array($_POST['tulipwork_orderstock_assigned_stores']) ?
        array_map('intval', (array)$_POST['tulipwork_orderstock_assigned_stores']) : null;
    $is_internal_recipe = isset($_POST['is_internal_recipe']) && $_POST['is_internal_recipe'] !== '-1' ?
        intval($_POST['is_internal_recipe']) : null;

    if (isset($_POST['tulipwork_product_categories'])) {
        $categories = array_map('intval', (array)$_POST['tulipwork_product_categories']);
        wp_set_object_terms($post_id, $categories, 'tulipwork_prod_cat');
    }
    if (isset($_POST['tulipwork_product_categories_quick'])) {
        $categories = array_map('intval', (array)$_POST['tulipwork_product_categories_quick']);
        wp_set_object_terms($post_id, $categories, 'tulipwork_prod_cat');
    }

    if ($is_quick_edit) {
        if ($supplier_quick !== null) {
            $old_main_supplier = get_post_meta($post_id, '_supplier', true);
            update_post_meta($post_id, '_supplier', $supplier_quick);
            if ($is_premium) {
                $current_suppliers = get_post_meta($post_id, '_suppliers', true) ?: [];
                if (!is_array($current_suppliers)) $current_suppliers = [];
                // Retirer l’ancien Main Supplier s’il existe
                if ($old_main_supplier && in_array($old_main_supplier, $current_suppliers)) {
                    $current_suppliers = array_diff($current_suppliers, [$old_main_supplier]);
                }
                // Ajouter le nouveau Main Supplier s’il n’est pas déjà dans la liste
                if (!in_array($supplier_quick, $current_suppliers)) {
                    $current_suppliers[] = $supplier_quick;
                }
                update_post_meta($post_id, '_suppliers', array_values(array_unique($current_suppliers)));
            }
        }
        if ($tax_rate_quick !== null) update_post_meta($post_id, '_tax_rate', $tax_rate_quick);
        if ($assigned_stores_quick !== null) update_post_meta($post_id, '_assigned_stores', $assigned_stores_quick);
        if ($is_internal_recipe_quick !== null) update_post_meta($post_id, '_is_internal_recipe', $is_internal_recipe_quick);
    }

    if (!$is_quick_edit) {
        if ($is_premium) {
            if (empty($suppliers)) {
                update_post_meta($post_id, '_suppliers', [$supplier]);
                update_post_meta($post_id, '_supplier', $supplier);
            } else {
                if ($supplier !== null && !in_array($supplier, $suppliers)) {
                    $suppliers[] = $supplier;
                }
                update_post_meta($post_id, '_suppliers', $suppliers);
                update_post_meta($post_id, '_supplier', $supplier ?: $suppliers[0]);
            }
        } else {
            if ($supplier !== null) update_post_meta($post_id, '_supplier', $supplier);
        }

        if ($tax_rate !== null) update_post_meta($post_id, '_tax_rate', $tax_rate);
        if ($assigned_stores !== null) update_post_meta($post_id, '_assigned_stores', $assigned_stores);
        if ($is_internal_recipe !== null) update_post_meta($post_id, '_is_internal_recipe', $is_internal_recipe);
    }
}

add_action('admin_notices', 'tulipwork_orderstock_bulk_action_notices');
function tulipwork_orderstock_bulk_action_notices() {
    if (isset($_GET['bulk_duplicated']) && isset($_GET['nonce'])) {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])), 'tulipwork_orderstock_bulk_action')) {
            return;
        }
        if (!current_user_can('tulipwork_orderstock_access')) {
            return;
        }
        $count = intval($_GET['bulk_duplicated']);
        if ($count > 0) {
            printf(
                '<div class="updated"><p>' . esc_html__('Duplicated %d product(s) successfully.', 'orderstock') . '</p></div>',
                esc_html($count)
            );
        }
    }
}

add_action('admin_init', 'tulipwork_orderstock_restrict_pro_features');
function tulipwork_orderstock_restrict_pro_features() {
    // Rien à faire dans la version gratuite
}

add_filter('post_row_actions', 'tulipwork_orderstock_add_nonce_to_edit_link', 10, 2);
function tulipwork_orderstock_add_nonce_to_edit_link($actions, $post) {
    if ($post->post_type === 'tulipwork_product' && isset($actions['edit'])) {
        $actions['edit'] = str_replace(
            'post.php?',
            'post.php?_wpnonce=' . wp_create_nonce('tulipwork_orderstock_enqueue') . '&',
            $actions['edit']
        );
    }
    return $actions;
}

add_filter('admin_url', 'tulipwork_orderstock_add_nonce_to_new_post_link', 10, 2);
function tulipwork_orderstock_add_nonce_to_new_post_link($url, $path) {
    if (strpos($path, 'post-new.php?post_type=tulipwork_product') !== false || 
        strpos($path, 'post-new.php?post_type=tulipwork_supplier') !== false) {
        $url = add_query_arg('_wpnonce', wp_create_nonce('tulipwork_orderstock_enqueue'), $url);
    }
    return $url;
}

add_action('admin_init', 'tulipwork_orderstock_add_custom_capabilities');
function tulipwork_orderstock_add_custom_capabilities() {
    $role = get_role('tulipworkmember');
    if ($role) {
        $role->remove_cap('edit_tulipwork_products');
        $role->remove_cap('manage_terms');
        $role->remove_cap('edit_terms');
        $role->remove_cap('delete_terms');
        $role->remove_cap('assign_terms');
        $role->remove_cap('edit_posts');
        $role->remove_cap('publish_posts');
        $role->remove_cap('delete_posts');
        $role->remove_cap('edit_others_posts');
        $role->remove_cap('read_private_posts');
        $role->remove_cap('manage_options');
        $role->remove_cap('manage_categories');
        $role->add_cap('tulipwork_orderstock_access');
        $role->add_cap('read');
    }
    $admin_role = get_role('administrator');
    if ($admin_role) {
        $admin_role->add_cap('tulipwork_orderstock_access');
    }
}

add_action('admin_menu', 'tulipwork_orderstock_remove_unwanted_menus', 999);
function tulipwork_orderstock_remove_unwanted_menus() {
    if (defined('TULIPWORK_SAAS_MODE') && TULIPWORK_SAAS_MODE) {
        $user = wp_get_current_user();
        if (in_array('tulipworkmember', $user->roles)) {
            remove_menu_page('tools.php');
            remove_menu_page('edit.php');
            remove_menu_page('edit-comments.php');
        }
    }
}

add_filter('user_has_cap', 'force_orderstock_caps_for_tulipworkmember', 10, 3);
function force_orderstock_caps_for_tulipworkmember($allcaps, $cap, $args) {
    if (!isset($allcaps['tulipwork_orderstock_access']) || !$allcaps['tulipwork_orderstock_access']) {
        return $allcaps;
    }

    $orderstock_post_types = ['tulipwork_product', 'tulipwork_supplier', 'tulipwork_order'];
    $context_post_id = isset($args[2]) ? $args[2] : null;
    $post_type = $context_post_id ? get_post_type($context_post_id) : 
                 (isset($_GET['post_type']) ? sanitize_text_field($_GET['post_type']) : '');

    if ($post_type && in_array($post_type, $orderstock_post_types)) {
        $allcaps['publish_posts'] = true;
        $allcaps['create_posts'] = true;
        $allcaps['delete_posts'] = true;
        $allcaps['edit_posts'] = true;
    } elseif (isset($_GET['post_type']) && in_array($_GET['post_type'], $orderstock_post_types)) {
        $allcaps['publish_posts'] = true;
        $allcaps['create_posts'] = true;
        $allcaps['delete_posts'] = true;
        $allcaps['edit_posts'] = true;
    } elseif (basename($_SERVER['PHP_SELF']) === 'edit.php' && isset($_GET['post_type']) && in_array($_GET['post_type'], $orderstock_post_types)) {
        $allcaps['publish_posts'] = true;
        $allcaps['create_posts'] = true;
        $allcaps['delete_posts'] = true;
        $allcaps['edit_posts'] = true;
    } elseif (basename($_SERVER['PHP_SELF']) === 'post-new.php' && isset($_GET['post_type']) && in_array($_GET['post_type'], $orderstock_post_types)) {
        $allcaps['publish_posts'] = true;
        $allcaps['create_posts'] = true;
        $allcaps['delete_posts'] = true;
        $allcaps['edit_posts'] = true;
    } elseif (basename($_SERVER['PHP_SELF']) === 'edit-tags.php' && isset($_GET['taxonomy']) && $_GET['taxonomy'] === 'tulipwork_prod_cat') {
        $allcaps['manage_terms'] = true;
        $allcaps['edit_terms'] = true;
        $allcaps['delete_terms'] = true;
        $allcaps['assign_terms'] = true;
    }

    return $allcaps;
}

add_filter('parent_file', 'tulipwork_orderstock_set_parent_file', 999);
function tulipwork_orderstock_set_parent_file($parent_file) {
    global $pagenow;

    $orderstock_pages = [
        'edit-tags.php' => (isset($_GET['taxonomy']) && $_GET['taxonomy'] === 'tulipwork_prod_cat'),
        'term.php' => (isset($_GET['taxonomy']) && $_GET['taxonomy'] === 'tulipwork_prod_cat'),
        'post.php' => (isset($_GET['post']) && in_array(get_post_type($_GET['post']), ['tulipwork_product', 'tulipwork_supplier', 'tulipwork_store'])),
        'post-new.php' => (isset($_GET['post_type']) && in_array($_GET['post_type'], ['tulipwork_product', 'tulipwork_supplier', 'tulipwork_store'])),
        'admin.php' => (isset($_GET['page']) && $_GET['page'] === 'tulipwork_orderstock-order-details')
    ];

    if (isset($orderstock_pages[$pagenow]) && $orderstock_pages[$pagenow]) {
        $parent_file = 'tulipwork_orderstock';
    }

    return $parent_file;
}

add_filter('submenu_file', 'tulipwork_orderstock_set_submenu_file', 999, 2);
function tulipwork_orderstock_set_submenu_file($submenu_file, $parent_file) {
    global $pagenow;

    if ($parent_file !== 'tulipwork_orderstock') {
        return $submenu_file;
    }

    if ($pagenow === 'edit-tags.php' && isset($_GET['taxonomy']) && $_GET['taxonomy'] === 'tulipwork_prod_cat') {
        $submenu_file = 'edit-tags.php?taxonomy=tulipwork_prod_cat&post_type=tulipwork_product';
    } elseif ($pagenow === 'term.php' && isset($_GET['taxonomy']) && $_GET['taxonomy'] === 'tulipwork_prod_cat') {
        $submenu_file = 'edit-tags.php?taxonomy=tulipwork_prod_cat&post_type=tulipwork_product';
    } elseif ($pagenow === 'post.php' && isset($_GET['post'])) {
        $post_type = get_post_type($_GET['post']);
        if ($post_type === 'tulipwork_product') {
            $submenu_file = 'edit.php?post_type=tulipwork_product';
        } elseif ($post_type === 'tulipwork_supplier') {
            $submenu_file = 'edit.php?post_type=tulipwork_supplier';
        } elseif ($post_type === 'tulipwork_store') {
            $submenu_file = 'edit.php?post_type=tulipwork_store';
        }
    } elseif ($pagenow === 'post-new.php' && isset($_GET['post_type'])) {
        if ($_GET['post_type'] === 'tulipwork_product') {
            $submenu_file = 'edit.php?post_type=tulipwork_product';
        } elseif ($_GET['post_type'] === 'tulipwork_supplier') {
            $submenu_file = 'edit.php?post_type=tulipwork_supplier';
        } elseif ($_GET['post_type'] === 'tulipwork_store') {
            $submenu_file = 'edit.php?post_type=tulipwork_store';
        }
    } elseif ($pagenow === 'admin.php' && isset($_GET['page']) && $_GET['page'] === 'tulipwork_orderstock-order-details') {
        $submenu_file = 'tulipwork_orderstock-order-history';
    }

    return $submenu_file;
}

add_action('admin_head', 'tulipwork_orderstock_force_menu_open_head');
function tulipwork_orderstock_force_menu_open_head() {
    if (isset($_GET['page']) && $_GET['page'] === 'tulipwork_orderstock-order-details') {
        ?>
        <style type="text/css">
            #toplevel_page_tulipwork_orderstock { display: block !important; }
            #toplevel_page_tulipwork_orderstock .wp-submenu { display: block !important; }
            #toplevel_page_tulipwork_orderstock .wp-submenu li a[href="admin.php?page=tulipwork_orderstock-order-history"] {
                background: #2271b1;
                color: white;
            }
        </style>
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function() {
                var menu = document.getElementById('toplevel_page_tulipwork_orderstock');
                if (menu) {
                    menu.classList.add('wp-has-current-submenu', 'wp-menu-open');
                    menu.classList.remove('wp-not-current-submenu');
                    var submenu = menu.querySelector('.wp-submenu');
                    if (submenu) submenu.style.display = 'block';
                }
            });
        </script>
        <?php
    }
}

add_action('bulk_edit_custom_box', 'tulipwork_orderstock_bulk_edit_fields', 10, 2);
function tulipwork_orderstock_bulk_edit_fields($column_name, $post_type) {
    static $fields_displayed = false;
    if ($fields_displayed || $post_type !== 'tulipwork_product' || !current_user_can('tulipwork_orderstock_access')) return;

    if ($column_name === 'taxonomy-tulipwork_prod_cat') {
        $fields_displayed = true;

        $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 = [
            '-1' => esc_html__('— No Change —', 'orderstock'),
            '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, '.', '')),
        ];
        $is_premium = tulipwork_orderstock_is_premium();
        $multi_store_enabled = get_option('orderstock_pro_central_kitchen_enabled', 0);

        echo '<style>
            .inline-edit-row fieldset label span.title {
                width: auto !important;
                display: contents !important;
                margin: 0 !important;
                padding: 0 !important;
            }
            .inline-edit-row fieldset label.inline-edit-group {
                margin: 10px !important;
            }
            .inline-edit-col div.bulk-edit-stores-container {
                max-height: 100px !important;
                overflow-y: auto !important;
                margin: 0 !important;
                padding: 0 !important;
            }
            .inline-edit-col div.bulk-edit-stores-container label.bulk-edit-store-label {
                display: block !important;
                margin: 2px 0 !important;
                padding: 0 !important;
                line-height: 1.2 !important;
            }
        </style>';

        ob_start();
        ?>
        <fieldset class="inline-edit-col-right">
            <div class="inline-edit-col">
                <label class="inline-edit-group">
                    <span class="title"><?php esc_html_e('Main Supplier', 'orderstock'); ?></span>
                    <select name="tulipwork_orderstock_supplier_bulk">
                        <option value="-1"><?php esc_html_e('— No Change —', 'orderstock'); ?></option>
                        <?php
                        $suppliers = get_posts([
                            'post_type' => 'tulipwork_supplier',
                            'posts_per_page' => -1,
                            'orderby' => 'title',
                            'order' => 'ASC',
                        ]);
                        foreach ($suppliers as $supplier) {
                            echo '<option value="' . esc_attr($supplier->ID) . '">' . esc_html($supplier->post_title) . '</option>';
                        }
                        ?>
                    </select>
                </label>
                <label class="inline-edit-group">
                    <span class="title"><?php esc_html_e('Tax Rate', 'orderstock'); ?></span>
                    <select name="tulipwork_orderstock_tax_rate_bulk">
                        <?php foreach ($tax_options as $value => $label) : ?>
                            <option value="<?php echo esc_attr($value); ?>"><?php echo esc_html($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <?php if ($is_premium && $multi_store_enabled) : ?>
                    <label class="inline-edit-group">
                        <span class="title"><?php esc_html_e('Replace Store Assignment', 'orderstock'); ?></span>
                        <div class="bulk-edit-stores-container">
                            <?php
                            $stores = get_posts([
                                'post_type' => 'tulipwork_store',
                                'posts_per_page' => -1,
                                'orderby' => 'title',
                                'order' => 'ASC',
                            ]);
                            foreach ($stores as $store) : ?>
                                <label class="bulk-edit-store-label">
                                    <input type="checkbox" name="tulipwork_orderstock_assigned_stores_bulk[]" value="<?php echo esc_attr($store->ID); ?>" />
                                    <?php echo esc_html($store->post_title); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </label>
                    <label class="inline-edit-group">
                        <span class="title"><?php esc_html_e('Internal Recipe', 'orderstock'); ?></span>
                        <select name="is_internal_recipe_bulk">
                            <option value="-1"><?php esc_html_e('— No Change —', 'orderstock'); ?></option>
                            <option value="0"><?php esc_html_e('No', 'orderstock'); ?></option>
                            <option value="1"><?php esc_html_e('Yes', 'orderstock'); ?></option>
                        </select>
                    </label>
                <?php endif; ?>
            </div>
        </fieldset>
        <?php
        $html_output = ob_get_clean();
        echo $html_output;
    }
}

add_action('bulk_edit_posts', 'tulipwork_orderstock_save_bulk_edit_products', 10, 2);
function tulipwork_orderstock_save_bulk_edit_products($post_ids, $data) {
    if (!current_user_can('tulipwork_orderstock_access') || empty($post_ids)) return;

    $is_premium = tulipwork_orderstock_is_premium();
    $multi_store_enabled = get_option('orderstock_pro_central_kitchen_enabled', 0);

    $supplier = isset($data['tulipwork_orderstock_supplier_bulk']) && $data['tulipwork_orderstock_supplier_bulk'] !== '-1' ?
        sanitize_text_field($data['tulipwork_orderstock_supplier_bulk']) : null;
    $tax_rate = isset($data['tulipwork_orderstock_tax_rate_bulk']) && $data['tulipwork_orderstock_tax_rate_bulk'] !== '-1' ?
        floatval($data['tulipwork_orderstock_tax_rate_bulk']) : null;

    foreach ($post_ids as $post_id) {
        if ($supplier !== null) {
            $old_main_supplier = get_post_meta($post_id, '_supplier', true);
            update_post_meta($post_id, '_supplier', $supplier);
            if ($is_premium) {
                $current_suppliers = get_post_meta($post_id, '_suppliers', true) ?: [];
                if (!is_array($current_suppliers)) $current_suppliers = [];
                // Retirer l’ancien Main Supplier s’il existe
                if ($old_main_supplier && in_array($old_main_supplier, $current_suppliers)) {
                    $current_suppliers = array_diff($current_suppliers, [$old_main_supplier]);
                }
                // Ajouter le nouveau Main Supplier s’il n’est pas déjà dans la liste
                if (!in_array($supplier, $current_suppliers)) {
                    $current_suppliers[] = $supplier;
                }
                update_post_meta($post_id, '_suppliers', array_values(array_unique($current_suppliers)));
            }
        }
        if ($tax_rate !== null) update_post_meta($post_id, '_tax_rate', $tax_rate);

        if ($is_premium && $multi_store_enabled) {
            if (isset($data['tulipwork_orderstock_assigned_stores_bulk']) && is_array($data['tulipwork_orderstock_assigned_stores_bulk'])) {
                $assigned_stores = array_map('intval', $data['tulipwork_orderstock_assigned_stores_bulk']);
                update_post_meta($post_id, '_assigned_stores', $assigned_stores);
            }
            if (isset($data['is_internal_recipe_bulk']) && $data['is_internal_recipe_bulk'] !== '-1') {
                $is_internal_recipe = intval($data['is_internal_recipe_bulk']);
                update_post_meta($post_id, '_is_internal_recipe', $is_internal_recipe);
            }
        }
    }
}

add_action('quick_edit_custom_box', 'tulipwork_orderstock_quick_edit_fields', 10, 2);
function tulipwork_orderstock_quick_edit_fields($column_name, $post_type) {
    static $fields_displayed = false;
    if ($fields_displayed || $post_type !== 'tulipwork_product' || !current_user_can('tulipwork_orderstock_access')) return;

    if ($column_name === 'taxonomy-tulipwork_prod_cat') {
        $fields_displayed = true;

        $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, '.', '')),
        ];
        $is_premium = tulipwork_orderstock_is_premium();
        $multi_store_enabled = get_option('orderstock_pro_central_kitchen_enabled', 0);

        echo '<style>
            .inline-edit-row fieldset label span.title {
                width: auto !important;
                display: contents !important;
                margin: 0 !important;
                padding: 0 !important;
            }
            .inline-edit-row fieldset label.inline-edit-group {
                margin: 10px !important;
            }
            .inline-edit-col div.quick-edit-stores-container {
                max-height: 100px !important;
                overflow-y: auto !important;
                margin: 0 !important;
                padding: 0 !important;
            }
            .inline-edit-col div.quick-edit-stores-container label.quick-edit-store-label {
                display: block !important;
                margin: 2px 0 !important;
                padding: 0 !important;
                line-height: 1.2 !important;
            }
        </style>';
        ?>
        <fieldset class="inline-edit-col-right">
            <div class="inline-edit-col">
                <label class="inline-edit-group">
                    <span class="title"><?php esc_html_e('Main Supplier', 'orderstock'); ?></span>
                    <select name="tulipwork_orderstock_supplier_quick">
                        <option value="-1"><?php esc_html_e('— No Change —', 'orderstock'); ?></option>
                        <?php
                        $suppliers = get_posts([
                            'post_type' => 'tulipwork_supplier',
                            'posts_per_page' => -1,
                            'orderby' => 'title',
                            'order' => 'ASC',
                        ]);
                        foreach ($suppliers as $supplier) {
                            echo '<option value="' . esc_attr($supplier->ID) . '">' . esc_html($supplier->post_title) . '</option>';
                        }
                        ?>
                    </select>
                </label>
                <label class="inline-edit-group">
                    <span class="title"><?php esc_html_e('Tax Rate', 'orderstock'); ?></span>
                    <select name="tax_rate_quick">
                        <option value="-1"><?php esc_html_e('— No Change —', 'orderstock'); ?></option>
                        <?php foreach ($tax_options as $value => $label) : ?>
                            <option value="<?php echo esc_attr($value); ?>"><?php echo esc_html($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <?php if ($is_premium && $multi_store_enabled) : ?>
                    <label class="inline-edit-group">
                        <span class="title"><?php esc_html_e('Replace Store Assignment', 'orderstock'); ?></span>
                        <div class="quick-edit-stores-container">
                            <?php
                            $stores = get_posts([
                                'post_type' => 'tulipwork_store',
                                'posts_per_page' => -1,
                                'orderby' => 'title',
                                'order' => 'ASC',
                            ]);
                            foreach ($stores as $store) : ?>
                                <label class="quick-edit-store-label">
                                    <input type="checkbox" name="tulipwork_orderstock_assigned_stores_quick[]" value="<?php echo esc_attr($store->ID); ?>" />
                                    <?php echo esc_html($store->post_title); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </label>
                    <label class="inline-edit-group">
                        <span class="title"><?php esc_html_e('Internal Recipe', 'orderstock'); ?></span>
                        <select name="is_internal_recipe_quick">
                            <option value="-1"><?php esc_html_e('— No Change —', 'orderstock'); ?></option>
                            <option value="0"><?php esc_html_e('No', 'orderstock'); ?></option>
                            <option value="1"><?php esc_html_e('Yes', 'orderstock'); ?></option>
                        </select>
                    </label>
                <?php endif; ?>
            </div>
        </fieldset>
        <?php
    }
}

add_action('admin_enqueue_scripts', 'tulipwork_orderstock_quick_edit_script');
function tulipwork_orderstock_quick_edit_script($hook) {
    if ($hook === 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] === 'tulipwork_product') {
        wp_enqueue_script(
            'tulipwork-orderstock-quick-edit',
            plugin_dir_url(__FILE__) . 'includes/js/quick-edit.js',
            ['jquery', 'inline-edit-post'],
            OrderStock::get_version(),
            true
        );
    }
}

add_filter('plugin_row_meta', 'orderstock_add_uninstall_warning_meta', 10, 4);
function orderstock_add_uninstall_warning_meta($plugin_meta, $plugin_file, $plugin_data, $status) {
    if (!defined('TULIPWORK_SAAS_MODE') || !TULIPWORK_SAAS_MODE) {
        if ($plugin_file === 'orderstock/orderstock.php' || $plugin_file === 'orderstock-pro/orderstock-pro.php') {
            $delete_data = get_option('tulipwork_orderstock_delete_data_on_uninstall', 0);
            if ($delete_data) {
                $warning = '<span style="color: #d63638; font-weight: bold;">' . 
                           esc_html__('Warning: "Delete Data on Uninstall" is enabled. Deleting this plugin will permanently remove all associated data (products, suppliers, orders, settings, stores, stock table, roles).', 'orderstock') . 
                           '</span>';
                $plugin_meta[] = $warning;
            }
        }
    }
    return $plugin_meta;
}

register_activation_hook(__FILE__, 'tulipwork_orderstock_activate');
function tulipwork_orderstock_activate() {
    tulipwork_orderstock_add_base_capabilities();
}

function tulipwork_orderstock_migrate_supplier_meta() {
    if (get_option('tulipwork_orderstock_supplier_migration_done')) {
        return;
    }

    $products = get_posts([
        'post_type' => 'tulipwork_product',
        'posts_per_page' => -1,
        'post_status' => 'publish',
    ]);

    $suppliers = get_posts([
        'post_type' => 'tulipwork_supplier',
        'posts_per_page' => -1,
        'fields' => 'id=>post_title',
    ]);

    $supplier_map = [];
    foreach ($suppliers as $id => $title) {
        $supplier_map[$title] = $id;
    }

    foreach ($products as $product) {
        $main_supplier = get_post_meta($product->ID, '_supplier', true);
        if ($main_supplier && isset($supplier_map[$main_supplier])) {
            update_post_meta($product->ID, '_supplier', $supplier_map[$main_supplier]);
        }

        $assigned_suppliers = get_post_meta($product->ID, '_suppliers', true);
        if (is_array($assigned_suppliers) && !empty($assigned_suppliers)) {
            $new_suppliers = [];
            foreach ($assigned_suppliers as $supplier_name) {
                if (isset($supplier_map[$supplier_name])) {
                    $new_suppliers[] = $supplier_map[$supplier_name];
                }
            }
            if (!empty($new_suppliers)) {
                update_post_meta($product->ID, '_suppliers', $new_suppliers);
            }
        }

        $prices_excl_tax = get_post_meta($product->ID, '_prices_excl_tax', true);
        if (is_array($prices_excl_tax) && !empty($prices_excl_tax)) {
            $new_prices = [];
            foreach ($prices_excl_tax as $supplier_name => $price) {
                if (isset($supplier_map[$supplier_name])) {
                    $new_prices[$supplier_map[$supplier_name]] = $price;
                }
            }
            if (!empty($new_prices)) {
                update_post_meta($product->ID, '_prices_excl_tax', $new_prices);
            }
        }
    }

    update_option('tulipwork_orderstock_supplier_migration_done', 1);
}

add_action('tulipwork_orderstock_init', 'tulipwork_orderstock_migrate_supplier_meta');

add_action('wp_ajax_tulipwork_orderstock_download_pdf', 'tulipwork_orderstock_download_pdf');
add_action('wp_ajax_nopriv_tulipwork_orderstock_download_pdf', 'tulipwork_orderstock_download_pdf');
function tulipwork_orderstock_download_pdf() {
    $filename = isset($_GET['filename']) ? sanitize_file_name($_GET['filename']) : '';
    $supplier_id = isset($_GET['supplier_id']) ? intval($_GET['supplier_id']) : 0;
    $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : '';

    if (!$filename || !$supplier_id || !wp_verify_nonce($nonce, 'tulipwork_orderstock_download_pdf')) {
        error_log("OrderStock: Invalid request - filename=$filename, supplier_id=$supplier_id, nonce=$nonce");
        wp_die(esc_html__('Invalid request.', 'orderstock'));
    }

    $upload_dir_info = wp_upload_dir();
    $file_path = $upload_dir_info['basedir'] . '/tulipwork_orderstock/' . $filename;

    if (file_exists($file_path)) {
        error_log("OrderStock: Serving PDF file: $file_path");
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($file_path));
        header('Cache-Control: no-cache, no-store, must-revalidate');
        header('Pragma: no-cache');
        header('Expires: 0');
        readfile($file_path);
        exit;
    } else {
        error_log("OrderStock: PDF file not found: $file_path");
        wp_die(esc_html__('File not found.', 'orderstock'));
    }
}



add_action('tulipwork_orderstock_cleanup_temp_files', 'tulipwork_orderstock_cleanup_temp_files');
function tulipwork_orderstock_cleanup_temp_files() {
    $upload_dir_info = wp_upload_dir();
    $upload_dir = $upload_dir_info['basedir'] . '/tulipwork_orderstock/';
    $files = glob($upload_dir . '*.pdf');
    $now = time();

    foreach ($files as $file) {
        if (file_exists($file) && ($now - filemtime($file)) > 300) { // 300 secondes = 5 minutes
            wp_delete_file($file);
        }
    }
}

register_activation_hook(__FILE__, 'tulipwork_orderstock_schedule_cleanup');
function tulipwork_orderstock_schedule_cleanup() {
    if (!wp_next_scheduled('tulipwork_orderstock_cleanup_temp_files')) {
        wp_schedule_event(time(), 'hourly', 'tulipwork_orderstock_cleanup_temp_files');
    }
}

register_deactivation_hook(__FILE__, 'tulipwork_orderstock_clear_schedule');
function tulipwork_orderstock_clear_schedule() {
    wp_clear_scheduled_hook('tulipwork_orderstock_cleanup_temp_files');
}

// Gérer le téléchargement des PDFs via jeton
add_action('template_redirect', 'tulipwork_orderstock_download_pdf_by_token');
function tulipwork_orderstock_download_pdf_by_token() {
    if (isset($_GET['tulipwork_pdf_download'])) {
        $pdf_token = sanitize_text_field($_GET['tulipwork_pdf_download']);
        $pdf_tokens = get_option('tulipwork_orderstock_pdf_tokens', []);
        $company_name = get_option('tulipwork_orderstock_company_name', 'Merco6');

        if (isset($pdf_tokens[$pdf_token]) && $pdf_tokens[$pdf_token]['expires'] > time()) {
            $file_path = $pdf_tokens[$pdf_token]['file'];
            $filename = $pdf_tokens[$pdf_token]['filename'];

            if (file_exists($file_path)) {
                error_log("OrderStock: Serving PDF for token $pdf_token: $file_path");
                header('Content-Type: application/pdf');
                header('Content-Disposition: attachment; filename="' . $filename . '"');
                header('Content-Length: ' . filesize($file_path));
                header('Cache-Control: no-cache, no-store, must-revalidate');
                header('Pragma: no-cache');
                header('Expires: 0');
                readfile($file_path);
                exit;
            } else {
                error_log("OrderStock: PDF file not found for token $pdf_token: $file_path");
                wp_die(esc_html__('File not found.', 'orderstock'));
            }
        } else {
            error_log("OrderStock: PDF token $pdf_token expired or invalid");
            wp_die(sprintf(
                esc_html__('This link has expired. Please check the email sent by %s to download the order PDF.', 'orderstock'),
                esc_html($company_name)
            ));
        }
    }
}

// Nettoyer les jetons expirés avec la tâche de nettoyage
add_action('tulipwork_orderstock_cleanup_temp_files', 'tulipwork_orderstock_cleanup_pdf_tokens');
function tulipwork_orderstock_cleanup_pdf_tokens() {
    $pdf_tokens = get_option('tulipwork_orderstock_pdf_tokens', []);
    $now = time();
    $updated = false;

    foreach ($pdf_tokens as $pdf_token => $data) {
        if ($data['expires'] < $now) {
            wp_delete_file($data['file']); // Supprimer le fichier PDF
            unset($pdf_tokens[$pdf_token]);
            $updated = true;
            error_log("OrderStock: Cleaned expired PDF token $pdf_token for file: " . $data['file']);
        }
    }

    if ($updated) {
        update_option('tulipwork_orderstock_pdf_tokens', $pdf_tokens);
    }
}

add_action('created_tulipwork_prod_cat', 'orderstock_save_category_lowercase', 10, 2);
add_action('edited_tulipwork_prod_cat', 'orderstock_save_category_lowercase', 10, 2);
function orderstock_save_category_lowercase($term_id, $tt_id) {
    $term = get_term($term_id, 'tulipwork_prod_cat');
    if ($term && !is_wp_error($term) && !empty($term->name)) {
        update_term_meta($term_id, '_name_lowercase', strtolower($term->name));
    }
}

add_action('restrict_manage_posts', 'tulipwork_orderstock_add_category_filter');
function tulipwork_orderstock_add_category_filter($post_type) {
    if ($post_type !== 'tulipwork_product' || !current_user_can('tulipwork_orderstock_access')) {
        return;
    }

    $categories = get_terms([
        'taxonomy' => 'tulipwork_prod_cat',
        'hide_empty' => false,
    ]);
    $selected_category = isset($_GET['product_category']) ? intval($_GET['product_category']) : '';
    $nonce = wp_create_nonce('tulipwork_orderstock_product_filter');

    ?>
    <select name="product_category" id="product_category">
        <option value=""><?php esc_html_e('All Categories', 'orderstock'); ?></option>
        <?php foreach ($categories as $category) : ?>
            <option value="<?php echo esc_attr($category->term_id); ?>" <?php selected($selected_category, $category->term_id); ?>>
                <?php echo esc_html($category->name); ?>
            </option>
        <?php endforeach; ?>
    </select>
    <input type="hidden" name="nonce" value="<?php echo esc_attr($nonce); ?>">
    <?php
}

add_action('tulipwork_orderstock_init', 'tulipwork_orderstock_migrate_price_excl_tax');
function tulipwork_orderstock_migrate_price_excl_tax() {
    if (get_option('tulipwork_orderstock_price_migration_done')) {
        return;
    }

    $products = get_posts([
        'post_type' => 'tulipwork_product',
        'posts_per_page' => -1,
        'post_status' => 'publish',
    ]);

    foreach ($products as $product) {
        $price_excl_tax = get_post_meta($product->ID, '_price_excl_tax', true);
        $main_supplier = get_post_meta($product->ID, '_supplier', true);
        $prices_excl_tax = get_post_meta($product->ID, '_prices_excl_tax', true) ?: [];

        if ($price_excl_tax !== '' && $main_supplier && !isset($prices_excl_tax[$main_supplier])) {
            $prices_excl_tax[$main_supplier] = floatval($price_excl_tax);
            update_post_meta($product->ID, '_prices_excl_tax', $prices_excl_tax);
            delete_post_meta($product->ID, '_price_excl_tax');
        }
    }

    update_option('tulipwork_orderstock_price_migration_done', 1);
}

?>