<?php
/**
 * Bizmart — Products admin page.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */
if (!defined('ABSPATH')) exit;

// Guard: this admin page requires WooCommerce
if ( ! function_exists('wc_get_products') ) {
    echo '<div class="wrap"><div class="notice notice-error"><p><strong>Bizmart:</strong> WooCommerce is required for this page.</p></div></div>';
    return;
}

/**
 * Performance upgrade:
 * - Avoid loading the entire product catalog on every admin page load.
 * - Cache statistics for a short period.
 */
// --- Global Flags & State ---
$is_edit = (isset($_GET['action']) && sanitize_key(wp_unslash($_GET['action'])) === 'edit' && !empty($_GET['id']));
$edit_name = '';

$stats_cache_key = 'bizmart_products_stats_v5_' . (int) get_current_blog_id();

// Manual refresh for debugging: /wp-admin/admin.php?page=bizmart-products&bizmart_refresh=1
if (isset($_GET['bizmart_refresh']) && current_user_can('manage_woocommerce')) {
    bizmart_invalidate_product_metrics_cache(null, 'manual_refresh');
}

// Force refresh: delete metrics cache on every page load to ensure accuracy
// 21-23: Clean up transients (removed for performance)

$stats = get_transient($stats_cache_key);

if (!$stats || !is_array($stats)) {
    // Total products (all published products)
    global $wpdb;
    $total_products = (int) $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type = %s AND post_status = %s",
            'product',
            'publish'
        )
    );

    // Products without/zero price (count via SQL)
    $missing_price_query = new WP_Query([
        'post_type'      => 'product',
        'post_status'    => 'publish',
        'fields'         => 'ids',
        'posts_per_page' => 1,
        'no_found_rows'  => false,
        'meta_query'     => [
            'relation' => 'OR',
            [
                'key'     => '_price',
                'compare' => 'NOT EXISTS',
            ],
            [
                'key'     => '_price',
                'value'   => '',
                'compare' => '=',
            ],
            [
                'key'     => '_price',
                'value'   => 0,
                'type'    => 'NUMERIC',
                'compare' => '<=',
            ],
        ],
    ]);
    $products_without_price = (int) $missing_price_query->found_posts;

    // Product type counts (cheap taxonomy counts)
    $type_counts = [
        'simple' => 0,
        'variable' => 0,
        'grouped' => 0,
        'external' => 0,
    ];
    foreach (array_keys($type_counts) as $slug) {
        $term = get_term_by('slug', $slug, 'product_type');
        $type_counts[$slug] = $term ? (int) $term->count : 0;
    }

    // Unified inventory totals (RULE A: manage_stock=yes only)
    $inv = function_exists('bizmart_metrics_get_inventory_totals')
        ? bizmart_metrics_get_inventory_totals(true)
        : ['stock_sales_value' => 0, 'stock_purchase_value' => 0, 'total_stock_qty' => 0];

    $stock_value = (float) ($inv['stock_sales_value'] ?? 0);
    $stock_purchase_value = (float) ($inv['stock_purchase_value'] ?? 0);
    $total_stock = (float) ($inv['total_stock_qty'] ?? 0);

    // Debug: show breakdown when ?bizmart_debug=1 is present (admin-only)
    if (isset($_GET['bizmart_debug']) && current_user_can('manage_woocommerce')) {
        $rows = function_exists('bizmart_metrics_get_inventory_rows') ? bizmart_metrics_get_inventory_rows() : [];
        echo "<div style=\"padding:12px;background:#fff;border:1px solid #eee;margin:10px 0;\">";
        echo "<h3>Bizmart Inventory Debug</h3>";
        echo "<p><strong>Totals (fresh):</strong> " . esc_html(wp_json_encode(function_exists('bizmart_metrics_get_inventory_totals') ? bizmart_metrics_get_inventory_totals(false) : [])) . "</p>";
        echo "<pre style=\"max-height:300px;overflow:auto;\">" . esc_html(print_r(array_map(function($r){ return [(int)$r->product_id,$r->post_type,(float)$r->stock_qty,$r->sku,$r->title]; }, $rows), true)) . "</pre>";
        echo "</div>";
    }

$stats = compact('total_products', 'products_without_price', 'type_counts', 'stock_value', 'stock_purchase_value', 'total_stock');
    set_transient($stats_cache_key, $stats, HOUR_IN_SECONDS);
} else {
    $total_products = (int) ($stats['total_products'] ?? 0);
    $products_without_price = (int) ($stats['products_without_price'] ?? 0);
    $type_counts = (array) ($stats['type_counts'] ?? []);
    $stock_value = (float) ($stats['stock_value'] ?? 0);
    $stock_purchase_value = (float) ($stats['stock_purchase_value'] ?? 0);
    $total_stock = (float) ($stats['total_stock'] ?? 0);
}

// Get all product categories
$product_categories = get_terms([
    'taxonomy' => 'product_cat',
    'hide_empty' => false,
    'orderby' => 'name',
    'order' => 'ASC'
]);

// Get shipping classes
$shipping_classes = get_terms([
    'taxonomy' => 'product_shipping_class',
    'hide_empty' => false
]);

// Get recent products
$recent_products = wc_get_products([
    'limit' => 8,
    'orderby' => 'date',
    'order' => 'DESC',
    'status' => 'publish'
]);

// Grouped products selector can be huge; cap for performance (filterable)
$simple_limit = (int) apply_filters('bizmart_grouped_simple_products_limit', 500);
$simple_limit = $simple_limit > 0 ? $simple_limit : 500;

$simple_products = wc_get_products([
    'type'    => 'simple',
    'limit'   => $simple_limit,
    'status'  => 'publish',
    'orderby' => 'title',
    'order'   => 'ASC',
]);

// --- EDIT MODE DATA PREPARATION ---
$edit_data = null;
$edit_active_tab = 'simple';
if ($is_edit) {
    $p_id = intval(wp_unslash($_GET['id']));
    $p = wc_get_product($p_id);
    if ($p) {
        $edit_name = $p->get_name();
        $type = $p->get_type();
        if ($type === 'variable') $edit_active_tab = 'variable';
        elseif ($type === 'grouped') $edit_active_tab = 'grouped';
        elseif ($type === 'external') $edit_active_tab = 'external';
        elseif ($p->is_downloadable()) $edit_active_tab = 'digital';
        
        $edit_data = [
            'id' => $p->get_id(),
            'type' => $type,
            'name' => $p->get_name(),
            'sku' => $p->get_sku(),
            'regular_price' => $p->get_regular_price(),
            'sale_price' => $p->get_sale_price(),
            'short_description' => $p->get_short_description(),
            'description' => $p->get_description(),
            'manage_stock' => $p->get_manage_stock(),
            'stock_quantity' => $p->get_stock_quantity(),
            'stock_status' => $p->get_stock_status(),
            'cost_price' => get_post_meta($p_id, '_purchase_price', true),
            'categories' => $p->get_category_ids(),
            'image_id' => $p->get_image_id(),
            'gallery_ids' => $p->get_gallery_image_ids(),
        ];
        
        // Load tags
        $tags = wp_get_post_terms($p_id, 'product_tag', ['fields' => 'names']);
        $edit_data['tags'] = is_array($tags) ? $tags : [];
        
        // Load attributes and variations for variable products
        if ($type === 'variable') {
            $attributes = [];
            $product_attributes = $p->get_attributes();
            
            foreach ($product_attributes as $attribute) {
                $attr_data = [
                    'name' => $attribute->get_name(),
                    'options' => $attribute->get_options(),
                    'visible' => $attribute->get_visible(),
                    'variation' => $attribute->get_variation(),
                ];
                
                // Check if it's a taxonomy attribute
                if ($attribute->is_taxonomy()) {
                    $attr_data['is_taxonomy'] = true;
                    $attr_data['taxonomy'] = $attribute->get_name();
                    
                    // Get term names instead of IDs
                    $term_ids = $attribute->get_options();
                    $term_names = [];
                    foreach ($term_ids as $term_id) {
                        $term = get_term($term_id, $attribute->get_name());
                        if ($term && !is_wp_error($term)) {
                            $term_names[] = $term->name;
                        }
                    }
                    $attr_data['options'] = $term_names;
                    
                    // Get the label for display
                    $taxonomy = get_taxonomy($attribute->get_name());
                    if ($taxonomy) {
                        $attr_data['label'] = $taxonomy->labels->singular_name;
                    }
                } else {
                    $attr_data['is_taxonomy'] = false;
                    $attr_data['label'] = $attribute->get_name();
                }
                
                $attributes[] = $attr_data;
            }
            $edit_data['attributes'] = $attributes;
            
            // Load variations
            $variations = [];
            $variation_ids = $p->get_children();
            
            foreach ($variation_ids as $var_id) {
                $variation = wc_get_product($var_id);
                if (!$variation) continue;
                
                $var_attributes = [];
                $raw_attributes = $variation->get_attributes();
                
                foreach ($raw_attributes as $key => $value) {
                    // Remove 'attribute_' prefix and taxonomy prefix if present
                    $clean_key = str_replace('attribute_', '', $key);
                    $clean_key = str_replace('pa_', '', $clean_key);
                    
                    // Try to get proper attribute name
                    $attr_name = $clean_key;
                    foreach ($attributes as $parent_attr) {
                        $check_name = str_replace(' ', '-', strtolower($parent_attr['name']));
                        if ($check_name === $clean_key || $parent_attr['name'] === $clean_key) {
                            $attr_name = $parent_attr['label'];
                            break;
                        }
                    }
                    
                    $var_attributes[$attr_name] = $value;
                }
                
                // Get cost price from meta
                $cost_price = get_post_meta($var_id, '_purchase_price', true);
                
                $variations[] = [
                    'id' => $var_id,
                    'sku' => $variation->get_sku(),
                    'regular_price' => $variation->get_regular_price(),
                    'sale_price' => $variation->get_sale_price(),
                    'cost_price' => $cost_price ? floatval($cost_price) : '',
                    'stock_quantity' => $variation->get_stock_quantity(),
                    'attributes' => $var_attributes,
                ];
            }
            $edit_data['variations'] = $variations;
        }
    }
}
?>
<script>
window.BizmartEditData = <?php echo wp_json_encode($edit_data); ?>;
window.BizmartActiveTab = "<?php echo esc_js($edit_active_tab); ?>";

jQuery(document).ready(function($) {
    if (window.BizmartEditData) {
        var d = window.BizmartEditData;
        console.log('Bizmart Edit Mode:', d);

        // Switch Tab UI
        if (d.type) {
            var tabId = 'biz-tab-' + d.type;
            $('.biz-tab').removeClass('active'); 
            $('.biz-tab-content').removeClass('active');
            $('#' + tabId).addClass('active');
            
            // Also activate the tab button
            $(`.biz-tab[data-tab="${d.type}"]`).addClass('active');
        }

        // Populate Simple Product Form
        if (d.type === 'simple') {
            $('#biz-simple-name').val(d.name);
            $('#biz-simple-sku').val(d.sku);
            $('#biz-simple-regular-price').val(d.regular_price);
            $('#biz-simple-sale-price').val(d.sale_price);
            $('#biz-simple-cost-price').val(d.cost_price);
            
            // Trigger profit calculation
            if (typeof BizProducts !== 'undefined') BizProducts.calculateProfit('simple');
            $('#biz-simple-short-description').val(d.short_description);
            $('#biz-simple-description').val(d.description);
            
            if (d.manage_stock === 'yes' || d.manage_stock === true) {
                $('#biz-simple-manage-stock').prop('checked', true).trigger('change');
                $('#biz-simple-stock-quantity').val(d.stock_quantity);
            }
            $('#biz-simple-stock-status').val(d.stock_status);
            
            // Categories
            if (d.categories && d.categories.length) {
                $('#biz-simple-categories').val(d.categories);
            }
            
            // Tags
            if (d.tags && d.tags.length && typeof BizProducts !== 'undefined') {
                d.tags.forEach(tag => BizProducts.addTag('simple', tag));
            }
            
            // Image
            if (d.image_id) {
                $('#biz-simple-image-id').val(d.image_id);
                // Get image URL via AJAX or display placeholder
            }
            
            // Change Submit Button
            var $btn = $('button[onclick^="BizProducts.createSimpleProduct"]');
            $btn.html('💾 ' + (typeof bizmart_text !== 'undefined' ? bizmart_text('Update Product', 'Mettre à jour', 'تحديث المنتج') : 'Update Product'));
        }
        
        // Populate Variable Product
        if (d.type === 'variable') {
            $('#biz-variable-name').val(d.name);
            $('#biz-variable-sku').val(d.sku);
            $('#biz-variable-short-description').val(d.short_description);
            $('#biz-variable-description').val(d.description);
            $('#biz-variable-base-regular').val(d.regular_price);
            $('#biz-variable-base-sale').val(d.sale_price);
            
            // Categories
            if (d.categories && d.categories.length) {
                $('#biz-variable-categories').val(d.categories);
            }
            
            // Tags
            if (d.tags && d.tags.length && typeof BizProducts !== 'undefined') {
                d.tags.forEach(tag => BizProducts.addTag('variable', tag));
            }
            
            // Image
            if (d.image_id) {
                $('#biz-variable-image-id').val(d.image_id);
            }
            
            // Rebuild Attributes
            if (d.attributes && d.attributes.length && typeof BizProducts !== 'undefined') {
                $('#biz-variable-attributes').empty();
                BizProducts.attributeCount = 0;
                
                d.attributes.forEach(function(attr) {
                    BizProducts.attributeCount++;
                    const id = BizProducts.attributeCount;
                    const attrName = attr.label || attr.name;
                    const attrValues = attr.options.join(', ');
                    
                    const attributeHtml = `
                        <div class="biz-attribute-row" data-id="${id}">
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label>Attribute Name</label>
                                    <input type="text" class="biz-input attribute-name" value="${attrName}" readonly style="background: #f9fafb;">
                                </div>
                                <div class="biz-form-group">
                                    <label>Attribute Values</label>
                                    <div class="biz-tag-input" id="biz-attribute-values-${id}">
                                        ${attr.options.map(v => `<span class="biz-tag">${v} <span class="biz-tag-remove">×</span></span>`).join('')}
                                        <input type="text" class="biz-attribute-values-input" placeholder="Add value">
                                    </div>
                                    <input type="hidden" class="attribute-values" id="biz-attribute-values-hidden-${id}" value="${attrValues}">
                                </div>
                            </div>
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label style="display: flex; align-items: center; cursor: pointer;">
                                        <span class="biz-switch">
                                            <input type="checkbox" class="attribute-visible" ${attr.visible ? 'checked' : ''}>
                                            <span class="biz-slider"></span>
                                        </span>
                                        Visible on product page
                                    </label>
                                </div>
                                <div class="biz-form-group">
                                    <label style="display: flex; align-items: center; cursor: pointer;">
                                        <span class="biz-switch">
                                            <input type="checkbox" class="attribute-variation" ${attr.variation ? 'checked' : ''}>
                                            <span class="biz-slider"></span>
                                        </span>
                                        Used for variations
                                    </label>
                                </div>
                                <button type="button" class="biz-btn" onclick="BizProducts.removeAttribute(${id})">Remove</button>
                            </div>
                        </div>
                    `;
                    
                    $('#biz-variable-attributes').append(attributeHtml);
                    
                    // Bind tag input events
                    $(`#biz-attribute-values-${id} .biz-attribute-values-input`).on('keypress', function(e) {
                        if (e.key === 'Enter') {
                            e.preventDefault();
                            const tag = $(this).val().trim();
                            if (tag) {
                                const rowId = $(this).closest('.biz-attribute-row').data('id');
                                const $container = $(`#biz-attribute-values-${rowId}`);
                                $container.prepend(`<span class="biz-tag">${tag} <span class="biz-tag-remove">×</span></span>`);
                                $(this).val('');
                                BizProducts.updateAttributeValues(rowId);
                            }
                        }
                    });
                });
            }
            
            // Rebuild Variations
            if (d.variations && d.variations.length && typeof BizProducts !== 'undefined') {
                $('#biz-variations-container').empty();
                BizProducts.variationCount = 0;
                
                d.variations.forEach(function(varData) {
                    BizProducts.variationCount++;
                    const id = BizProducts.variationCount;
                    
                    // Build attribute display string
                    const attrPairs = [];
                    for (const [name, value] of Object.entries(varData.attributes)) {
                        attrPairs.push({name: name, value: value});
                    }
                    const attrString = attrPairs.map(p => `${p.name}: ${p.value}`).join(', ');
                    const comboJson = JSON.stringify(attrPairs);
                    
                    const variationHtml = `
                        <div class="biz-variation-row" id="variation-${id}" data-combo='${comboJson}' data-variation-id="${varData.id}">
                            <div class="biz-variation-header">
                                <h4 class="biz-variation-title">Variation ${id}</h4>
                                <button type="button" class="biz-remove-variation" onclick="BizProducts.removeVariation(${id})">
                                    &times;
                                </button>
                            </div>
                            
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label>Attributes</label>
                                    <input type="text" class="biz-input variation-attributes-display" value="${attrString}" readonly>
                                </div>
                                <div class="biz-form-group">
                                    <label>Variation SKU</label>
                                    <input type="text" class="biz-input variation-sku" value="${varData.sku || ''}" data-id="${id}">
                                </div>
                                <div class="biz-form-group">
                                    <label>Regular price</label>
                                    <input type="number" step="0.01" min="0" class="biz-input variation-regular-price" value="${varData.regular_price || ''}" data-id="${id}">
                                </div>
                            </div>
                            
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label>Sale price</label>
                                    <input type="number" step="0.01" min="0" class="biz-input variation-sale-price" value="${varData.sale_price || ''}" data-id="${id}">
                                </div>
                                <div class="biz-form-group">
                                    <label>Cost price</label>
                                    <input type="number" step="0.01" min="0" class="biz-input variation-cost-price" value="${varData.cost_price || ''}" data-id="${id}">
                                </div>
                                <div class="biz-form-group">
                                    <label>Stock</label>
                                    <input type="number" min="0" step="1" inputmode="numeric" pattern="[0-9]*" class="biz-input variation-stock" value="${varData.stock_quantity || ''}" data-id="${id}">
                                </div>
                            </div>
                        </div>
                    `;
                    
                    $('#biz-variations-container').append(variationHtml);
                });
            }
            // Change Submit Button
            var $vbtn = $('button[onclick^="BizProducts.createVariableProduct"]');
            $vbtn.html('💾 ' + (typeof bizmart_text !== 'undefined' ? bizmart_text('Update Product', 'Mettre à jour', 'تحديث المنتج') : 'Update Product'));
        }
    }
});
</script>
<?php if (false) : // Extracted to assets/products.css (enqueued on bizmart-products) ?>
    <style>
        .biz-products-container {
            display: flex;
            gap: 30px;
            margin-bottom: 30px;
        }
        
        .biz-products-main {
            flex: 4;
        }
        
        .biz-products-sidebar {
            flex: 1;
            min-width: 320px;
        }
        
        .biz-card {
            background: white;
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }
        
        .biz-tabs {
            display: flex;
            border-bottom: 2px solid #e5e7eb;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 5px;
        }
        
        .biz-tab {
            padding: 16px 24px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            margin-bottom: -2px;
            font-weight: 500;
            color: #6b7280;
            transition: all 0.3s;
            white-space: nowrap;
        }
        
        .biz-tab:hover {
            color: #4f46e5;
        }
        
        .biz-tab.active {
            color: #4f46e5;
            border-bottom-color: #4f46e5;
        }
        
        .biz-tab-content {
            display: none;
            animation: fadeIn 0.3s ease;
        }
        
        .biz-tab-content.active {
            display: block;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .biz-form-group {
            margin-bottom: 24px;
        }
        
        .biz-form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #374151;
            font-size: 14px;
        }
        
        .biz-form-group label.required:after {
            content: ' *';
            color: #ef4444;
        }
        
        .biz-input, .biz-select, .biz-textarea, .biz-multiselect {
            width: 100%;
            padding: 14px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 14px;
            box-sizing: border-box;
            transition: all 0.3s;
            background: white;
        }
        
        .biz-multiselect {
            min-height: 100px;
            padding: 10px;
        }
        
        .biz-multiselect option {
            padding: 8px;
            margin: 2px 0;
            border-radius: 4px;
        }
        
        .biz-multiselect option:hover {
            background: #f3f4f6;
        }
        
        .biz-input:focus, .biz-select:focus, .biz-textarea:focus, .biz-multiselect:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }
        
        .biz-textarea {
            min-height: 100px;
            resize: vertical;
        }
        
        .biz-textarea-small {
            min-height: 80px;
        }
        
        .biz-switch {
            position: relative;
            display: inline-block;
            width: 44px;
            height: 24px;
            vertical-align: middle;
            margin-right: 8px;
        }
        
        .biz-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .biz-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }
        
        .biz-slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .biz-slider {
            background-color: #10b981;
        }
        
        input:checked + .biz-slider:before {
            transform: translateX(20px);
        }
        
        .biz-btn {
            background-color: #4f46e5;
            color: white;
            padding: 14px 28px;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .biz-btn:hover {
            background-color: #4338ca;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .biz-btn-success {
            background-color: #10b981;
        }
        
        .biz-btn-success:hover {
            background-color: #059669;
        }
        
        .biz-btn-secondary {
            background-color: #fff;
            color: #374151;
            border: 1px solid #d1d5db;
        }
        
        .biz-btn-secondary:hover {
            background-color: #f9fafb;
            color: #111827;
            border-color: #9ca3af;
        }
        
        .biz-variation-row {
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 16px;
            position: relative;
        }
        
        .biz-variation-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }
        
        .biz-variation-title {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
            color: #374151;
        }
        
        .biz-remove-variation {
            background: none;
            border: none;
            color: #ef4444;
            cursor: pointer;
            font-size: 20px;
            padding: 0;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
        }
        
        .biz-remove-variation:hover {
            background: #fee2e2;
        }
        
        .biz-form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
        }
        
        .biz-form-grid-2 {
            grid-template-columns: 1fr 1fr;
        }
        
        .biz-form-grid-3 {
            grid-template-columns: 1fr 1fr 1fr;
        }
        
        .biz-form-grid-4 {
            grid-template-columns: 1fr 1fr 1fr 1fr;
        }
        
        .biz-stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }
        
        .biz-stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }
        
        .biz-stat-card.success {
            background: linear-gradient(135deg, #48bb78 0%, #38b2ac 100%);
        }
        
        .biz-stat-card.warning {
            background: linear-gradient(135deg, #ed8936 0%, #ecc94b 100%);
        }
        
        .biz-stat-card.info {
            background: linear-gradient(135deg, #4299e1 0%, #667eea 100%);
        }
        
        .biz-stat-value {
            font-size: 24px;
            font-weight: bold;
            margin: 10px 0;
        }
        
        .biz-stat-label {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .biz-alert {
            padding: 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid;
        }
        
        .biz-alert-success {
            background-color: #d1fae5;
            border-left-color: #10b981;
            color: #065f46;
        }
        
        .biz-alert-info {
            background-color: #dbeafe;
            border-left-color: #3b82f6;
            color: #1e40af;
        }
        
        .biz-alert-warning {
            background-color: #fef3c7;
            border-left-color: #f59e0b;
            color: #92400e;
        }
        
        .biz-section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f9fafb;
            border-radius: 12px;
        }
        
        .biz-section-title {
            margin: 0 0 20px 0;
            color: #374151;
            font-size: 18px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .biz-image-preview {
            width: 100px;
            height: 100px;
            border-radius: 8px;
            object-fit: cover;
            border: 2px solid #e5e7eb;
            margin-top: 10px;
            display: none;
        }
        
        .biz-image-preview.show {
            display: block;
        }
        
        .biz-image-upload-area {
            border: 2px dashed #d1d5db;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            min-height: 150px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        
        .biz-image-upload-area:hover {
            border-color: #4f46e5;
            background: #f9fafb;
        }
        
        .biz-gallery-images {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
        
        .biz-gallery-image {
            width: 80px;
            height: 80px;
            border-radius: 6px;
            object-fit: cover;
            position: relative;
        }
        
        .biz-remove-image {
            position: absolute;
            top: -8px;
            right: -8px;
            background: #ef4444;
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .biz-attributes-section {
            margin-top: 30px;
        }
        
        .biz-attribute-row {
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 12px;
        }
        
        .biz-toggle-section {
            cursor: pointer;
            padding: 15px;
            background: #f8fafc;
            border-radius: 8px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .biz-toggle-section:hover {
            background: #f1f5f9;
        }
        
        .biz-collapsible-content {
            display: none;
            padding: 20px;
            background: white;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
            margin-top: 10px;
        }
        
        .biz-collapsible-content.show {
            display: block;
        }
        
        .biz-recent-products {
            margin-top: 24px;
        }
        
        .biz-product-item {
            display: flex;
            align-items: center;
            padding: 12px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            margin-bottom: 8px;
            transition: all 0.3s;
        }
        
        .biz-product-item:hover {
            border-color: #4f46e5;
            background: #f9fafb;
        }
        
        .biz-product-icon {
            width: 40px;
            height: 40px;
            background: rgba(79, 70, 229, 0.1);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            color: #4f46e5;
        }
        
        .biz-product-info {
            flex: 1;
        }
        
        .biz-product-name {
            font-weight: 500;
            color: #374151;
            margin: 0 0 4px 0;
            font-size: 14px;
        }
        
        .biz-product-sku {
            font-size: 12px;
            color: #6b7280;
            margin: 0;
        }
        
        .biz-product-price {
            font-weight: 600;
            color: #059669;
            font-size: 14px;
        }
        
        .biz-radio-group {
            display: flex;
            gap: 20px;
            margin-top: 10px;
        }
        
        .biz-radio-label {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
        }
        
        .biz-advanced-settings {
            background: #f8fafc;
            border-radius: 8px;
            padding: 20px;
            margin-top: 30px;
        }
        
        .biz-tag-input {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            padding: 10px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            min-height: 44px;
            align-items: center;
        }
        
        .biz-tag {
            background: #e0e7ff;
            color: #4f46e5;
            padding: 4px 12px;
            border-radius: 16px;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .biz-tag-remove {
            cursor: pointer;
            font-size: 16px;
            line-height: 1;
        }
        
        .biz-tag-input input {
            border: none;
            outline: none;
            flex: 1;
            min-width: 100px;
            padding: 8px;
        }
        
        .biz-color-picker {
            width: 40px;
            height: 40px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            padding: 0;
        }
        
        .biz-date-picker {
            cursor: pointer;
        }
        
        .biz-loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #4f46e5;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .biz-category-creator {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        
        .biz-category-creator input {
            flex: 1;
            padding: 10px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
        }
        
        .biz-category-creator button {
            padding: 10px 20px;
            background: #4f46e5;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
        }
        
        .biz-shipping-section {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
            display: none;
        }
        
        .biz-shipping-section.show {
            display: block;
        }
        
        .biz-file-list {
            margin-top: 15px;
        }
        
        .biz-file-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px;
            background: #f9fafb;
            border-radius: 6px;
            margin-bottom: 8px;
        }
        
        .biz-file-name {
            display: flex;
            align-items: center;
            gap: 10px;
        }
    </style>
    <?php endif; ?>

    <?php
    $current_view = isset($_GET['view']) ? sanitize_text_field(wp_unslash($_GET['view'])) : 'list';
    // Ensure valid view
    if (!in_array($current_view, ['create', 'list', 'alerts'])) {
        $current_view = 'list';
    }
    
    // Tab URLs
    $base_url   = remove_query_arg(['view', 'paged', 's']);
    $create_url = add_query_arg('view', 'create', $base_url);
    $list_url   = add_query_arg('view', 'list', $base_url);
    $alerts_url = add_query_arg('view', 'alerts', $base_url);
    ?>

    <div class="wrap" style="padding: 20px 40px; box-sizing: border-box;">
    <?php if (!empty($edit_data) && !empty($edit_data['id'])) : ?>
        <input type="hidden" id="bizmart-edit-product-id" value="<?php echo esc_attr((int)$edit_data['id']); ?>">
        <input type="hidden" id="bizmart-edit-product-type" value="<?php echo esc_attr($edit_data['type'] ?? ''); ?>">
    <?php endif; ?>

    <div class="biz-products-container" style="flex-direction: column; gap: 0;">
        <!-- Header Tabs -->
        <div style="display: flex; gap: 20px; border-bottom: 2px solid #e5e7eb; padding-bottom: 0px; margin-bottom: 30px;">
            <a href="<?php echo esc_url($list_url); ?>" 
               style="text-decoration: none; padding: 10px 20px; font-weight: 600; font-size: 16px; border-bottom: 3px solid <?php echo esc_attr($current_view === 'list' ? '#4f46e5' : 'transparent'); ?>; color: <?php echo esc_attr($current_view === 'list' ? '#4f46e5' : '#6b7280'); ?>; transition: all 0.2s; margin-bottom: -2px;">
                📦 <?php echo esc_html(bizmart_text('Product List', 'Liste Produits', 'قائمة المنتجات')); ?>
            </a>
            <a href="<?php echo esc_url($alerts_url); ?>" 
               style="text-decoration: none; padding: 10px 20px; font-weight: 600; font-size: 16px; border-bottom: 3px solid <?php echo esc_attr($current_view === 'alerts' ? '#4f46e5' : 'transparent'); ?>; color: <?php echo esc_attr($current_view === 'alerts' ? '#4f46e5' : '#6b7280'); ?>; transition: all 0.2s; margin-bottom: -2px;">
                ⚠️ <?php echo esc_html(bizmart_text('Stock Alerts', 'Alertes Stock', 'تنبيهات المخزون')); ?>
            </a>
            <a href="<?php echo esc_url($create_url); ?>" 
               style="text-decoration: none; padding: 10px 20px; font-weight: 600; font-size: 16px; border-bottom: 3px solid <?php echo esc_attr($current_view === 'create' ? '#4f46e5' : 'transparent'); ?>; color: <?php echo esc_attr($current_view === 'create' ? '#4f46e5' : '#6b7280'); ?>; transition: all 0.2s; margin-bottom: -2px;">
                <?php if ($is_edit) : ?>
                    ✏️ <?php echo esc_html(bizmart_text('Edit Product', 'Modifier Produit', 'تعديل المنتج')); ?>
                <?php else : ?>
                    🚀 <?php echo esc_html(bizmart_text('Product Creation', 'Création Produit', 'إنشاء منتج')); ?>
                <?php endif; ?>
            </a>
        </div>

        <div class="biz-stats-grid">
            <div class="biz-stat-card info" title="<?php echo esc_attr(bizmart_text('Total number of published products', 'Nombre total de produits publiés', 'العدد الإجمالي للمنتجات المنشورة')); ?>">
                <div class="biz-stat-value"><?php echo intval($total_products); ?></div>
                <div class="biz-stat-label"><?php echo esc_html(bizmart_text('Total Products', 'Total Produits', 'إجمالي المنتجات')); ?></div>
            </div>
            <div class="biz-stat-card neutral" title="<?php echo esc_attr(bizmart_text('Stock Value Details', 'Détails Valeur Stock', 'تفاصيل قيمة المخزون')); ?>">
                <div class="biz-stat-label">
                    <div style="font-weight: 700; text-transform: uppercase; font-size: 13px; margin-bottom: 6px; letter-spacing: 0.5px;"><?php echo esc_html(bizmart_text('Stock Value', 'Valeur du Stock', 'قيمة المخزون')); ?></div>
                    <div><?php echo esc_html(bizmart_text('Vente:', 'Vente :', 'البيع:')); ?> <strong><?php echo wc_price($stock_value); ?></strong></div>
                    <div><?php echo esc_html(bizmart_text('Achat:', 'Achat :', 'الشراء:')); ?> <strong><?php echo wc_price($stock_purchase_value); ?></strong></div>
                </div>
            </div>
            <div class="biz-stat-card warning" title="<?php echo esc_attr(bizmart_text('Total items currently in stock (published)', 'Total d\'articles actuellement en stock (publiés)', 'إجمالي العناصر المتوفرة حالياً (المنشورة)')); ?>">
                <div class="biz-stat-value"><?php echo number_format($total_stock, 0); ?></div>
                <div class="biz-stat-label"><?php echo esc_html(bizmart_text('Items in Stock', 'Articles en Stock', 'عناصر في المخزون')); ?></div>
            </div>
            <div class="biz-stat-card info">
                <div class="biz-stat-value"><?php echo intval($type_counts['variable']); ?></div>
                <div class="biz-stat-label"><?php echo esc_html(bizmart_text('Variable', 'Variables', 'متغير')); ?></div>
            </div>
        </div>

        <?php if ($current_view === 'list') : ?>
            <div class="biz-products-main" style="width: 100%;">
                <?php include plugin_dir_path(__FILE__) . 'products-list.php'; ?>
            </div>
        <?php elseif ($current_view === 'alerts') : ?>
            <div class="biz-products-main" style="width: 100%;">
                <?php
                // stock-alerts.php is a core feature
                $alerts_file = BIZMART_CORE_DIR . 'admin/stock-alerts.php';
                if (file_exists($alerts_file)) {
                    include $alerts_file;
                }
                ?>
            </div>
        <?php else : ?>

        <?php if ($is_edit) : ?>
            <div style="margin-bottom: 24px; padding: 15px 20px; background: #f0f9ff; border-radius: 12px; border-left: 4px solid #0ea5e9;">
                <h3 style="margin:0; color:#0369a1; font-size: 16px;">✏️ <?php echo sprintf(bizmart_text('Editing: %s', 'Modification de : %s', 'تعديل: %s'), '<strong>' . esc_html($edit_name) . '</strong>'); ?></h3>
            </div>
        <?php endif; ?>

        <!-- Original Product Creation Content Starts Here -->
        <div style="display: flex; gap: 30px;">
            <div class="biz-products-main">
                <div class="biz-card">
                    <h1 style="margin: 0 0 24px 0; color: #1f2937;">🚀 <?php echo esc_html(bizmart_text('Advanced Product Creation', 'Création Avancée de Produits', 'إنشاء منتج متقدم')); ?></h1>
                <div style="display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:30px;">
                    <p style="color: #6b7280; margin:0;"><?php echo esc_html(bizmart_text('Create complete products with all WooCommerce features', 'Créez des produits complets avec toutes les fonctionnalités WooCommerce', 'أنشئ منتجات كاملة بجميع ميزات WooCommerce')); ?></p>
                    <div>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline-block;margin:0;">
                            <?php wp_nonce_field('bizmart_export_products_nonce','bizmart_export_products_nonce_field'); ?>
                            <input type="hidden" name="action" value="bizmart_export_products">
                            <button type="submit" class="biz-btn biz-btn-secondary">📤 <?php echo esc_html(bizmart_text('Export data', 'Exporter Données', 'تصدير البيانات')); ?></button>
                        </form>
                    </div>
                </div>
                

                
                <!-- Tabs -->
                <?php if (false) : // Extracted to assets/products.js (enqueued on bizmart-products) ?>
                <script>
                (function(){
                    window.BizProducts = window.BizProducts || {};
                    if (typeof window.BizProducts.switchTab !== 'function') {
                        window.BizProducts.switchTab = function(tab) {
                            try {
                                if (!tab) return false;
                                var tabs = document.querySelectorAll('.biz-tabs .biz-tab');
                                for (var i = 0; i < tabs.length; i++) {
                                    tabs[i].classList.remove('active');
                                }
                                var panels = document.querySelectorAll('.biz-tab-content');
                                for (var j = 0; j < panels.length; j++) {
                                    panels[j].classList.remove('active');
                                }
                                var activeTab = document.querySelector('.biz-tabs .biz-tab[data-tab="' + tab + '"]');
                                if (activeTab) activeTab.classList.add('active');
                                var panel = document.getElementById('biz-tab-' + tab);
                                if (panel) panel.classList.add('active');
                            } catch (e) {}
                            return false;
                        };
                    }

                    function getBizmartConfig() {
                        var cfg = window.BizmartAnalytics || {};
                        return {
                            ajaxUrl: cfg.ajax_url || cfg.ajaxUrl || window.ajaxurl || '',
                            nonce: cfg.nonce || ''
                        };
                    }

                    function getSelectedValues(selectId) {
                        var el = document.getElementById(selectId);
                        if (!el) return [];
                        var out = [];
                        for (var i = 0; i < el.options.length; i++) {
                            if (el.options[i].selected) out.push(el.options[i].value);
                        }
                        return out;
                    }

                    function splitCsv(value) {
                        if (!value) return [];
                        return String(value)
                            .split(',')
                            .map(function(s){ return s.trim(); })
                            .filter(function(s){ return !!s; });
                    }

                    function fallbackCreateSimple(status, btnEl) {
                        var cfg = getBizmartConfig();
                        if (!cfg.ajaxUrl || !cfg.nonce) {
                            try { alert('Bizmart config is missing (ajax/nonce). Please refresh the page.'); } catch (e) {}
                            return false;
                        }

                        var name = (document.getElementById('biz-simple-name') || {}).value || '';
                        var sku = (document.getElementById('biz-simple-sku') || {}).value || '';
                        var regularPrice = (document.getElementById('biz-simple-regular-price') || {}).value || '';

                        if (!name.trim()) {
                            try { alert('Please enter a product name'); } catch (e1) {}
                            return false;
                        }
                        if (!sku.trim()) {
                            sku = String(name)
                                .toUpperCase()
                                .replace(/[^A-Z0-9]/g, '')
                                .substring(0, 12) || ('BIZ-' + Date.now());
                            try {
                                var skuEl = document.getElementById('biz-simple-sku');
                                if (skuEl) skuEl.value = sku;
                            } catch (e2) {}
                        }

                        
                        // Edit mode: include product ID so backend updates instead of creating a duplicate
                        var editIdEl = document.getElementById('bizmart-edit-product-id');
                        var editId = editIdEl ? parseInt(editIdEl.value || '0', 10) : 0;

var productData = {
                            id: editId || 0,
                            name: name,
                            sku: sku,
                            regular_price: regularPrice || '',
                            sale_price: ((document.getElementById('biz-simple-sale-price') || {}).value || ''),
                            cost_price: ((document.getElementById('biz-simple-cost-price') || {}).value || ''),
                            short_description: ((document.getElementById('biz-simple-short-description') || {}).value || ''),
                            description: ((document.getElementById('biz-simple-description') || {}).value || ''),
                            categories: getSelectedValues('biz-simple-categories'),
                            tags: splitCsv(((document.getElementById('biz-simple-tags') || {}).value || '')),
                            image_id: ((document.getElementById('biz-simple-image-id') || {}).value || 0),
                            gallery_ids: splitCsv(((document.getElementById('biz-simple-gallery-ids') || {}).value || '')),
                            manage_stock: (document.getElementById('biz-simple-manage-stock') || {}).checked ? 1 : 0,
                            stock_status: ((document.getElementById('biz-simple-stock-status') || {}).value || 'instock'),
                            stock_quantity: ((document.getElementById('biz-simple-stock-quantity') || {}).value || 0),
                            backorders: ((document.getElementById('biz-simple-backorders') || {}).value || 'no'),
                            sold_individually: ((document.getElementById('biz-simple-sold-individually') || {}).value || 'no') === 'yes' ? 1 : 0,
                            weight: ((document.getElementById('biz-simple-weight') || {}).value || ''),
                            length: ((document.getElementById('biz-simple-length') || {}).value || ''),
                            width: ((document.getElementById('biz-simple-width') || {}).value || ''),
                            height: ((document.getElementById('biz-simple-height') || {}).value || ''),
                            shipping_class: ((document.getElementById('biz-simple-shipping-class') || {}).value || ''),
                            virtual: (document.getElementById('biz-simple-virtual') || {}).checked ? 1 : 0,
                            cross_sell_ids: splitCsv(((document.getElementById('biz-simple-cross-sells') || {}).value || '')),
                            upsell_ids: splitCsv(((document.getElementById('biz-simple-upsells') || {}).value || '')),
                            purchase_note: ((document.getElementById('biz-simple-purchase-note') || {}).value || ''),
                            menu_order: ((document.getElementById('biz-simple-menu-order') || {}).value || 0),
                            status: status,
                            comment_status: ((document.getElementById('biz-simple-reviews') || {}).value || 'open')
                        };

                        var btn = btnEl || null;
                        if (!btn) {
                            // Best-effort fallback for older markup
                            var btnCreate = document.querySelector('button[onclick^="BizProducts.createSimpleProduct"]');
                            var btnDraft = document.querySelector('button[onclick^="BizProducts.saveProduct"]');
                            btn = status === 'draft' ? btnDraft : btnCreate;
                        }

                        var originalHtml = '';
                        if (btn) {
                            originalHtml = btn.innerHTML;
                            btn.disabled = true;
                            btn.innerHTML = (editId ? 'Updating...' : 'Creating...');
                        }

                        var body = new URLSearchParams();
                        body.set('action', 'bizmart_create_simple_product');
                        body.set('nonce', cfg.nonce);
                        body.set('data', JSON.stringify(productData));

                        fetch(cfg.ajaxUrl, {
                            method: 'POST',
                            credentials: 'same-origin',
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                            body: body.toString()
                        }).then(function(r){
                            return r.json();
                        }).then(function(resp){
                            if (btn) {
                                btn.disabled = false;
                                btn.innerHTML = originalHtml;
                            }
                            if (resp && resp.success) {
                                try { alert('Product created successfully!'); } catch (e2) {}
                                setTimeout(function(){ window.location.reload(); }, 1200);
                                return;
                            }
                            var msg = (resp && resp.data) ? resp.data : 'An error occurred';
                            try { alert('Error: ' + msg); } catch (e3) {}
                        }).catch(function(err){
                            if (btn) {
                                btn.disabled = false;
                                btn.innerHTML = originalHtml;
                            }
                            try { alert('Server connection error'); } catch (e4) {}
                            if (window && window.console) console.error(err);
                        });

                        return false;
                    }

                    function bootstrapCall(fnName, args, selfFn, fallbackFn, timeoutMs) {
                        var start = Date.now();
                        timeoutMs = typeof timeoutMs === 'number' ? timeoutMs : 6000;
                        (function tick(){
                            try {
                                var bp = window.BizProducts;
                                var target = bp && bp[fnName];
                                if (typeof target === 'function' && target !== selfFn) {
                                    return target.apply(bp, args || []);
                                }
                            } catch (e) {}
                            if (Date.now() - start > timeoutMs) {
                                if (typeof fallbackFn === 'function') {
                                    try { return fallbackFn(); } catch (e2) {}
                                }
                                try { alert('This action is still loading. Please wait a moment and try again.'); } catch (e3) {}
                                return;
                            }
                            setTimeout(tick, 75);
                        })();
                        return false;
                    }

                    function directOpenMediaUploader(inputId, previewId) {
                        try {
                            if (typeof wp === 'undefined' || !wp.media) {
                                alert('Media uploader is not available. Please refresh the page.');
                                return false;
                            }
                            var frame = wp.media({
                                title: 'Select an image',
                                button: { text: 'Use this image' },
                                multiple: false
                            });
                            frame.on('select', function() {
                                var attachment = frame.state().get('selection').first().toJSON();
                                try {
                                    var inputEl = document.getElementById(inputId);
                                    if (inputEl) inputEl.value = attachment.id;
                                    var imgEl = document.getElementById(previewId);
                                    if (imgEl) {
                                        imgEl.src = attachment.url;
                                        if (imgEl.classList) imgEl.classList.add('show');
                                    }
                                } catch (e2) {}
                            });
                            frame.open();
                        } catch (e) {}
                        return false;
                    }

                    function directOpenGalleryUploader(type) {
                        try {
                            if (typeof wp === 'undefined' || !wp.media) {
                                alert('Media uploader is not available. Please refresh the page.');
                                return false;
                            }

                            var frame = wp.media({
                                title: 'Select images',
                                button: { text: 'Add to gallery' },
                                multiple: true
                            });

                            frame.on('select', function() {
                                var attachments = frame.state().get('selection').toJSON();
                                var idsEl = document.getElementById('biz-' + type + '-gallery-ids');
                                var galleryEl = document.getElementById('biz-' + type + '-gallery');
                                var existing = [];
                                try {
                                    var raw = (idsEl && idsEl.value) ? String(idsEl.value) : '';
                                    existing = raw.split(',').map(function(v){ return String(v).trim(); }).filter(Boolean);
                                } catch (e1) { existing = []; }
                                attachments.forEach(function(att) {
                                    var idStr = String(att.id);
                                    if (existing.indexOf(idStr) === -1) existing.push(idStr);
                                    if (galleryEl && !document.getElementById('biz-' + type + '-gallery-item-' + att.id)) {
                                        var wrap = document.createElement('div');
                                        wrap.id = 'biz-' + type + '-gallery-item-' + att.id;
                                        wrap.style.position = 'relative';
                                        wrap.style.display = 'inline-block';

                                        var img = document.createElement('img');
                                        img.src = att.url;
                                        img.className = 'biz-gallery-image';

                                        var btn = document.createElement('button');
                                        btn.type = 'button';
                                        btn.className = 'biz-remove-image';
                                        btn.innerHTML = '&times;';
                                        btn.onclick = function() {
                                            return window.BizProducts.removeFromGallery(type, att.id);
                                        };

                                        wrap.appendChild(img);
                                        wrap.appendChild(btn);
                                        galleryEl.appendChild(wrap);
                                    }
                                });

                                if (idsEl) idsEl.value = existing.join(',');
                            });

                            frame.open();
                        } catch (e) {}
                        return false;
                    }

                    function directOpenFileUploader() {
                        try {
                            if (typeof wp === 'undefined' || !wp.media) {
                                alert('Media uploader is not available. Please refresh the page.');
                                return false;
                            }
                            var frame = wp.media({
                                title: 'Add files',
                                button: { text: 'Add' },
                                multiple: true
                            });
                            frame.open();
                        } catch (e) {}
                        return false;
                    }

                    // Create buttons (prevent dead clicks during progressive rendering)
                    window.BizProducts.createSimpleProduct = function bizBootstrap_createSimpleProduct(btnEl){
                        return bootstrapCall('createSimpleProduct', [btnEl], bizBootstrap_createSimpleProduct, function(){
                            return fallbackCreateSimple('publish', btnEl);
                        }, 250);
                    };
                    window.BizProducts.saveProduct = function bizBootstrap_saveProduct(type, status, btnEl){
                        if (type === 'simple') {
                            return bootstrapCall('saveProduct', [type, status, btnEl], bizBootstrap_saveProduct, function(){
                                return fallbackCreateSimple(status || 'draft', btnEl);
                            }, 250);
                        }
                        return bootstrapCall('saveProduct', [type, status, btnEl], bizBootstrap_saveProduct);
                    };
                    window.BizProducts.createVariableProduct = function bizBootstrap_createVariableProduct(btnEl){
                        return bootstrapCall('createVariableProduct', [btnEl], bizBootstrap_createVariableProduct);
                    };
                    window.BizProducts.createGroupedProduct = function bizBootstrap_createGroupedProduct(btnEl){
                        return bootstrapCall('createGroupedProduct', [btnEl], bizBootstrap_createGroupedProduct);
                    };
                    window.BizProducts.createExternalProduct = function bizBootstrap_createExternalProduct(btnEl){
                        return bootstrapCall('createExternalProduct', [btnEl], bizBootstrap_createExternalProduct);
                    };
                    window.BizProducts.createDigitalProduct = function bizBootstrap_createDigitalProduct(btnEl){
                        return bootstrapCall('createDigitalProduct', [btnEl], bizBootstrap_createDigitalProduct);
                    };

                    // Media & helper actions
                    window.BizProducts.openMediaUploader = function bizBootstrap_openMediaUploader(inputId, previewId){
                        return bootstrapCall('openMediaUploader', [inputId, previewId], bizBootstrap_openMediaUploader, function(){
                            return directOpenMediaUploader(inputId, previewId);
                        }, 250);
                    };
                    window.BizProducts.openGalleryUploader = function bizBootstrap_openGalleryUploader(type){
                        return bootstrapCall('openGalleryUploader', [type], bizBootstrap_openGalleryUploader, function(){
                            return directOpenGalleryUploader(type);
                        }, 250);
                    };
                    window.BizProducts.openFileUploader = function bizBootstrap_openFileUploader(){
                        return bootstrapCall('openFileUploader', [], bizBootstrap_openFileUploader, function(){
                            return directOpenFileUploader();
                        }, 250);
                    };
                    window.BizProducts.removeFromGallery = function bizBootstrap_removeFromGallery(type, imageId){
                        try {
                            var idsEl = document.getElementById('biz-' + type + '-gallery-ids');
                            if (idsEl) {
                                var parts = String(idsEl.value || '').split(',').map(function(v){ return String(v).trim(); }).filter(Boolean);
                                parts = parts.filter(function(v){ return v !== String(imageId); });
                                idsEl.value = parts.join(',');
                            }
                            var wrap = document.getElementById('biz-' + type + '-gallery-item-' + imageId);
                            if (wrap && wrap.parentNode) wrap.parentNode.removeChild(wrap);
                        } catch (e) {}
                        return false;
                    };
                    window.BizProducts.createCategory = function bizBootstrap_createCategory(type){
                        return bootstrapCall('createCategory', [type], bizBootstrap_createCategory);
                    };
                })();
                </script>
                <?php endif; ?>
                <div class="biz-tabs">
                    <div class="biz-tab active" data-tab="simple" onclick="BizProducts.switchTab('simple')">📦 <?php echo esc_html(bizmart_text('Simple', 'Simple', 'بسيط')); ?></div>
                    <div class="biz-tab" data-tab="variable" onclick="BizProducts.switchTab('variable')">🎯 <?php echo esc_html(bizmart_text('Variable', 'Variable', 'متغير')); ?></div>
                    <div class="biz-tab" data-tab="grouped" onclick="BizProducts.switchTab('grouped')">📦 <?php echo esc_html(bizmart_text('Grouped', 'Groupé', 'مجمّع')); ?></div>
                    <div class="biz-tab" data-tab="external" onclick="BizProducts.switchTab('external')">🔗 <?php echo esc_html(bizmart_text('External', 'Externe', 'خارجي')); ?></div>
                    <div class="biz-tab" data-tab="digital" onclick="BizProducts.switchTab('digital')">💾 <?php echo esc_html(bizmart_text('Digital', 'Digital', 'رقمي')); ?></div>
                </div>
                
                <!-- Simple Product Tab -->
                <div id="biz-tab-simple" class="biz-tab-content active">
                    <form id="biz-form-simple">
                        <!-- Basic Information -->
                        <div class="biz-section">
                            <h3 class="biz-section-title">📋 <?php echo esc_html(bizmart_text('Basic information', 'Informations de Base', 'المعلومات الأساسية')); ?></h3>
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label class="required"><?php echo esc_html(bizmart_text('Product name', 'Nom du produit', 'اسم المنتج')); ?></label>
                                    <input type="text" id="biz-simple-name" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Descriptive product name', 'Nom descriptif du produit', 'اسم وصفي للمنتج')); ?>" required>
                                </div>
                                <div class="biz-form-group">
                                    <label>SKU</label>
                                    <input type="text" id="biz-simple-sku" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Unique reference', 'Référence unique', 'مرجع فريد')); ?>">
                                    <small style="color: #6b7280; display: block; margin-top: 4px;"><?php echo esc_html(bizmart_text('Must be unique', 'Doit être unique', 'يجب أن يكون فريداً')); ?></small>
                                </div>
                            </div>
                            
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Regular price', 'Prix régulier', 'السعر العادي')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-simple-regular-price" class="biz-input biz-price-input" data-type="regular" placeholder="0.00">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Sale price', 'Prix promotionnel', 'سعر التخفيض')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-simple-sale-price" class="biz-input biz-price-input" data-type="sale" placeholder="0.00">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Cost price', "Prix d'achat (coût)", 'سعر التكلفة')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-simple-cost-price" class="biz-input biz-price-input" data-type="cost" placeholder="0.00">
                                </div>
                            </div>
                            
                            <!-- Profit Intelligence (Premium Feature) -->
                            <div class="biz-profit-intelligence" id="biz-simple-profit-intel" style="display:none; margin-top: 15px; padding: 15px; background: #f8fafc; border-radius: 12px; border: 1px solid #e2e8f0;">
                                <div style="display:flex; justify-content:space-between; align-items:center;">
                                    <div style="font-size:12px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.5px;">💰 <?php echo esc_html(bizmart_text('Profit Intelligence', 'Intelligence de Profit', 'تحليل الأرباح')); ?></div>
                                    <div id="biz-simple-profit-status" style="font-size:11px; font-weight:700; padding:2px 8px; border-radius:10px;"></div>
                                </div>
                                <div class="biz-form-grid-3" style="margin-top:10px;">
                                    <div class="biz-intel-stat">
                                        <label style="font-size:11px; color:#64748b; margin-bottom:4px; display:block;"><?php echo esc_html(bizmart_text('Profit', 'Bénéfice', 'الربح')); ?></label>
                                        <div id="biz-simple-profit-val" style="font-size:16px; font-weight:800; color:#1e293b;">-</div>
                                    </div>
                                    <div class="biz-intel-stat">
                                        <label style="font-size:11px; color:#64748b; margin-bottom:4px; display:block;"><?php echo esc_html(bizmart_text('Margin', 'Marge', 'الهامش')); ?> (%)</label>
                                        <div id="biz-simple-margin-val" style="font-size:16px; font-weight:800; color:#1e293b;">-</div>
                                    </div>
                                    <div class="biz-intel-stat">
                                        <label style="font-size:11px; color:#64748b; margin-bottom:4px; display:block;"><?php echo esc_html(bizmart_text('Markup', 'Majoration', 'نسبة الزيادة')); ?> (%)</label>
                                        <div id="biz-simple-markup-val" style="font-size:16px; font-weight:800; color:#1e293b;">-</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Short description', 'Description courte', 'وصف مختصر')); ?></label>
                                <textarea id="biz-simple-short-description" class="biz-textarea biz-textarea-small" placeholder="<?php echo esc_attr(bizmart_text('Short description shown in lists...', 'Description concise affichée dans les listes...', 'وصف موجز يظهر في القوائم...')); ?>"></textarea>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Full description', 'Description complète', 'الوصف الكامل')); ?></label>
                                <textarea id="biz-simple-description" class="biz-textarea" placeholder="<?php echo esc_attr(bizmart_text('Detailed product description...', 'Description détaillée du produit...', 'وصف تفصيلي للمنتج...')); ?>"></textarea>
                            </div>
                        </div>
                        
                        <!-- Categories & Tags -->
                        <div class="biz-section">
                            <h3 class="biz-section-title">🏷️ <?php echo esc_html(bizmart_text('Categories & tags', 'Catégories & Étiquettes', 'الفئات والعلامات')); ?></h3>
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Categories', 'Catégories', 'الفئات')); ?></label>
                                    <select id="biz-simple-categories" class="biz-multiselect" multiple>
                                        <?php foreach ($product_categories as $category): ?>
                                            <option value="<?php echo intval($category->term_id); ?>"><?php echo esc_html($category->name); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="biz-category-creator">
                                        <input type="text" id="biz-simple-new-category" placeholder="<?php echo esc_attr(bizmart_text('New category', 'Nouvelle catégorie', 'فئة جديدة')); ?>">
                                        <button type="button" onclick="BizProducts.createCategory('simple')">+ <?php echo esc_html(bizmart_text('Add', 'Ajouter', 'إضافة')); ?></button>
                                    </div>
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Tags', 'Étiquettes (Tags)', 'العلامات')); ?></label>
                                    <div class="biz-tag-input" id="biz-simple-tags-container">
                                        <input type="text" id="biz-simple-tags-input" placeholder="<?php echo esc_attr(bizmart_text('Add a tag, press Enter', 'Ajouter une étiquette, appuyez sur Entrée', 'أضف علامة، اضغط Enter')); ?>">
                                    </div>
                                    <input type="hidden" id="biz-simple-tags">
                                </div>
                            </div>
                        </div>
                        
                        <!-- Images -->
                        <div class="biz-section">
                            <h3 class="biz-section-title">🖼️ <?php echo esc_html(bizmart_text('Product images', 'Images du Produit', 'صور المنتج')); ?></h3>
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Main image', 'Image principale', 'الصورة الرئيسية')); ?></label>
                                    <div class="biz-image-upload-area" onclick="BizProducts.openMediaUploader('biz-simple-image-id', 'biz-simple-image-preview')">
                                        <div style="font-size: 48px; color: #9ca3af;">📷</div>
                                        <p style="margin: 10px 0 0 0; color: #6b7280;"><?php echo esc_html(bizmart_text('Click to upload', 'Cliquez pour télécharger', 'انقر للرفع')); ?></p>
                                        <small style="color: #9ca3af;"><?php echo esc_html(bizmart_text('Recommended: 600x600 pixels', 'Recommandé: 600x600 pixels', 'موصى به: 600×600 بكسل')); ?></small>
                                    </div>
                                    <input type="hidden" id="biz-simple-image-id">
                                    <img id="biz-simple-image-preview" class="biz-image-preview">
                                </div>
                                
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Image gallery', "Galerie d'images", 'معرض الصور')); ?></label>
                                    <div class="biz-image-upload-area" onclick="BizProducts.openGalleryUploader('simple')">
                                        <div style="font-size: 48px; color: #9ca3af;">🖼️</div>
                                        <p style="margin: 10px 0 0 0; color: #6b7280;"><?php echo esc_html(bizmart_text('Click to add', 'Cliquez pour ajouter', 'انقر للإضافة')); ?></p>
                                        <small style="color: #9ca3af;"><?php echo esc_html(bizmart_text('Add multiple images', 'Ajoutez plusieurs images', 'أضف صوراً متعددة')); ?></small>
                                    </div>
                                    <div class="biz-gallery-images" id="biz-simple-gallery"></div>
                                    <input type="hidden" id="biz-simple-gallery-ids">
                                </div>
                            </div>
                        </div>
                        
                        <!-- Inventory -->
                        <div class="biz-section">
                            <h3 class="biz-section-title">📦 <?php echo esc_html(bizmart_text('Inventory', 'Gestion du Stock', 'المخزون')); ?></h3>
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label style="display: flex; align-items: center; cursor: pointer;">
                                        <span class="biz-switch">
                                            <input type="checkbox" id="biz-simple-manage-stock" <?php if (!empty($edit_data) && ($edit_data['type'] ?? '') === 'simple' && !empty($edit_data['manage_stock'])) echo 'checked'; ?>>
<span class="biz-slider"></span>
                                        </span>
                                        <?php echo esc_html(bizmart_text('Manage stock', 'Gérer le stock', 'إدارة المخزون')); ?>
                                    </label>
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Stock status', 'Statut du stock', 'حالة المخزون')); ?></label>
                                    <select id="biz-simple-stock-status" class="biz-select">
                                        <option value="instock" <?php if (!empty($edit_data) && ($edit_data['type'] ?? '')==='simple') selected(($edit_data['stock_status'] ?? ''), 'instock'); ?>><?php echo esc_html(bizmart_text('In stock', 'En stock', 'متوفر')); ?></option>
                                        <option value="outofstock" <?php if (!empty($edit_data) && ($edit_data['type'] ?? '')==='simple') selected(($edit_data['stock_status'] ?? ''), 'outofstock'); ?>><?php echo esc_html(bizmart_text('Out of stock', 'Rupture de stock', 'غير متوفر')); ?></option>
                                        <option value="onbackorder" <?php if (!empty($edit_data) && ($edit_data['type'] ?? '')==='simple') selected(($edit_data['stock_status'] ?? ''), 'onbackorder'); ?>><?php echo esc_html(bizmart_text('On backorder', 'Sur commande', 'طلب مسبق')); ?></option>
                                    </select>
                                </div>
                                <div class="biz-form-group" id="biz-simple-stock-quantity-group" style="display: <?php echo (!empty($edit_data) && ($edit_data['type'] ?? '')==='simple' && !empty($edit_data['manage_stock'])) ? 'block' : 'none'; ?>;">
                                    <label><?php echo esc_html(bizmart_text('Stock quantity', 'Quantité en stock', 'كمية المخزون')); ?></label>
                                    <input type="number" min="0" step="1" inputmode="numeric" pattern="[0-9]*" id="biz-simple-stock-quantity" class="biz-input" placeholder="0" value="<?php echo (!empty($edit_data) && ($edit_data['type'] ?? '')==='simple' && isset($edit_data['stock_quantity'])) ? esc_attr($edit_data['stock_quantity']) : ''; ?>">
                                </div>
                            </div>
                            
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Purchase limit', 'Limite par commande', 'حد الشراء')); ?></label>
                                    <input type="number" min="0" id="biz-simple-purchase-limit" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Unlimited', 'Illimité', 'غير محدود')); ?>">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Allow backorders?', 'Permettre les précommandes?', 'السماح بالطلب المسبق؟')); ?></label>
                                    <select id="biz-simple-backorders" class="biz-select">
                                        <option value="no"><?php echo esc_html(bizmart_text('No', 'Non', 'لا')); ?></option>
                                        <option value="notify"><?php echo esc_html(bizmart_text('Allow, notify customer', 'Autoriser, notifier', 'السماح مع إشعار العميل')); ?></option>
                                        <option value="yes"><?php echo esc_html(bizmart_text('Allow', 'Autoriser', 'السماح')); ?></option>
                                    </select>
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Sold individually?', 'Vendu individuellement?', 'يُباع فردياً؟')); ?></label>
                                    <select id="biz-simple-sold-individually" class="biz-select">
                                        <option value="no"><?php echo esc_html(bizmart_text('No', 'Non', 'لا')); ?></option>
                                        <option value="yes"><?php echo esc_html(bizmart_text('Yes', 'Oui', 'نعم')); ?></option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Virtual Product Toggle -->
                        <div class="biz-section">
                            <div class="biz-form-group">
                                <label style="display: flex; align-items: center; cursor: pointer;">
                                    <span class="biz-switch">
                                        <input type="checkbox" id="biz-simple-virtual" onchange="BizProducts.toggleShippingSection(this.checked)">
                                        <span class="biz-slider"></span>
                                    </span>
                                    <?php echo esc_html(bizmart_text('Virtual product (no shipping)', 'Produit virtuel (pas de livraison)', 'منتج افتراضي (بدون شحن)')); ?>
                                </label>
                            </div>
                        </div>
                        
                        <!-- Shipping Section (Hidden by default for virtual products) -->
                        <div class="biz-shipping-section" id="biz-simple-shipping-section">
                            <h3 class="biz-section-title">🚚 <?php echo esc_html(bizmart_text('Shipping', 'Livraison', 'الشحن')); ?></h3>
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Weight (kg)', 'Poids (kg)', 'الوزن (كغ)')); ?></label>
                                    <input type="number" step="0.001" min="0" id="biz-simple-weight" class="biz-input" placeholder="0.00">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Length (cm)', 'Longueur (cm)', 'الطول (سم)')); ?></label>
                                    <input type="number" step="0.1" min="0" id="biz-simple-length" class="biz-input" placeholder="0.0">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Width (cm)', 'Largeur (cm)', 'العرض (سم)')); ?></label>
                                    <input type="number" step="0.1" min="0" id="biz-simple-width" class="biz-input" placeholder="0.0">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Height (cm)', 'Hauteur (cm)', 'الارتفاع (سم)')); ?></label>
                                    <input type="number" step="0.1" min="0" id="biz-simple-height" class="biz-input" placeholder="0.0">
                                </div>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Shipping class', 'Classe de livraison', 'فئة الشحن')); ?></label>
                                <select id="biz-simple-shipping-class" class="biz-select">
                                    <option value=""><?php echo esc_html(bizmart_text('Default', 'Par défaut', 'افتراضي')); ?></option>
                                    <?php foreach ($shipping_classes as $class): ?>
                                        <option value="<?php echo esc_attr($class->term_id); ?>"><?php echo esc_html($class->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <!-- Linked Products -->
                        <div class="biz-section">
                            <h3 class="biz-section-title">🔗 <?php echo esc_html(bizmart_text('Linked products', 'Produits Liés', 'منتجات مرتبطة')); ?></h3>
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Cross-sells', 'Ventes croisées (Cross-sells)', 'بيع متقاطع')); ?></label>
                                    <input type="text" id="biz-simple-cross-sells" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('SKUs separated by commas', 'SKUs séparés par des virgules', 'أرقام SKU مفصولة بفواصل')); ?>">
                                    <small style="color: #6b7280;"><?php echo esc_html(bizmart_text('Frequently bought together', 'Produits fréquemment achetés ensemble', 'يُشترى عادة معاً')); ?></small>
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Upsells', 'Ventes incitatives (Upsells)', 'منتجات مقترحة')); ?></label>
                                    <input type="text" id="biz-simple-upsells" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('SKUs separated by commas', 'SKUs séparés par des virgules', 'أرقام SKU مفصولة بفواصل')); ?>">
                                    <small style="color: #6b7280;"><?php echo esc_html(bizmart_text('Similar higher-quality products', 'Produits similaires de meilleure qualité', 'منتجات مشابهة بجودة أعلى')); ?></small>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Advanced Settings -->
                        <div class="biz-section">
                            <div class="biz-toggle-section" onclick="BizProducts.toggleSection('biz-simple-advanced')">
                                <h3 class="biz-section-title">⚙️ <?php echo esc_html(bizmart_text('Advanced settings', 'Paramètres Avancés', 'إعدادات متقدمة')); ?></h3>
                                <span>▼</span>
                            </div>
                            <div id="biz-simple-advanced" class="biz-collapsible-content">
                                <div class="biz-form-grid-2">
                                    <div class="biz-form-group">
                                        <label><?php echo esc_html(bizmart_text('Purchase note', "Note d'achat", 'ملاحظة الشراء')); ?></label>
                                        <textarea id="biz-simple-purchase-note" class="biz-textarea biz-textarea-small" placeholder="<?php echo esc_attr(bizmart_text('Message after purchase...', 'Message après achat...', 'رسالة بعد الشراء...')); ?>"></textarea>
                                    </div>
                                    <div class="biz-form-group">
                                        <label><?php echo esc_html(bizmart_text('Menu order', 'Ordre de menu', 'ترتيب القائمة')); ?></label>
                                        <input type="number" id="biz-simple-menu-order" class="biz-input" placeholder="0">
                                    </div>
                                </div>
                                
                                <div class="biz-form-grid-2">
                                    <div class="biz-form-group">
                                        <label><?php echo esc_html(bizmart_text('Publish date', 'Date de publication', 'تاريخ النشر')); ?></label>
                                        <input type="datetime-local" id="biz-simple-publish-date" class="biz-input biz-date-picker">
                                    </div>
                                    <div class="biz-form-group">
                                        <label><?php echo esc_html(bizmart_text('Product status', 'État du produit', 'حالة المنتج')); ?></label>
                                        <select id="biz-simple-status" class="biz-select">
                                            <option value="publish"><?php echo esc_html(bizmart_text('Published', 'Publié', 'منشور')); ?></option>
                                            <option value="draft"><?php echo esc_html(bizmart_text('Draft', 'Brouillon', 'مسودة')); ?></option>
                                            <option value="private"><?php echo esc_html(bizmart_text('Private', 'Privé', 'خاص')); ?></option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Reviews', 'Commentaires', 'التقييمات')); ?></label>
                                    <select id="biz-simple-reviews" class="biz-select">
                                        <option value="open"><?php echo esc_html(bizmart_text('Enable', 'Autoriser', 'تفعيل')); ?></option>
                                        <option value="closed"><?php echo esc_html(bizmart_text('Disable', 'Fermer', 'تعطيل')); ?></option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Submit -->
                        <div style="display: flex; gap: 12px; margin-top: 30px;">
                            <button type="button" class="biz-btn biz-btn-success" onclick="BizProducts.createSimpleProduct(this)">
                                <span style="font-size: 18px;">✅</span>
                                <?php echo esc_html((!empty($edit_data) && ($edit_data['type'] ?? '')==='simple') ? bizmart_text('Update product', 'Mettre à jour le produit', 'تحديث المنتج') : bizmart_text('Create product', 'Créer le produit', 'إنشاء المنتج')); ?>
                            </button>
                            <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.resetForm('simple')">
                                ↻ <?php echo esc_html(bizmart_text('Reset', 'Réinitialiser', 'إعادة تعيين')); ?>
                            </button>
                            <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.saveProduct('simple','draft', this)">
                                💾 <?php echo esc_html(bizmart_text('Save draft', 'Enregistrer brouillon', 'حفظ كمسودة')); ?>
                            </button>
                        </div>
                    </form>
                </div>
                
                <!-- Variable Product Tab -->
                <div id="biz-tab-variable" class="biz-tab-content">
                    <form id="biz-form-variable">
                        <!-- Basic Information -->
                        <div class="biz-section">
                            <h3 class="biz-section-title">📋 <?php echo esc_html(bizmart_text('Basic information', 'Informations de Base', 'المعلومات الأساسية')); ?></h3>
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label class="required"><?php echo esc_html(bizmart_text('Product name', 'Nom du produit', 'اسم المنتج')); ?></label>
                                    <input type="text" id="biz-variable-name" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Product line name', 'Nom de la gamme', 'اسم خط المنتج')); ?>" required>
                                </div>
                                <div class="biz-form-group">
                                    <label class="required"><?php echo esc_html(bizmart_text('Parent SKU', 'SKU parent', 'SKU الرئيسي')); ?></label>
                                    <input type="text" id="biz-variable-sku" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Line SKU', 'SKU de la gamme', 'SKU الخط')); ?>" required>
                                </div>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Short description', 'Description courte', 'وصف مختصر')); ?></label>
                                <textarea id="biz-variable-short-description" class="biz-textarea biz-textarea-small" placeholder="<?php echo esc_attr(bizmart_text('Short description...', 'Description concise...', 'وصف مختصر...')); ?>"></textarea>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Full description', 'Description complète', 'الوصف الكامل')); ?></label>
                                <textarea id="biz-variable-description" class="biz-textarea" placeholder="<?php echo esc_attr(bizmart_text('Detailed description...', 'Description détaillée...', 'وصف تفصيلي...')); ?>"></textarea>
                            </div>
                        </div>
                        
                        <!-- Categories & Tags -->
                        <div class="biz-section">
                            <h3 class="biz-section-title">🏷️ <?php echo esc_html(bizmart_text('Categories & tags', 'Catégories & Étiquettes', 'الفئات والعلامات')); ?></h3>
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Categories', 'Catégories', 'الفئات')); ?></label>
                                    <select id="biz-variable-categories" class="biz-multiselect" multiple>
                                        <?php foreach ($product_categories as $category): ?>
                                            <option value="<?php echo intval($category->term_id); ?>"><?php echo esc_html($category->name); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="biz-category-creator">
                                        <input type="text" id="biz-variable-new-category" placeholder="<?php echo esc_attr(bizmart_text('New category', 'Nouvelle catégorie', 'فئة جديدة')); ?>">
                                        <button type="button" onclick="BizProducts.createCategory('variable')">+ <?php echo esc_html(bizmart_text('Add', 'Ajouter', 'إضافة')); ?></button>
                                    </div>
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Tags', 'Étiquettes (Tags)', 'العلامات')); ?></label>
                                    <div class="biz-tag-input" id="biz-variable-tags-container">
                                        <input type="text" id="biz-variable-tags-input" placeholder="<?php echo esc_attr(bizmart_text('Add a tag, press Enter', 'Ajouter une étiquette, appuyez sur Entrée', 'أضف علامة، اضغط Enter')); ?>">
                                    </div>
                                    <input type="hidden" id="biz-variable-tags">
                                </div>
                            </div>
                        </div>
                        
                        <!-- Attributes -->
                        <div class="biz-section">
                            <h3 class="biz-section-title">🎨 <?php echo esc_html(bizmart_text('Attributes', 'Attributs', 'السمات')); ?></h3>
                            <div id="biz-variable-attributes">
                                <?php
                                // Get all product attributes
                                $attribute_taxonomies = wc_get_attribute_taxonomies();
                                ?>
                                <div class="biz-attribute-row" data-id="1">
                                    <div class="biz-form-grid-2">
                                        <div class="biz-form-group">
                                            <label><?php echo esc_html(bizmart_text('Select an existing attribute', 'Sélectionner un attribut existant', 'اختر سمة موجودة')); ?></label>
                                            <select class="biz-select existing-attribute-select" onchange="BizProducts.onExistingAttributeSelect(this)">
                                                <option value="">-- <?php echo esc_html(bizmart_text('Choose an existing attribute', 'Choisir un attribut existant', 'اختر سمة موجودة')); ?> --</option>
                                                <?php foreach ($attribute_taxonomies as $tax): ?>
                                                    <option value="<?php echo esc_attr($tax->attribute_name); ?>" data-label="<?php echo esc_attr($tax->attribute_label); ?>">
                                                        <?php echo esc_html($tax->attribute_label); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                                <option value="new">+ <?php echo esc_html(bizmart_text('Create a new attribute', 'Créer un nouvel attribut', 'إنشاء سمة جديدة')); ?></option>
                                            </select>
                                        </div>
                                        <div class="biz-form-group">
                                            <label><?php echo esc_html(bizmart_text('Or create a new attribute', 'Ou créer un nouvel attribut', 'أو أنشئ سمة جديدة')); ?></label>
                                            <input type="text" class="biz-input attribute-name" placeholder="<?php echo esc_attr(bizmart_text('Attribute name (e.g. Color, Size)', "Nom de l'attribut (ex: Couleur, Taille)", 'اسم السمة (مثال: اللون، المقاس)')); ?>" style="display: none;">
                                        </div>
                                        <div class="biz-form-group">
                                            <label><?php echo esc_html(bizmart_text('Attribute values', "Valeurs de l'attribut", 'قيم السمة')); ?></label>
                                            <div class="biz-tag-input" id="biz-attribute-values-1">
                                                <input type="text" class="biz-attribute-values-input" placeholder="<?php echo esc_attr(bizmart_text('Add a value, press Enter', 'Ajouter une valeur, appuyez sur Entrée', 'أضف قيمة، اضغط Enter')); ?>">
                                            </div>
                                            <input type="hidden" class="attribute-values" id="biz-attribute-values-hidden-1">
                                            <small style="color: #6b7280;"><?php echo esc_html(bizmart_text('Separate values with commas or add them one by one', 'Séparer les valeurs par des virgules ou ajoutez-les une par une', 'افصل القيم بفواصل أو أضفها واحدة تلو الأخرى')); ?></small>
                                        </div>
                                    </div>
                                    <div class="biz-form-grid-3">
                                        <div class="biz-form-group">
                                            <label style="display: flex; align-items: center; cursor: pointer;">
                                                <span class="biz-switch">
                                                    <input type="checkbox" class="attribute-visible" checked>
                                                    <span class="biz-slider"></span>
                                                </span>
                                                <?php echo esc_html(bizmart_text('Visible on product page', 'Visible sur la page produit', 'مرئي على صفحة المنتج')); ?>
                                            </label>
                                        </div>
                                        <div class="biz-form-group">
                                            <label style="display: flex; align-items: center; cursor: pointer;">
                                                <span class="biz-switch">
                                                    <input type="checkbox" class="attribute-variation" checked>
                                                    <span class="biz-slider"></span>
                                                </span>
                                                <?php echo esc_html(bizmart_text('Used for variations', 'Utilisé pour les variations', 'مستخدم للتنويعات')); ?>
                                            </label>
                                        </div>
                                        <button type="button" class="biz-btn" onclick="BizProducts.addAttribute()">+ <?php echo esc_html(bizmart_text('Add another attribute', 'Ajouter un autre attribut', 'إضافة سمة أخرى')); ?></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Variations Section -->
                        <div class="biz-section">
                            <div class="biz-toggle-section" onclick="BizProducts.toggleSection('biz-variations-section')">
                                <h3 class="biz-section-title">🎯 <?php echo esc_html(bizmart_text('Variations', 'Variations', 'التنويعات')); ?></h3>
                                <span>▼</span>
                            </div>
                            <div id="biz-variations-section" class="biz-collapsible-content">
                                <div style="margin-bottom: 20px;">
                                    <button type="button" class="biz-btn" onclick="BizProducts.generateVariations()">
                                        <span style="font-size: 18px;">⚡</span>
                                        <?php echo esc_html(bizmart_text('Generate automatically', 'Générer automatiquement', 'إنشاء تلقائي')); ?>
                                    </button>
                                    <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.addVariation()">
                                        <span style="font-size: 18px;">+</span>
                                        <?php echo esc_html(bizmart_text('Add manually', 'Ajouter manuellement', 'إضافة يدوياً')); ?>
                                    </button>
                                </div>
                                
                                <div id="biz-variations-container">
                                    <!-- Variations will be added here -->
                                </div>
                            </div>
                        </div>
                        
                        <!-- Images -->
                        <div class="biz-section">
                            <h3 class="biz-section-title">🖼️ <?php echo esc_html(bizmart_text('Product images', 'Images du Produit', 'صور المنتج')); ?></h3>
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Main image', 'Image principale', 'الصورة الرئيسية')); ?></label>
                                <div class="biz-image-upload-area" onclick="BizProducts.openMediaUploader('biz-variable-image-id', 'biz-variable-image-preview')">
                                    <div style="font-size: 48px; color: #9ca3af;">📷</div>
                                    <p style="margin: 10px 0 0 0; color: #6b7280;"><?php echo esc_html(bizmart_text('Click to upload', 'Cliquez pour télécharger', 'انقر للرفع')); ?></p>
                                </div>
                                <input type="hidden" id="biz-variable-image-id">
                                <img id="biz-variable-image-preview" class="biz-image-preview">
                            </div>
                        </div>
                        
                        <!-- Pricing -->
                        <div class="biz-section">
                            <h3 class="biz-section-title">💰 <?php echo esc_html(bizmart_text('Base pricing', 'Prix de Base', 'التسعير الأساسي')); ?></h3>
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Base regular price', 'Prix régulier de base', 'السعر العادي الأساسي')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-variable-base-regular" class="biz-input" placeholder="0.00">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Base sale price', 'Prix promotionnel de base', 'سعر التخفيض الأساسي')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-variable-base-sale" class="biz-input" placeholder="0.00">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Base cost price', "Prix d'achat de base", 'سعر التكلفة الأساسي')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-variable-base-cost" class="biz-input" placeholder="0.00">
                                </div>
                            </div>
                        </div>
                        
                        <!-- Submit -->
                        <div style="display: flex; gap: 12px; margin-top: 30px;">
                            <button type="button" class="biz-btn biz-btn-success" onclick="BizProducts.createVariableProduct(this)">
                                <span style="font-size: 18px;">🎯</span>
                                <?php echo esc_html(bizmart_text('Create variable product', 'Créer produit variable', 'إنشاء منتج متغير')); ?>
                            </button>
                            <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.resetForm('variable')">
                                ↻ <?php echo esc_html(bizmart_text('Reset', 'Réinitialiser', 'إعادة تعيين')); ?>
                            </button>
                        </div>
                    </form>
                </div>
                
                <!-- Grouped Product Tab -->
                <div id="biz-tab-grouped" class="biz-tab-content">
                    <form id="biz-form-grouped">
                        <div class="biz-section">
                            <h3 class="biz-section-title">📦 <?php echo esc_html(bizmart_text('Grouped product', 'Produit Groupé', 'منتج مجمّع')); ?></h3>
                            <p style="color: #6b7280; margin-bottom: 20px;"><?php echo esc_html(bizmart_text('Create a grouped product that contains multiple simple products', 'Créez un produit groupé qui contient plusieurs produits simples', 'أنشئ منتجاً مجمّعاً يحتوي على عدة منتجات بسيطة')); ?></p>
                            
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label class="required"><?php echo esc_html(bizmart_text('Group name', 'Nom du groupe', 'اسم المجموعة')); ?></label>
                                    <input type="text" id="biz-grouped-name" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Bundle/kit name', 'Nom du pack/kit', 'اسم الحزمة/الطقم')); ?>" required>
                                </div>
                                <div class="biz-form-group">
                                    <label class="required"><?php echo esc_html(bizmart_text('Group SKU', 'SKU du groupe', 'SKU المجموعة')); ?></label>
                                    <input type="text" id="biz-grouped-sku" class="biz-input" placeholder="SKU-GROUPE" required>
                                </div>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Description', 'Description', 'الوصف')); ?></label>
                                <textarea id="biz-grouped-description" class="biz-textarea" placeholder="<?php echo esc_attr(bizmart_text('Bundle description...', 'Description du pack...', 'وصف الحزمة...')); ?>"></textarea>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Products to include', 'Produits à inclure', 'المنتجات المطلوب تضمينها')); ?></label>
                                <select id="biz-grouped-products" class="biz-multiselect" multiple>
                                    <?php foreach ($simple_products as $product): ?>
                                        <option value="<?php echo esc_attr($product->get_id()); ?>">
                                            <?php echo esc_html($product->get_name()); ?> (<?php echo esc_html($product->get_sku()); ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <small style="color: #6b7280;"><?php echo esc_html(bizmart_text('Select the simple products to include in this group', 'Sélectionnez les produits simples à inclure dans ce groupe', 'اختر المنتجات البسيطة لتضمينها في المجموعة')); ?></small>
                            </div>
                            
                            <!-- Categories -->
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Categories', 'Catégories', 'الفئات')); ?></label>
                                <select id="biz-grouped-categories" class="biz-multiselect" multiple>
                                    <?php foreach ($product_categories as $category): ?>
                                        <option value="<?php echo intval($category->term_id); ?>"><?php echo esc_html($category->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <!-- Image -->
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Group image', 'Image du groupe', 'صورة المجموعة')); ?></label>
                                <div class="biz-image-upload-area" onclick="BizProducts.openMediaUploader('biz-grouped-image-id', 'biz-grouped-image-preview')">
                                    <div style="font-size: 48px; color: #9ca3af;">📷</div>
                                    <p style="margin: 10px 0 0 0; color: #6b7280;"><?php echo esc_html(bizmart_text('Click to upload', 'Cliquez pour télécharger', 'انقر للرفع')); ?></p>
                                </div>
                                <input type="hidden" id="biz-grouped-image-id">
                                <img id="biz-grouped-image-preview" class="biz-image-preview">
                            </div>
                            
                            <div style="display: flex; gap: 12px; margin-top: 30px;">
                                <button type="button" class="biz-btn biz-btn-success" onclick="BizProducts.createGroupedProduct(this)">
                                    <span style="font-size: 18px;">📦</span>
                                    <?php echo esc_html(bizmart_text('Create grouped product', 'Créer produit groupé', 'إنشاء منتج مجمّع')); ?>
                                </button>
                                <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.resetForm('grouped')">
                                    ↻ <?php echo esc_html(bizmart_text('Reset', 'Réinitialiser', 'إعادة تعيين')); ?>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
                
                <!-- External/Affiliate Product Tab -->
                <div id="biz-tab-external" class="biz-tab-content">
                    <form id="biz-form-external">
                        <div class="biz-section">
                            <h3 class="biz-section-title">🔗 <?php echo esc_html(bizmart_text('External/Affiliate product', 'Produit Externe/Affilié', 'منتج خارجي/تابع')); ?></h3>
                            <p style="color: #6b7280; margin-bottom: 20px;"><?php echo esc_html(bizmart_text('Product sold on another site (Amazon, etc.)', 'Produit vendu sur un autre site (Amazon, etc.)', 'منتج يُباع على موقع آخر (أمازون، إلخ.)')); ?></p>
                            
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label class="required"><?php echo esc_html(bizmart_text('Product name', 'Nom du produit', 'اسم المنتج')); ?></label>
                                    <input type="text" id="biz-external-name" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Product name', 'Nom du produit', 'اسم المنتج')); ?>" required>
                                </div>
                                <div class="biz-form-group">
                                    <label class="required"><?php echo esc_html(bizmart_text('SKU', 'SKU', 'SKU')); ?></label>
                                    <input type="text" id="biz-external-sku" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Reference', 'Référence', 'المرجع')); ?>" required>
                                </div>
                            </div>
                            
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label class="required"><?php echo esc_html(bizmart_text('Product URL', 'URL du produit', 'رابط المنتج')); ?></label>
                                    <input type="url" id="biz-external-url" class="biz-input" placeholder="https://" required>
                                </div>
                                <div class="biz-form-group">
                                    <label class="required"><?php echo esc_html(bizmart_text('Button text', 'Bouton texte', 'نص الزر')); ?></label>
                                    <input type="text" id="biz-external-button" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('e.g. Buy on Amazon', 'ex: Acheter sur Amazon', 'مثال: اشترِ من أمازون')); ?>" value="<?php echo esc_attr(bizmart_text('Buy now', 'Acheter maintenant', 'اشترِ الآن')); ?>" required>
                                </div>
                            </div>
                            
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Price', 'Prix', 'السعر')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-external-price" class="biz-input" placeholder="0.00">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Sale price', 'Prix promotionnel', 'سعر التخفيض')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-external-sale-price" class="biz-input" placeholder="0.00">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Cost price', "Prix d'achat", 'سعر التكلفة')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-external-cost-price" class="biz-input" placeholder="0.00">
                                </div>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Categories', 'Catégories', 'الفئات')); ?></label>
                                <select id="biz-external-categories" class="biz-multiselect" multiple>
                                    <?php foreach ($product_categories as $category): ?>
                                        <option value="<?php echo intval($category->term_id); ?>"><?php echo esc_html($category->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Description', 'Description', 'الوصف')); ?></label>
                                <textarea id="biz-external-description" class="biz-textarea" placeholder="<?php echo esc_attr(bizmart_text('Product description...', 'Description du produit...', 'وصف المنتج...')); ?>"></textarea>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Product image', 'Image du produit', 'صورة المنتج')); ?></label>
                                <div class="biz-image-upload-area" onclick="BizProducts.openMediaUploader('biz-external-image-id', 'biz-external-image-preview')">
                                    <div style="font-size: 48px; color: #9ca3af;">📷</div>
                                    <p style="margin: 10px 0 0 0; color: #6b7280;"><?php echo esc_html(bizmart_text('Click to upload', 'Cliquez pour télécharger', 'انقر للرفع')); ?></p>
                                </div>
                                <input type="hidden" id="biz-external-image-id">
                                <img id="biz-external-image-preview" class="biz-image-preview">
                            </div>
                            
                            <div style="display: flex; gap: 12px; margin-top: 30px;">
                                <button type="button" class="biz-btn biz-btn-success" onclick="BizProducts.createExternalProduct(this)">
                                    <span style="font-size: 18px;">🔗</span>
                                    <?php echo esc_html(bizmart_text('Create external product', 'Créer produit externe', 'إنشاء منتج خارجي')); ?>
                                </button>
                                <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.resetForm('external')">
                                    ↻ <?php echo esc_html(bizmart_text('Reset', 'Réinitialiser', 'إعادة تعيين')); ?>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
                
                <!-- Digital Product Tab -->
                <div id="biz-tab-digital" class="biz-tab-content">
                    <form id="biz-form-digital">
                        <div class="biz-section">
                            <h3 class="biz-section-title">💾 <?php echo esc_html(bizmart_text('Digital/Downloadable product', 'Produit Digital/Téléchargeable', 'منتج رقمي/قابل للتحميل')); ?></h3>
                            <p style="color: #6b7280; margin-bottom: 20px;"><?php echo esc_html(bizmart_text('Virtual products with downloadable files', 'Produits virtuels avec fichiers téléchargeables', 'منتجات افتراضية مع ملفات قابلة للتحميل')); ?></p>
                            
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label class="required"><?php echo esc_html(bizmart_text('Product name', 'Nom du produit', 'اسم المنتج')); ?></label>
                                    <input type="text" id="biz-digital-name" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('File/eBook name', 'Nom du fichier/ebook', 'اسم الملف/الكتاب الإلكتروني')); ?>" required>
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('SKU', 'SKU', 'SKU')); ?></label>
                                    <input type="text" id="biz-digital-sku" class="biz-input" placeholder="DIGITAL-">
                                </div>
                            </div>
                            
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Price', 'Prix', 'السعر')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-digital-price" class="biz-input" placeholder="0.00">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Sale price', 'Prix promotionnel', 'سعر التخفيض')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-digital-sale-price" class="biz-input" placeholder="0.00">
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Cost price', "Prix d'achat", 'سعر التكلفة')); ?></label>
                                    <input type="number" step="0.01" min="0" id="biz-digital-cost-price" class="biz-input" placeholder="0.00">
                                </div>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Downloadable files', 'Fichiers téléchargeables', 'ملفات قابلة للتحميل')); ?></label>
                                <div class="biz-image-upload-area" onclick="BizProducts.openFileUploader()">
                                    <div style="font-size: 48px; color: #9ca3af;">📎</div>
                                    <p style="margin: 10px 0 0 0; color: #6b7280;"><?php echo esc_html(bizmart_text('Click to add files', 'Cliquez pour ajouter des fichiers', 'انقر لإضافة ملفات')); ?></p>
                                    <small style="color: #9ca3af;">PDF, ZIP, MP3, etc.</small>
                                </div>
                                <div id="biz-digital-files-list" class="biz-file-list"></div>
                                <input type="hidden" id="biz-digital-files">
                            </div>
                            
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Download limit', 'Limite de téléchargement', 'حد التحميل')); ?></label>
                                    <input type="number" min="0" id="biz-digital-download-limit" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Unlimited', 'Illimité', 'غير محدود')); ?>">
                                    <small style="color: #6b7280;"><?php echo esc_html(bizmart_text('Max downloads per customer', 'Nombre max de téléchargements par client', 'أقصى عدد تحميلات لكل عميل')); ?></small>
                                </div>
                                <div class="biz-form-group">
                                    <label><?php echo esc_html(bizmart_text('Expiry (days)', 'Expiration (jours)', 'الانتهاء (أيام)')); ?></label>
                                    <input type="number" min="0" id="biz-digital-download-expiry" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Never', 'Jamais', 'أبداً')); ?>">
                                    <small style="color: #6b7280;"><?php echo esc_html(bizmart_text('Days until link expires', 'Jours avant expiration du lien', 'أيام قبل انتهاء الرابط')); ?></small>
                                </div>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Categories', 'Catégories', 'الفئات')); ?></label>
                                <select id="biz-digital-categories" class="biz-multiselect" multiple>
                                    <?php foreach ($product_categories as $category): ?>
                                        <option value="<?php echo intval($category->term_id); ?>"><?php echo esc_html($category->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Description', 'Description', 'الوصف')); ?></label>
                                <textarea id="biz-digital-description" class="biz-textarea" placeholder="<?php echo esc_attr(bizmart_text('Digital product description...', 'Description du produit digital...', 'وصف المنتج الرقمي...')); ?>"></textarea>
                            </div>
                            
                            <div class="biz-form-group">
                                <label><?php echo esc_html(bizmart_text('Image', 'Image', 'صورة')); ?></label>
                                <div class="biz-image-upload-area" onclick="BizProducts.openMediaUploader('biz-digital-image-id', 'biz-digital-image-preview')">
                                    <div style="font-size: 48px; color: #9ca3af;">📷</div>
                                    <p style="margin: 10px 0 0 0; color: #6b7280;"><?php echo esc_html(bizmart_text('Click to upload', 'Cliquez pour télécharger', 'انقر للرفع')); ?></p>
                                </div>
                                <input type="hidden" id="biz-digital-image-id">
                                <img id="biz-digital-image-preview" class="biz-image-preview">
                            </div>
                            
                            <div style="display: flex; gap: 12px; margin-top: 30px;">
                                <button type="button" class="biz-btn biz-btn-success" onclick="BizProducts.createDigitalProduct(this)">
                                    <span style="font-size: 18px;">💾</span>
                                    <?php echo esc_html(bizmart_text('Create digital product', 'Créer produit digital', 'إنشاء منتج رقمي')); ?>
                                </button>
                                <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.resetForm('digital')">
                                    ↻ <?php echo esc_html(bizmart_text('Reset', 'Réinitialiser', 'إعادة تعيين')); ?>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Recent Products -->
            <div class="biz-card biz-recent-products">
                <h3 style="margin: 0 0 20px 0; color: #374151;">🕐 <?php echo esc_html(bizmart_text('Recently created products', 'Produits récemment créés', 'المنتجات المنشأة مؤخراً')); ?></h3>
                <div id="biz-recent-products-list">
                    <?php foreach ($recent_products as $product): ?>
                        <a href="<?php echo esc_url(get_edit_post_link($product->get_id())); ?>" target="_blank" rel="noopener" class="biz-product-item" style="display:flex;gap:12px;align-items:center;padding:12px 14px;border-bottom:1px solid #f1f5f9;text-decoration:none;color:inherit;">
                            <div class="biz-product-icon" style="flex:0 0 48px;display:flex;align-items:center;justify-content:center;border-radius:8px;background:#f8fafc;width:48px;height:48px;">
                                <?php 
                                if ($product->is_type('variable')) echo '🎯';
                                elseif ($product->is_type('grouped')) echo '📦';
                                elseif ($product->is_type('external')) echo '🔗';
                                elseif ($product->is_downloadable()) echo '💾';
                                else echo '📦';
                                ?>
                            </div>
                            <div class="biz-product-info" style="flex:1;min-width:0;">
                                <p class="biz-product-name" style="margin:0 0 4px;font-weight:700;color:#0f172a;line-height:1.2;"><?php echo esc_html($product->get_name()); ?></p>
                                <div style="display:flex;gap:10px;align-items:center;font-size:13px;color:#6b7280;">
                                    <div><?php echo $product->get_sku() ? esc_html($product->get_sku()) : esc_html(bizmart_text('No SKU', 'Pas de SKU', 'بدون SKU')); ?></div>
                                    <div style="color:#10b981;font-weight:600"><?php echo $product->is_in_stock() ? esc_html(bizmart_text('In stock','En stock', 'متوفر')) : esc_html(bizmart_text('Out of stock','Rupture', 'غير متوفر')); ?></div>
                                </div>
                                <?php $short = wp_trim_words( wp_strip_all_tags( $product->get_short_description() ?: $product->get_description() ), 20 ); ?>
                                <?php if ($short): ?><p style="margin:6px 0 0;font-size:13px;color:#475569;"><?php echo esc_html($short); ?></p><?php endif; ?>
                                <div style="margin-top:8px;font-size:13px;color:#6b7280;"><?php echo wp_kses_post(wp_trim_words(wp_strip_all_tags(wc_get_product_category_list($product->get_id(), ', ')), 10)); ?></div>
                            </div>
                            <div class="biz-product-price" style="flex:0 0 auto;text-align:right;min-width:110px;">
                                <?php echo wc_price($product->get_price()); ?>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>


        </div>
        
        <div class="biz-products-sidebar">
            <!-- Help Card -->
            <div class="biz-card">
                <h3 style="margin: 0 0 16px 0; color: #374151;">💡 <?php echo esc_html(bizmart_text('Quick tips', 'Astuces rapides', 'نصائح سريعة')); ?></h3>
                <div style="color: #6b7280; font-size: 14px; line-height: 1.6;">
                    <p><strong>📦 <?php echo esc_html(bizmart_text('Simple product', 'Produit Simple', 'منتج بسيط')); ?>:</strong> <?php echo esc_html(bizmart_text('Standard physical or digital items', 'Articles physiques ou digitaux standards', 'عناصر مادية أو رقمية قياسية')); ?></p>
                    <p><strong>🎯 <?php echo esc_html(bizmart_text('Variable product', 'Produit Variable', 'منتج متغير')); ?>:</strong> <?php echo esc_html(bizmart_text('Products with options (size, color)', 'Produits avec options (taille, couleur)', 'منتجات مع خيارات (مقاس، لون)')); ?></p>
                    <p><strong>📦 <?php echo esc_html(bizmart_text('Grouped product', 'Produit Groupé', 'منتج مجمّع')); ?>:</strong> <?php echo esc_html(bizmart_text('Bundles/sets of products', 'Packs/ensembles de produits', 'حزم/مجموعات من المنتجات')); ?></p>
                    <p><strong>🔗 <?php echo esc_html(bizmart_text('External product', 'Produit Externe', 'منتج خارجي')); ?>:</strong> <?php echo esc_html(bizmart_text('Products sold on other sites', "Produits vendus sur d'autres sites", 'منتجات تُباع على مواقع أخرى')); ?></p>
                    <p><strong>💾 <?php echo esc_html(bizmart_text('Digital product', 'Produit Digital', 'منتج رقمي')); ?>:</strong> <?php echo esc_html(bizmart_text('eBooks, music, software', 'eBooks, musique, logiciels', 'كتب إلكترونية، موسيقى، برامج')); ?></p>
                    <p><strong>📊 <?php echo esc_html(bizmart_text('Sync', 'Synchronisation', 'المزامنة')); ?>:</strong> <?php echo esc_html(bizmart_text('All products automatically sync with WooCommerce', 'Tous les produits sont automatiquement synchronisés avec WooCommerce', 'جميع المنتجات تتم مزامنتها تلقائياً مع WooCommerce')); ?></p>
                </div>
            </div>
            
            <!-- Quick Actions -->
            <div class="biz-card">
                <h3 style="margin: 0 0 16px 0; color: #374151;">⚡ <?php echo esc_html(bizmart_text('Quick actions', 'Actions rapides', 'إجراءات سريعة')); ?></h3>
                <div style="display: flex; flex-direction: column; gap: 12px;">
                    <?php if (defined('BIZMART_ADDON_VERSION')) : ?>
                    <a href="?page=bizmart-invoices" class="biz-btn" style="text-align: center;">
                        🧾 <?php echo esc_html(bizmart_text('New invoice', 'Nouvelle Facture', 'فاتورة جديدة')); ?>
                    </a>
                    <?php endif; ?>
                    <a href="<?php echo esc_url(admin_url('edit.php?post_type=product')); ?>" class="biz-btn biz-btn-secondary" style="text-align: center;">
                        📋 <?php echo esc_html(bizmart_text('All products', 'Tous les Produits', 'جميع المنتجات')); ?>
                    </a>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=products')); ?>" class="biz-btn biz-btn-secondary" style="text-align: center;">
                        ⚙️ <?php echo esc_html(bizmart_text('Product settings', 'Paramètres Produits', 'إعدادات المنتجات')); ?>
                    </a>
                </div>
            </div>
            
            <!-- Status -->
            <div class="biz-card">
                <h3 style="margin: 0 0 16px 0; color: #374151;">📊 <?php echo esc_html(bizmart_text('Sync', 'Synchronisation', 'المزامنة')); ?></h3>
                <div id="biz-sync-status" style="color: #10b981; font-size: 14px;">
                    ✅ <?php echo esc_html(bizmart_text('Connected to WooCommerce', 'Connecté à WooCommerce', 'متصل بـ WooCommerce')); ?> (<?php echo (int) $total_products; ?> <?php echo esc_html(bizmart_text('products', 'produits', 'منتجات')); ?>)
                </div>
                <div style="margin-top: 12px; font-size: 12px; color: #6b7280;">
                    <p><?php echo esc_html(bizmart_text('Supported features:', 'Fonctionnalités supportées:', 'الميزات المدعومة:')); ?></p>
                    <ul style="margin: 8px 0; padding-left: 20px;">
                        <li>✅ <?php echo esc_html(bizmart_text('All product types', 'Tous les types de produits', 'جميع أنواع المنتجات')); ?></li>
                        <li>✅ <?php echo esc_html(bizmart_text('Categories & tags', 'Catégories & étiquettes', 'الفئات والعلامات')); ?></li>
                        <li>✅ <?php echo esc_html(bizmart_text('Advanced stock management', 'Gestion du stock avancée', 'إدارة المخزون المتقدمة')); ?></li>
                        <li>✅ <?php echo esc_html(bizmart_text('Images & galleries', 'Images & galeries', 'الصور والمعارض')); ?></li>
                        <li>✅ <?php echo esc_html(bizmart_text('Shipping & dimensions', 'Livraison & dimensions', 'الشحن والأبعاد')); ?></li>
                        <li>✅ <?php echo esc_html(bizmart_text('Linked products', 'Produits liés', 'منتجات مرتبطة')); ?></li>
                        <li>✅ <?php echo esc_html(bizmart_text('Attributes & variations', 'Attributs & variations', 'السمات والتنويعات')); ?></li>
                        <li>✅ <?php echo esc_html(bizmart_text('Digital products', 'Produits digitaux', 'المنتجات الرقمية')); ?></li>
                    </ul>
                </div>
            </div>
            
            <!-- Product Types Stats -->
            <div class="biz-card">
                <h3 style="margin: 0 0 16px 0; color: #374151;">📊 <?php echo esc_html(bizmart_text('Product types', 'Types de Produits', 'أنواع المنتجات')); ?></h3>
                <div style="font-size: 13px;">
                    <?php
                    $product_types_labels = [
                        'simple' => bizmart_text('Simple', 'Simple', 'بسيط'),
                        'variable' => bizmart_text('Variable', 'Variable', 'متغير'),
                        'grouped' => bizmart_text('Grouped', 'Groupé', 'مجمّع'),
                        'external' => bizmart_text('External', 'Externe', 'خارجي')
                    ];
                    
                    foreach ($product_types_labels as $type => $label) {
                        $count = $type_counts[$type] ?? 0;
                        echo '<div style="display: flex; justify-content: space-between; margin-bottom: 8px; padding: 6px 0; border-bottom: 1px solid #f3f4f6;">
                                <span>' . $label . '</span>
                                <span style="font-weight: 600;">' . $count . '</span>
                              </div>';
                    }
                    ?>
                </div>
            </div>
        </div>
        </div>
        </div> <!-- End biz-products-container-inner -->
    <?php endif; ?>
    </div>
</div>



<?php if (false) : // Extracted to assets/products.js (enqueued on bizmart-products) ?>
<script>
(function($){
    window.BizProducts = {
        adminLang: '<?php echo esc_js(bizmart_admin_lang()); ?>',
        t: function(en, fr, ar) {
            if (this.adminLang === 'ar') {
                const dict = (window.BizmartI18n && BizmartI18n.ar) ? BizmartI18n.ar : null;
                return ar || (dict && dict[en]) || en;
            }
            return this.adminLang === 'fr' ? fr : en;
        },
        variationCount: 0,
        attributeCount: 1,
        digitalFiles: [],
        simpleGallery: [],
        variableGallery: [],
        tags: {
            simple: [],
            variable: [],
            external: [],
            digital: [],
            grouped: []
        },
        
        bindEvents: function() {
            $(document).on('click', '.biz-tag-remove', function(e) {
                e.preventDefault();
                e.stopPropagation();

                const $btn = $(this);
                const type = $btn.data('biz-type');
                const tag = $btn.data('biz-tag');

                // Product tags
                if (type && tag !== undefined) {
                    $btn.closest('.biz-tag').remove();
                    BizProducts.removeTag(type, tag);
                    return;
                }

                // Attribute value tags
                const $tagEl = $btn.closest('.biz-tag');
                const $row = $tagEl.closest('.biz-attribute-row');
                const rowId = $row.data('id');
                if (rowId) {
                    $tagEl.remove();
                    BizProducts.updateAttributeValues(rowId);
                }
            });

            $(document).on('input', '.biz-price-input', function() {
                const type = $(this).attr('id').startsWith('biz-simple') ? 'simple' : '';
                if (type) BizProducts.calculateProfit(type);
            });
        },

        calculateProfit: function(type) {
            const reg = parseFloat($(`#biz-${type}-regular-price`).val()) || 0;
            const sale = parseFloat($(`#biz-${type}-sale-price`).val()) || 0;
            const cost = parseFloat($(`#biz-${type}-cost-price`).val()) || 0;
            
            const selling = (sale > 0 && sale < reg) ? sale : reg;
            const $intel = $(`#biz-${type}-profit-intel`);
            
            if (selling <= 0 || cost <= 0) {
                $intel.fadeOut(200);
                return;
            }
            
            $intel.fadeIn(200);
            
            const profit = selling - cost;
            const margin = (profit / selling) * 100;
            const markup = (profit / cost) * 100;
            
            const $profitVal = $(`#biz-${type}-profit-val`);
            const $marginVal = $(`#biz-${type}-margin-val`);
            const $markupVal = $(`#biz-${type}-markup-val`);
            const $status = $(`#biz-${type}-profit-status`);

            const currency = 'د.ج';
            $profitVal.text(profit.toLocaleString() + ' ' + currency);
            $marginVal.text(margin.toFixed(1) + '%');
            $markupVal.text(markup.toFixed(1) + '%');

            if (profit > 0) {
                $profitVal.css('color', '#16a34a');
                $status.text('PROFITABLE').css({'background':'#dcfce7', 'color':'#16a34a'});
            } else if (profit < 0) {
                $profitVal.css('color', '#dc2626');
                $status.text('LOSS').css({'background':'#fee2e2', 'color':'#dc2626'});
            } else {
                $profitVal.css('color', '#64748b');
                $status.text('BREAK-EVEN').css({'background':'#f1f5f9', 'color':'#64748b'});
            }
        },

        addTag: function(type, tag) {
            tag = (tag || '').trim();
            if (!tag) return;
            if (!this.tags[type]) this.tags[type] = [];
            if (this.tags[type].includes(tag)) return;

            this.tags[type].push(tag);

            const $container = $(`#biz-${type}-tags-container`);
            const $tag = $('<span>', { class: 'biz-tag' }).text(tag + ' ');
            $tag.append(
                $('<span>', {
                    class: 'biz-tag-remove',
                    text: '×',
                    'data-biz-type': type,
                    'data-biz-tag': tag
                })
            );
            $container.prepend($tag);

            $(`#biz-${type}-tags`).val(this.tags[type].join(','));
        },

        removeTag: function(type, tag) {
            if (!this.tags[type]) return;
            this.tags[type] = this.tags[type].filter(t => t !== tag);
            $(`#biz-${type}-tags`).val(this.tags[type].join(','));
        },

        switchTab: function(tab) {
            $('.biz-tab').removeClass('active');
            $('.biz-tab-content').removeClass('active');

            $(`.biz-tab[data-tab="${tab}"]`).addClass('active');
            
            $(`#biz-tab-${tab}`).addClass('active');
        },
        
        toggleSection: function(sectionId) {
            const content = $(`#${sectionId}`);
            const icon = content.prev().find('span');
            content.toggleClass('show');
            icon.text(content.hasClass('show') ? '▲' : '▼');
        },
        
        toggleShippingSection: function(isVirtual) {
            const shippingSection = $('#biz-simple-shipping-section');
            if (isVirtual) {
                shippingSection.removeClass('show');
            } else {
                shippingSection.addClass('show');
            }
        },
        
        createCategory: function(type) {
            const categoryName = $(`#biz-${type}-new-category`).val().trim();
            if (!categoryName) {
                alert(BizProducts.t('Please enter a category name', 'Veuillez entrer un nom de catégorie'));
                return;
            }
            
            $.post(BizmartAnalytics.ajax_url, {
                action: 'bizmart_create_product_category',
                nonce: BizmartAnalytics.nonce,
                name: categoryName
            }, function(response) {
                if (response.success) {
                    const id = String(response.data.id);
                    const name = response.data.name;

                    // Add once to all category selects (avoid duplicates)
                    $('.biz-multiselect').each(function() {
                        const $sel = $(this);
                        if ($sel.attr('id') && $sel.attr('id').includes('categories')) {
                            if ($sel.find(`option[value="${id}"]`).length) return;
                            $sel.append($('<option>', { value: id, text: name }));
                        }
                    });

                    // Select in current tab without appending duplicates
                    const $current = $(`#biz-${type}-categories`);
                    const currentVal = ($current.val() || []).map(String);
                    if (!currentVal.includes(id)) currentVal.push(id);
                    $current.val(currentVal);
                    
                    // Clear input
                    $(`#biz-${type}-new-category`).val('');
                    
                    alert(BizProducts.t('Category created successfully!', 'Catégorie créée avec succès!'));
                } else {
                    alert(BizProducts.t('Error: ', 'Erreur: ') + response.data);
                }
            });
        },
        
        onExistingAttributeSelect: function(select) {
            const $select = $(select);
            const $row = $select.closest('.biz-attribute-row');
            const attributeSlug = $select.val();
            
            if (attributeSlug === 'new') {
                // Show the manual attribute name input
                $row.find('.attribute-name').show().focus();
                $row.find('.biz-attribute-values-input').prop('disabled', false);
                return;
            }
            
            if (attributeSlug) {
                // Get the selected attribute label
                const selectedOption = $select.find('option:selected');
                const attributeLabel = selectedOption.data('label') || attributeSlug;
                
                // Set the attribute name
                $row.find('.attribute-name').val(attributeLabel).show();
                
                // Fetch existing terms for this attribute
                $.post(BizmartAnalytics.ajax_url, {
                    action: 'bizmart_get_attribute_terms',
                    nonce: BizmartAnalytics.nonce,
                    attribute_name: attributeSlug
                }, function(response) {
                    if (response.success && response.data.terms.length > 0) {
                        // Clear existing tags
                        $row.find('.biz-attribute-values-input').siblings('.biz-tag').remove();
                        
                        // Add existing terms as tags
                        response.data.terms.forEach(function(term) {
                            const tag = String(term.name || '');
                            const rowId = $row.data('id');
                            const $container = $row.find('#biz-attribute-values-' + rowId);
                            const $tagEl = $('<span>', { class: 'biz-tag' }).text(tag + ' ');
                            $tagEl.append($('<span>', { class: 'biz-tag-remove', text: '×' }));
                            $container.prepend($tagEl);

                            BizProducts.updateAttributeValues(rowId);
                        });
                        
                        // Enable adding new terms
                        $row.find('.biz-attribute-values-input').prop('disabled', false);
                    }
                });
            } else {
                // Clear if "Choose existing attribute" is selected
                $row.find('.attribute-name').val('');
                $row.find('.biz-attribute-values-input').siblings('.biz-tag').remove();
                $row.find('.biz-attribute-values-input').prop('disabled', true);
                BizProducts.updateAttributeValues($row.data('id'));
            }
        },

        updateAttributeValues: function(rowId) {
            const $row = $(`.biz-attribute-row[data-id="${rowId}"]`);
            const tags = [];
            $row.find('.biz-tag').each(function() {
                tags.push($(this).contents().first().text().trim());
            });
            $(`#biz-attribute-values-hidden-${rowId}`).val(tags.join(','));
        },
        
        addAttribute: function() {
            this.attributeCount++;
            const id = this.attributeCount;
            
            // Generate existing attributes options
            let existingAttributesOptions = '';
            const existingAttributes = <?php echo wp_json_encode($attribute_taxonomies); ?>;
            existingAttributes.forEach(function(attr) {
                existingAttributesOptions += `<option value="${attr.attribute_name}" data-label="${attr.attribute_label}">${attr.attribute_label}</option>`;
            });
            
            const attributeHtml = `
                <div class="biz-attribute-row" data-id="${id}">
                    <div class="biz-form-grid-2">
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Select an existing attribute', 'Sélectionner un attribut existant')}</label>
                            <select class="biz-select existing-attribute-select" onchange="BizProducts.onExistingAttributeSelect(this)">
                                <option value="">-- ${BizProducts.t('Choose an existing attribute', 'Choisir un attribut existant')} --</option>
                                ${existingAttributesOptions}
                                <option value="new">+ ${BizProducts.t('Create a new attribute', 'Créer un nouvel attribut')}</option>
                            </select>
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Or create a new attribute', 'Ou créer un nouvel attribut')}</label>
                            <input type="text" class="biz-input attribute-name" placeholder="${BizProducts.t('Attribute name (e.g. Color, Size)', \"Nom de l\\'attribut (ex: Couleur, Taille)\")}" style="display: none;">
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Attribute values', \"Valeurs de l\\'attribut\")}</label>
                            <div class="biz-tag-input" id="biz-attribute-values-${id}">
                                <input type="text" class="biz-attribute-values-input" placeholder="${BizProducts.t('Add a value, press Enter', 'Ajouter une valeur, appuyez sur Entrée')}">
                            </div>
                            <input type="hidden" class="attribute-values" id="biz-attribute-values-hidden-${id}">
                            <small style="color: #6b7280;">${BizProducts.t('Separate values with commas or add them one by one', 'Séparer les valeurs par des virgules ou ajoutez-les une par une')}</small>
                        </div>
                    </div>
                    <div class="biz-form-grid-3">
                        <div class="biz-form-group">
                            <label style="display: flex; align-items: center; cursor: pointer;">
                                <span class="biz-switch">
                                    <input type="checkbox" class="attribute-visible" checked>
                                    <span class="biz-slider"></span>
                                </span>
                                ${BizProducts.t('Visible on product page', 'Visible sur la page produit')}
                            </label>
                        </div>
                        <div class="biz-form-group">
                            <label style="display: flex; align-items: center; cursor: pointer;">
                                <span class="biz-switch">
                                    <input type="checkbox" class="attribute-variation" checked>
                                    <span class="biz-slider"></span>
                                </span>
                                ${BizProducts.t('Used for variations', 'Utilisé pour les variations')}
                            </label>
                        </div>
                        <button type="button" class="biz-btn" onclick="BizProducts.removeAttribute(${id})">${BizProducts.t('Remove', 'Supprimer')}</button>
                    </div>
                </div>
            `;
            
            $('#biz-variable-attributes').append(attributeHtml);
            
            // Initialize tag input for the new attribute
            $(`#biz-attribute-values-${id} .biz-attribute-values-input`).on('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    const tag = $(this).val().trim();
                    if (tag) {
                        const rowId = $(this).closest('.biz-attribute-row').data('id');
                        const $container = $(`#biz-attribute-values-${rowId}`);
                        const $tagElement = $(`
                            <span class="biz-tag">
                                ${tag}
                                <span class="biz-tag-remove">×</span>
                            </span>
                        `);
                        $container.prepend($tagElement);
                        $(this).val('');
                        BizProducts.updateAttributeValues(rowId);
                    }
                }
            });
        },
        
        removeAttribute: function(id) {
            $(`.biz-attribute-row[data-id="${id}"]`).remove();
        },
        
        addVariation: function() {
            this.variationCount++;
            const id = this.variationCount;
            
            const variationHtml = `
                <div class="biz-variation-row" id="variation-${id}">
                    <div class="biz-variation-header">
                        <h4 class="biz-variation-title">Variation ${id}</h4>
                        <button type="button" class="biz-remove-variation" onclick="BizProducts.removeVariation(${id})">
                            &times;
                        </button>
                    </div>
                    
                    <div class="biz-form-grid-3">
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Attributes', 'Attributs')}</label>
                            <input type="text" class="biz-input variation-attributes" placeholder="${BizProducts.t('Color: Red, Size: M', 'Couleur: Rouge, Taille: M')}" data-id="${id}">
                            <small style="color: #6b7280;">${BizProducts.t('Format: Attribute: Value, Attribute: Value', 'Format: Attribut: Valeur, Attribut: Valeur')}</small>
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Variation SKU', 'SKU Variation')}</label>
                            <input type="text" class="biz-input variation-sku" placeholder="VAR-${id}" data-id="${id}">
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Regular price', 'Prix régulier')}</label>
                            <input type="number" step="0.01" min="0" class="biz-input variation-regular-price" placeholder="0.00" data-id="${id}">
                        </div>
                    </div>
                    
                    <div class="biz-form-grid-3">
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Sale price', 'Prix promotionnel')}</label>
                            <input type="number" step="0.01" min="0" class="biz-input variation-sale-price" placeholder="0.00" data-id="${id}">
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Cost price', "Prix d'achat")}</label>
                            <input type="number" step="0.01" min="0" class="biz-input variation-cost-price" placeholder="0.00" data-id="${id}">
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Stock', 'Stock')}</label>
                            <input type="number" min="0" class="biz-input variation-stock" placeholder="0" data-id="${id}">
                        </div>
                    </div>
                </div>
            `;
            
            $('#biz-variations-container').append(variationHtml);
        },
        
        generateVariations: function() {
            // Collect attributes
            const attributes = [];
            $('.biz-attribute-row').each(function() {
                const name = $(this).find('.attribute-name').val();
                const values = $(this).find('.attribute-values').val().split(',').map(v => v.trim()).filter(v => v);
                if (name && values.length > 0) {
                    attributes.push({
                        name: name,
                        values: values
                    });
                }
            });
            
            if (attributes.length === 0) {
                alert(BizProducts.t('Please define attributes first', "Veuillez d'abord définir des attributs"));
                return;
            }
            
            // Generate combinations
            let combinations = [];
            
            function generateCombos(current, index) {
                if (index === attributes.length) {
                    combinations.push([...current]);
                    return;
                }
                
                const attribute = attributes[index];
                for (const value of attribute.values) {
                    current.push({ name: attribute.name, value: value });
                    generateCombos(current, index + 1);
                    current.pop();
                }
            }
            
            generateCombos([], 0);
            
            // Clear and add variations
            $('#biz-variations-container').empty();
            this.variationCount = 0;
            
            combinations.forEach(combo => {
                this.variationCount++;
                const id = this.variationCount;
                const attrString = combo.map(attr => `${attr.name}: ${attr.value}`).join(', ');
                const comboJson = JSON.stringify(combo);
                
                const variationHtml = `
                    <div class="biz-variation-row" id="variation-${id}" data-combo='${comboJson}'>
                        <div class="biz-variation-header">
                            <h4 class="biz-variation-title">Variation ${id}</h4>
                            <button type="button" class="biz-remove-variation" onclick="BizProducts.removeVariation(${id})">
                                &times;
                            </button>
                        </div>
                        
                        <div class="biz-form-grid-3">
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Attributes', 'Attributs')}</label>
                                <input type="text" class="biz-input variation-attributes-display" value="${attrString}" readonly>
                            </div>
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Variation SKU', 'SKU Variation')}</label>
                                <input type="text" class="biz-input variation-sku" placeholder="${$('#biz-variable-sku').val() || 'VAR'}-${id}" data-id="${id}">
                            </div>
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Regular price', 'Prix régulier')}</label>
                                <input type="number" step="0.01" min="0" class="biz-input variation-regular-price" placeholder="${$('#biz-variable-base-regular').val() || '0.00'}" data-id="${id}">
                            </div>
                        </div>
                        
                        <div class="biz-form-grid-3">
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Sale price', 'Prix promotionnel')}</label>
                                <input type="number" step="0.01" min="0" class="biz-input variation-sale-price" placeholder="${$('#biz-variable-base-sale').val() || '0.00'}" data-id="${id}">
                            </div>
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Cost price', "Prix d'achat")}</label>
                                <input type="number" step="0.01" min="0" class="biz-input variation-cost-price" placeholder="${$('#biz-variable-base-cost').val() || '0.00'}" data-id="${id}">
                            </div>
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Stock', 'Stock')}</label>
                                <input type="number" min="0" class="biz-input variation-stock" placeholder="10" data-id="${id}">
                            </div>
                        </div>
                    </div>
                `;
                
                $('#biz-variations-container').append(variationHtml);
            });
            
            alert(BizProducts.t(`${combinations.length} variations generated automatically`, `${combinations.length} variations générées automatiquement`));
        },
        
        removeVariation: function(id) {
            $(`#variation-${id}`).remove();
        },
        
        openMediaUploader: function(inputId, previewId) {
            if (typeof wp === 'undefined' || !wp.media) {
                alert(BizProducts.t('Media uploader is not available. Please refresh the page.', "Le gestionnaire de médias n'est pas disponible. Veuillez rafraîchir la page."));
                return;
            }
            
            const frame = wp.media({
                title: BizProducts.t('Select an image', 'Sélectionner une image'),
                button: {
                    text: BizProducts.t('Use this image', 'Utiliser cette image')
                },
                multiple: false
            });
            
            frame.on('select', function() {
                const attachment = frame.state().get('selection').first().toJSON();
                $(`#${inputId}`).val(attachment.id);
                $(`#${previewId}`).attr('src', attachment.url).addClass('show');
            });
            
            frame.open();
        },
        
        openGalleryUploader: function(type) {
            if (typeof wp === 'undefined' || !wp.media) {
                alert(BizProducts.t('Media uploader is not available. Please refresh the page.', "Le gestionnaire de médias n'est pas disponible. Veuillez rafraîchir la page."));
                return;
            }
            
            const frame = wp.media({
                title: BizProducts.t('Select images', 'Sélectionner des images'),
                button: {
                    text: BizProducts.t('Add to gallery', 'Ajouter à la galerie')
                },
                multiple: true
            });
            
            frame.on('select', function() {
                const attachments = frame.state().get('selection').toJSON();
                attachments.forEach(attachment => {
                    BizProducts.addToGallery(type, attachment);
                });
            });
            
            frame.open();
        },
        
        openFileUploader: function() {
            if (typeof wp === 'undefined' || !wp.media) {
                alert(BizProducts.t('Media uploader is not available. Please refresh the page.', "Le gestionnaire de médias n'est pas disponible. Veuillez rafraîchir la page."));
                return;
            }
            
            const frame = wp.media({
                title: BizProducts.t('Add files', 'Ajouter des fichiers'),
                button: {
                    text: BizProducts.t('Add', 'Ajouter')
                },
                multiple: true,
                library: {
                    type: ['application/pdf', 'application/zip', 'audio/mpeg', 'image/jpeg', 'image/png', 'text/plain']
                }
            });
            
            frame.on('select', function() {
                const attachments = frame.state().get('selection').toJSON();
                attachments.forEach(attachment => {
                    BizProducts.addDigitalFile(attachment);
                });
            });
            
            frame.open();
        },
        
        addToGallery: function(type, attachment) {
            const galleryDiv = $(`#biz-${type}-gallery`);
            const imageId = attachment.id;
            
            if (BizProducts[type + 'Gallery'].includes(imageId)) return;
            
            BizProducts[type + 'Gallery'].push(imageId);
            
            const imageHtml = `
                <div style="position: relative; display: inline-block;">
                    <img src="${attachment.url}" class="biz-gallery-image">
                    <button type="button" class="biz-remove-image" onclick="BizProducts.removeFromGallery('${type}', ${imageId})">
                        ×
                    </button>
                </div>
            `;
            
            galleryDiv.append(imageHtml);
            $(`#biz-${type}-gallery-ids`).val(BizProducts[type + 'Gallery'].join(','));
        },
        
        removeFromGallery: function(type, imageId) {
            BizProducts[type + 'Gallery'] = BizProducts[type + 'Gallery'].filter(id => id !== imageId);
            $(`#biz-${type}-gallery-ids`).val(BizProducts[type + 'Gallery'].join(','));
            $(`button[onclick="BizProducts.removeFromGallery('${type}', ${imageId})"]`).parent().remove();
        },
        
        addDigitalFile: function(attachment) {
            const fileId = attachment.id;
            
            if (this.digitalFiles.some(f => f.id === fileId)) return;
            
            this.digitalFiles.push({
                id: fileId,
                name: attachment.filename || attachment.title,
                url: attachment.url
            });
            
            this.updateDigitalFilesList();
        },
        
        updateDigitalFilesList: function() {
            const listDiv = $('#biz-digital-files-list');
            listDiv.empty();
            
            this.digitalFiles.forEach((file, index) => {
                const fileHtml = `
                    <div class="biz-file-item">
                        <div class="biz-file-name">
                            <span style="font-size: 20px;">📎</span>
                            <span style="font-size: 14px;">${file.name}</span>
                        </div>
                        <button type="button" class="biz-remove-variation" onclick="BizProducts.removeDigitalFile(${index})">
                            &times;
                        </button>
                    </div>
                `;
                listDiv.append(fileHtml);
            });
            
            $('#biz-digital-files').val(JSON.stringify(this.digitalFiles));
        },
        
        removeDigitalFile: function(index) {
            this.digitalFiles.splice(index, 1);
            this.updateDigitalFilesList();
        },
        
        createSimpleProduct: function(btnEl) {
            this.saveProduct('simple', 'publish', btnEl);
        },
        
        createVariableProduct: function(btnEl) {
            this.saveProduct('variable', 'publish', btnEl);
        },
        
        createGroupedProduct: function(btnEl) {
            this.saveProduct('grouped', 'publish', btnEl);
        },
        
        createExternalProduct: function(btnEl) {
            this.saveProduct('external', 'publish', btnEl);
        },
        
        createDigitalProduct: function(btnEl) {
            this.saveProduct('digital', 'publish', btnEl);
        },
        
        saveProduct: function(type, status, btnEl) {
            let productData = {};
            // Robust edit detection: prefer server-provided edit data, then hidden field, then URL param.
            const editIdFromGlobal = (window.BizmartEditData && window.BizmartEditData.id) ? parseInt(window.BizmartEditData.id, 10) : 0;
            const editIdFromHidden = parseInt($('#bizmart-edit-product-id').val() || '0', 10);
            const editIdFromUrl = (() => { try { const u = new URLSearchParams(window.location.search); return parseInt(u.get('id') || '0', 10) || 0; } catch(e){ return 0; } })();
            const editId = editIdFromGlobal || editIdFromHidden || editIdFromUrl || 0;
            const isEditMode = !!editId;

            
            switch(type) {
                case 'simple':
                    productData = {
                        name: $('#biz-simple-name').val(),
                        sku: $('#biz-simple-sku').val(),
                        regular_price: $('#biz-simple-regular-price').val(),
                        sale_price: $('#biz-simple-sale-price').val() || '',
                        cost_price: $('#biz-simple-cost-price').val() || '',
                        short_description: $('#biz-simple-short-description').val(),
                        description: $('#biz-simple-description').val(),
                        categories: $('#biz-simple-categories').val() || [],
                        tags: this.tags.simple,
                        image_id: $('#biz-simple-image-id').val() || 0,
                        gallery_ids: this.simpleGallery,
                        manage_stock: $('#biz-simple-manage-stock').is(':checked') ? 1 : 0,
                        stock_status: $('#biz-simple-stock-status').val(),
                        stock_quantity: $('#biz-simple-stock-quantity').val() || 0,
                        backorders: $('#biz-simple-backorders').val(),
                        sold_individually: $('#biz-simple-sold-individually').val() === 'yes' ? 1 : 0,
                        weight: $('#biz-simple-weight').val() || '',
                        length: $('#biz-simple-length').val() || '',
                        width: $('#biz-simple-width').val() || '',
                        height: $('#biz-simple-height').val() || '',
                        shipping_class: $('#biz-simple-shipping-class').val() || '',
                        virtual: $('#biz-simple-virtual').is(':checked') ? 1 : 0,
                        cross_sell_ids: $('#biz-simple-cross-sells').val().split(',').map(s => s.trim()).filter(s => s),
                        upsell_ids: $('#biz-simple-upsells').val().split(',').map(s => s.trim()).filter(s => s),
                        purchase_note: $('#biz-simple-purchase-note').val(),
                        menu_order: $('#biz-simple-menu-order').val() || 0,
                        status: status,
                        comment_status: $('#biz-simple-reviews').val()
                    };

                    // Minimal requirement: name only.
                    if (!productData.name) {
                        alert(BizProducts.t('Please enter a product name', 'Veuillez saisir un nom de produit'));
                        return;
                    }
                    if (!isEditMode && !productData.sku) {
                        productData.sku = String(productData.name)
                            .toUpperCase()
                            .replace(/[^A-Z0-9]/g, '')
                            .substring(0, 12) || ('BIZ-' + Date.now());
                        $('#biz-simple-sku').val(productData.sku);
                    }
                    if (!productData.regular_price) {
                        productData.regular_price = '';
                    }
                    break;
                    
                case 'variable':
                    // Collect attributes
                    const attributes = [];
                    $('.biz-attribute-row').each(function() {
                        const name = $(this).find('.attribute-name').val();
                        const valuesInput = $(this).find('.attribute-values').val();
                        const values = valuesInput ? valuesInput.split(',').map(v => v.trim()).filter(v => v) : [];
                        const visible = $(this).find('.attribute-visible').is(':checked');
                        const variation = $(this).find('.attribute-variation').is(':checked');
                        
                        if (name && values.length > 0) {
                            attributes.push({
                                name: name,
                                options: values,
                                visible: visible,
                                variation: variation
                            });
                        }
                    });
                    
                    // Collect variations
                    const variations = [];
                    $('.biz-variation-row').each(function() {
                        const $vrow = $(this);
                        let vAttrs = {};
                        const comboData = $vrow.data('combo');
                        
                        if (comboData && Array.isArray(comboData)) {
                            comboData.forEach(c => { vAttrs[c.name] = c.value; });
                        } else {
                            // Fallback to manual parsing if data-combo is missing
                            const attrStr = $vrow.find('.variation-attributes-display').val() || '';
                            attrStr.split(',').forEach(p => {
                                const kv = p.split(':');
                                if (kv.length === 2) vAttrs[kv[0].trim()] = kv[1].trim();
                            });
                        }

                        const variationData = {
                            attributes: vAttrs,
                            sku: $vrow.find('.variation-sku').val() || $vrow.find('.variation-sku').attr('placeholder'),
                            regular_price: $vrow.find('.variation-regular-price').val() || $vrow.find('.variation-regular-price').attr('placeholder'),
                            sale_price: $vrow.find('.variation-sale-price').val() || $vrow.find('.variation-sale-price').attr('placeholder') || '',
                            cost_price: $vrow.find('.variation-cost-price').val() || $vrow.find('.variation-cost-price').attr('placeholder') || '',
                            stock_quantity: $vrow.find('.variation-stock').val() || $vrow.find('.variation-stock').attr('placeholder') || 0
                        };
                        
                        const hasExistingId = !!$vrow.data('variation-id');
                        const hasSku = !!variationData.sku;
                        const hasAttrs = variationData.attributes && Object.keys(variationData.attributes).length > 0;
                        if (hasExistingId || hasSku || hasAttrs) {
                            if (hasExistingId) {
                                variationData.id = $vrow.data('variation-id');
                            }
                            variations.push(variationData);
                        }
                    });
                    
                    productData = {
                        name: $('#biz-variable-name').val(),
                        sku: $('#biz-variable-sku').val(),
                        short_description: $('#biz-variable-short-description').val(),
                        description: $('#biz-variable-description').val(),
                        categories: $('#biz-variable-categories').val() || [],
                        tags: this.tags.variable,
                        image_id: $('#biz-variable-image-id').val() || 0,
                        attributes: attributes,
                        variations: variations,
                        base_regular_price: $('#biz-variable-base-regular').val() || '',
                        base_sale_price: $('#biz-variable-base-sale').val() || '',
                        base_cost_price: $('#biz-variable-base-cost').val() || '',
                        status: status
                    };
                    
                    if (!productData.name || !productData.sku) {
                        alert(BizProducts.t('Please fill in the product name and SKU', 'Veuillez remplir le nom et le SKU du produit'));
                        return;
                    }
                    
                    if (attributes.length === 0) {
                        alert(BizProducts.t('Please define at least one attribute', 'Veuillez définir au moins un attribut'));
                        return;
                    }
                    
                    if (variations.length === 0) {
                        alert(BizProducts.t('Please create at least one variation', 'Veuillez créer au moins une variation'));
                        return;
                    }
                    break;
                    
                case 'grouped':
                    productData = {
                        name: $('#biz-grouped-name').val(),
                        sku: $('#biz-grouped-sku').val(),
                        description: $('#biz-grouped-description').val(),
                        categories: $('#biz-grouped-categories').val() || [],
                        image_id: $('#biz-grouped-image-id').val() || 0,
                        grouped_products: $('#biz-grouped-products').val() || [],
                        status: status
                    };
                    
                    if (!productData.name || !productData.sku) {
                        alert(BizProducts.t('Please fill in the group name and SKU', 'Veuillez remplir le nom et le SKU du groupe'));
                        return;
                    }
                    
                    if (productData.grouped_products.length === 0) {
                        alert(BizProducts.t('Please select at least one product to include in the group', 'Veuillez sélectionner au moins un produit à inclure dans le groupe'));
                        return;
                    }
                    break;
                    
                case 'external':
                    productData = {
                        name: $('#biz-external-name').val(),
                        sku: $('#biz-external-sku').val(),
                        product_url: $('#biz-external-url').val(),
                        button_text: $('#biz-external-button').val(),
                        regular_price: $('#biz-external-price').val() || '',
                        sale_price: $('#biz-external-sale-price').val() || '',
                        cost_price: $('#biz-external-cost-price').val() || '',
                        categories: $('#biz-external-categories').val() || [],
                        description: $('#biz-external-description').val(),
                        image_id: $('#biz-external-image-id').val() || 0,
                        status: status
                    };
                    
                    if (!productData.name || !productData.sku || !productData.product_url || !productData.button_text) {
                        alert(BizProducts.t('Please fill in all required fields', 'Veuillez remplir tous les champs obligatoires'));
                        return;
                    }
                    break;
                    
                case 'digital':
                    // Collect digital files
                    const files = [];
                    $('.biz-digital-file-row').each(function() {
                        const name = $(this).find('.digital-file-name').val();
                        const url = $(this).find('.digital-file-url').val();
                        if (name && url) {
                            files.push({ name: name, url: url });
                        }
                    });
                    
                    productData = {
                        name: $('#biz-digital-name').val(),
                        sku: $('#biz-digital-sku').val(),
                        regular_price: $('#biz-digital-price').val() || '0',
                        sale_price: $('#biz-digital-sale-price').val() || '',
                        cost_price: $('#biz-digital-cost-price').val() || '',
                        description: $('#biz-digital-description').val(),
                        categories: $('#biz-digital-categories').val() || [],
                        image_id: $('#biz-digital-image-id').val() || 0,
                        download_files: files,
                        download_limit: $('#biz-digital-limit').val() || -1,
                        download_expiry: $('#biz-digital-expiry').val() || -1,
                        virtual: 1,
                        downloadable: 1,
                        status: status
                    };
                    
                    if (!productData.name) {
                        alert(BizProducts.t('Please enter a product name', 'Veuillez saisir un nom de produit'));
                        return;
                    }
                    if (!isEditMode && !productData.sku) {
                        productData.sku = String(productData.name)
                            .toUpperCase()
                            .replace(/[^A-Z0-9]/g, '')
                            .substring(0, 12) || ('BIZ-' + Date.now());
                        $('#biz-digital-sku').val(productData.sku);
                    }
                    if (!productData.regular_price) {
                        productData.regular_price = '';
                    }
                    
                    if (productData.download_files.length === 0) {
                        alert(BizProducts.t('Please add at least one downloadable file', 'Veuillez ajouter au moins un fichier téléchargeable'));
                        return;
                    }
                    break;
            }
            // Global: Add ID if in edit mode (robust)
            if (isEditMode) { productData.id = editId; }
const isUpdate = !!productData.id;
            const $btn = btnEl ? $(btnEl) : $(`button[onclick^="BizProducts.create${type.charAt(0).toUpperCase() + type.slice(1)}Product"]`);
            const originalText = $btn.html();
            
            $btn.prop('disabled', true).html('<span class="biz-loading"></span> ' + (isUpdate ? BizProducts.t('Updating...', 'Mise à jour...') : BizProducts.t('Creating...', 'Création...')));
            
            $.post(BizmartAnalytics.ajax_url, {
                action: `bizmart_create_${type}_product`,
                nonce: BizmartAnalytics.nonce,
                data: JSON.stringify(productData)
            }, function(response) {
                $btn.prop('disabled', false).html(originalText);
                
                if (response.success) {
                    // Show success message
                    const msg = isUpdate ? BizProducts.t('Product updated successfully!', 'Produit mis à jour avec succès!') : BizProducts.t('Product created successfully!', 'Produit créé avec succès!');
                    const alertHtml = `
                        <div class="biz-alert biz-alert-success">
                            <strong>✅ ${msg}</strong><br>
                            ${response.data.name} (${response.data.sku})<br>
                            <small><a href="${response.data.edit_link}" target="_blank">${BizProducts.t('Edit product', 'Modifier le produit')}</a> | 
                            <a href="${response.data.view_link}" target="_blank">${BizProducts.t('View product', 'Voir le produit')}</a></small>
                        </div>
                    `;
                    
                    $('.biz-products-main').prepend(alertHtml);
                    
                    // Reset form
                    BizProducts.resetForm(type);
                    
                    // Reload page to update stats
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                    
                    // Remove alert after 5 seconds
                    setTimeout(() => {
                        $('.biz-alert').fadeOut(300, function() {
                            $(this).remove();
                        });
                    }, 5000);
                } else {
                    var msg = response.data;
                    if (msg && typeof msg === 'object' && msg.message) msg = msg.message;
                    alert(BizProducts.t('Error: ', 'Erreur: ') + (msg || BizProducts.t('An error occurred', 'Une erreur est survenue')));
                }
            }).fail(function(xhr, status, error) {
                $btn.prop('disabled', false).html(originalText);
                alert(BizProducts.t('Server connection error: ', 'Erreur de connexion au serveur: ') + error);
            });
        },
        
        resetForm: function(type) {
            $(`#biz-form-${type}`)[0].reset();
            
            // Reset specific elements
            switch(type) {
                case 'simple':
                    $('#biz-simple-stock-quantity-group').hide();
                    $('#biz-simple-image-preview').removeClass('show').attr('src', '');
                    $('#biz-simple-image-id').val('');
                    this.simpleGallery = [];
                    $('#biz-simple-gallery').empty();
                    this.tags.simple = [];
                    $('#biz-simple-tags').val('');
                    $('#biz-simple-tags-container .biz-tag').remove();
                    $('#biz-simple-shipping-section').removeClass('show');
                    break;
                    
                case 'variable':
                    $('#biz-variations-container').empty();
                    this.variationCount = 0;
                    this.attributeCount = 1;
                    $('#biz-variable-attributes').empty();
                    // Add default attribute row
                    const defaultAttr = `
                        <div class="biz-attribute-row" data-id="1">
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label>${BizProducts.t('Attribute name', "Nom de l'attribut")}</label>
                                    <input type="text" class="biz-input attribute-name" placeholder="${BizProducts.t('e.g. Color, Size', 'ex: Couleur, Taille')}">
                                </div>
                                <div class="biz-form-group">
                                    <label>${BizProducts.t('Values', 'Valeurs')}</label>
                                    <input type="text" class="biz-input attribute-values" placeholder="${BizProducts.t('e.g. Red, Blue, Green (comma-separated)', 'ex: Rouge, Bleu, Vert (séparées par des virgules)')}">
                                </div>
                            </div>
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label style="display: flex; align-items: center; cursor: pointer;">
                                        <span class="biz-switch">
                                            <input type="checkbox" class="attribute-visible" checked>
                                            <span class="biz-slider"></span>
                                        </span>
                                        ${BizProducts.t('Visible on product page', 'Visible sur la page produit')}
                                    </label>
                                </div>
                                <div class="biz-form-group">
                                    <label style="display: flex; align-items: center; cursor: pointer;">
                                        <span class="biz-switch">
                                            <input type="checkbox" class="attribute-variation" checked>
                                            <span class="biz-slider"></span>
                                        </span>
                                        ${BizProducts.t('Used for variations', 'Utilisé pour les variations')}
                                    </label>
                                </div>
                                <button type="button" class="biz-btn" onclick="BizProducts.addAttribute()">+ ${BizProducts.t('Add attribute', 'Ajouter attribut')}</button>
                            </div>
                        </div>
                    `;
                    $('#biz-variable-attributes').html(defaultAttr);
                    
                    $('#biz-variable-image-preview').removeClass('show').attr('src', '');
                    $('#biz-variable-image-id').val('');
                    this.tags.variable = [];
                    $('#biz-variable-tags').val('');
                    $('#biz-variable-tags-container .biz-tag').remove();
                    break;
                    
                case 'digital':
                    this.digitalFiles = [];
                    $('#biz-digital-files-list').empty();
                    $('#biz-digital-files').val('');
                    $('#biz-digital-image-preview').removeClass('show').attr('src', '');
                    $('#biz-digital-image-id').val('');
                    break;
                    
                case 'grouped':
                    $('#biz-grouped-image-preview').removeClass('show').attr('src', '');
                    $('#biz-grouped-image-id').val('');
                    break;
                    
                case 'external':
                    $('#biz-external-image-preview').removeClass('show').attr('src', '');
                    $('#biz-external-image-id').val('');
                    break;
            }
        }
    };
    
    // Initialize
    $(document).ready(function() {
        BizProducts.bindEvents();

        // Initialize tag inputs for all tabs (safe DOM rendering, no inline JS)
        ['simple', 'variable', 'external', 'digital', 'grouped'].forEach(type => {
            $(`#biz-${type}-tags-input`).on('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    const tag = $(this).val();
                    BizProducts.addTag(type, tag);
                    $(this).val('');
                }
            });
        });
        
        // Toggle stock quantity field for simple products
        $('#biz-simple-manage-stock').on('change', function() {
            if ($(this).is(':checked')) {
                $('#biz-simple-stock-quantity-group').show();
            } else {
                $('#biz-simple-stock-quantity-group').hide();
            }
        });
        
        // Auto-generate SKU for simple product
        $('#biz-simple-name').on('blur', function() {
            if ($('#biz-simple-sku').val() === '') {
                const name = $(this).val();
                if (name) {
                    const sku = name.toUpperCase()
                        .replace(/[^A-Z0-9]/g, '')
                        .substring(0, 10);
                    $('#biz-simple-sku').val(sku);
                }
            }
        });
        
        // Hide shipping section by default (virtual checked)
        $('#biz-simple-shipping-section').removeClass('show');
        
        // Show advanced section when page loads
        setTimeout(() => {
            $('#biz-simple-advanced').addClass('show');
            $('#biz-simple-advanced').prev().find('span').text('▲');
        }, 100);
        
        // Initialize tag input for the first attribute row
        $('#biz-attribute-values-1 .biz-attribute-values-input').on('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const tag = $(this).val().trim();
                if (tag) {
                    const rowId = $(this).closest('.biz-attribute-row').data('id');
                    const $container = $(`#biz-attribute-values-${rowId}`);
                    const $tagElement = $('<span>', { class: 'biz-tag' }).text(tag + ' ');
                    $tagElement.append($('<span>', { class: 'biz-tag-remove', text: '×' }));
                    $container.prepend($tagElement);
                    $(this).val('');
                    BizProducts.updateAttributeValues(rowId);
                }
            }
        });
    });
})(jQuery);
</script>
    </div><!-- .biz-products-container -->
    </div><!-- .wrap -->
<?php endif; ?>
