<?php if (isset($component)) { $__componentOriginal3f11930a8702d3d700513f5d743b90ca = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal3f11930a8702d3d700513f5d743b90ca = $attributes; } ?>
<?php $component = App\View\Components\TenantLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('tenant-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\TenantLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('header', null, []); ?> 
        <div class="flex justify-between items-center">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                <?php echo e(__('Edit Product')); ?>: <?php echo e($product->name); ?>

            </h2>
            <button type="submit" form="product-form" class="inline-flex items-center px-4 py-2 bg-green-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-green-700 active:bg-green-900 focus:outline-none focus:border-green-900 focus:ring ring-green-300 disabled:opacity-25 transition ease-in-out duration-150 shadow-sm">
                Update
            </button>
        </div>
     <?php $__env->endSlot(); ?>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white shadow-sm sm:rounded-lg pb-10">
                <div class="p-6 bg-white border-b border-gray-200">
                    <form method="POST" action="<?php echo e(route('tenant.products.update', $product->id)); ?>" id="product-form" enctype="multipart/form-data">
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('PUT'); ?>
                        <input type="hidden" name="has_variants" id="has_variants_input" value="<?php echo e($product->has_variants ? '1' : '0'); ?>">

                        <!-- Basic Information -->
                        <div class="mb-8">
                            <h3 class="text-lg font-medium text-gray-900 border-b-2 border-green-100 pb-2 mb-6 flex items-center">
                                <span class="bg-green-100 text-green-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">1</span>
                                Basic Information
                            </h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label for="name" class="block text-sm font-medium text-gray-700">Product Name</label>
                                    <input type="text" name="name" id="product_name" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50" value="<?php echo e(old('name', $product->name)); ?>" required>
                                </div>

                                <div>
                                    <label for="category_id" class="block text-sm font-medium text-gray-700">Category</label>
                                    <select name="category_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50">
                                        <option value="">-- Select Category --</option>
                                        <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($category->id); ?>" <?php echo e($product->category_id == $category->id ? 'selected' : ''); ?>><?php echo e($category->name); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>

                                <div>
                                    <label for="brand_id" class="block text-sm font-medium text-gray-700">Brand</label>
                                    <select name="brand_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50">
                                        <option value="">-- Select Brand --</option>
                                        <?php $__currentLoopData = $brands; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $brand): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($brand->id); ?>" <?php echo e($product->brand_id == $brand->id ? 'selected' : ''); ?>><?php echo e($brand->name); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>

                                <div>
                                    <label for="unit_id" class="block text-sm font-medium text-gray-700">Base Unit</label>
                                    <select name="unit_id" id="base_unit" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50" required>
                                        <option value="">-- Select Base Unit --</option>
                                        <?php $__currentLoopData = $units; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $unit): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($unit->id); ?>" data-name="<?php echo e($unit->name); ?>" <?php echo e($product->unit_id == $unit->id ? 'selected' : ''); ?>><?php echo e($unit->name); ?> (<?php echo e($unit->short_name); ?>)</option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>

                                <div>
                                    <label for="manufacture_date" class="block text-sm font-medium text-gray-700">Manufacture Date</label>
                                    <input type="date" name="manufacture_date" id="manufacture_date" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50" value="<?php echo e(old('manufacture_date', $product->manufacture_date ? $product->manufacture_date->format('Y-m-d') : '')); ?>">
                                </div>
                                <div>
                                    <label for="expiry_date" class="block text-sm font-medium text-gray-700">Expiry Date</label>
                                    <input type="date" name="expiry_date" id="expiry_date" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50" value="<?php echo e(old('expiry_date', $product->expiry_date ? $product->expiry_date->format('Y-m-d') : '')); ?>">
                                </div>

                                <div class="col-span-1 md:col-span-2">
                                    <label for="image" class="block text-sm font-medium text-gray-700">Product Image (Optional)</label>
                                    <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md hover:border-green-400 transition-colors">
                                        <div class="space-y-1 text-center">
                                            <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
                                                <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                                            </svg>
                                            <div class="flex text-sm text-gray-600 justify-center">
                                                <label for="product-image-upload" class="relative cursor-pointer bg-white rounded-md font-medium text-green-600 hover:text-green-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-green-500">
                                                    <span>Upload a file</span>
                                                    <input id="product-image-upload" name="image" type="file" class="sr-only" accept="image/*">
                                                </label>
                                                <p class="pl-1">or drag and drop</p>
                                            </div>
                                            <p class="text-xs text-gray-500">PNG, JPG, GIF up to 2MB</p>
                                        </div>
                                    </div>
                                    <div id="image-preview" class="mt-4 <?php echo e($product->image_url ? '' : 'hidden'); ?>">
                                        <p class="text-sm text-gray-500 mb-2">Preview:</p>
                                        <img src="<?php echo e($product->image_url ?? '#'); ?>" alt="Image Preview" class="h-32 w-auto object-cover rounded-md border border-gray-200">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Variant Toggle -->
                        <div class="mb-8 p-4 bg-gray-50 rounded-lg border border-gray-200 flex items-center justify-between">
                            <div class="flex items-center">
                                <input type="checkbox" id="has_variants_checkbox" class="form-checkbox h-5 w-5 text-green-600 rounded focus:ring-green-500 transition duration-150 ease-in-out" <?php echo e($product->has_variants ? 'checked' : ''); ?>>
                                <label for="has_variants_checkbox" class="ml-3 cursor-pointer">
                                    <span class="block text-sm font-medium text-gray-900">This product has multiple options</span>
                                    <span class="block text-sm text-gray-500">Enable this if you sell variants like Size, Color, etc.</span>
                                </label>
                            </div>
                        </div>

                        <!-- SIMPLE PRODUCT FORM -->
                        <div id="simple_product_section" style="<?php echo e($product->has_variants ? 'display: none;' : ''); ?>">
                            <h3 class="text-lg font-medium text-gray-900 border-b-2 border-blue-100 pb-2 mb-6 flex items-center">
                                <span class="bg-blue-100 text-blue-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">2</span>
                                Pricing & Inventory
                            </h3>
                            <?php
                                $simpleVariant = $product->variants->first();
                                $basePriceRecord = null;
                                if ($simpleVariant) {
                                    $basePriceRecord = $simpleVariant->prices->filter(function($p) {
                                        return $p->productUnit && $p->productUnit->is_base;
                                    })->first();
                                }
                                
                                $simplePrice = $basePriceRecord ? $basePriceRecord->price : ($simpleVariant->price ?? 0);
                                $simpleCost = $basePriceRecord ? $basePriceRecord->cost : ($simpleVariant->cost ?? 0);
                                $simpleStock = $simpleVariant->stock ?? 0;
                                $simpleSku = $simpleVariant->sku ?? '';
                            ?>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 bg-gray-50 p-6 rounded-lg border border-gray-100">
                                <div>
                                    <label for="simple_sku" class="block text-sm font-medium text-gray-700">SKU</label>
                                    <input type="text" id="simple_sku" name="sku" value="<?php echo e($simpleSku); ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50" placeholder="e.g. SKU-12345">
                                </div>
                                <div>
                                    <label for="simple_stock" class="block text-sm font-medium text-gray-700">Initial Stock</label>
                                    <input type="number" id="simple_stock" name="stock" value="<?php echo e($simpleStock); ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50" placeholder="0">
                                </div>
                                <div>
                                    <label for="simple_price" class="block text-sm font-medium text-gray-700">Selling Price ($)</label>
                                    <div class="mt-1 relative rounded-md shadow-sm">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <span class="text-gray-500 sm:text-sm">$</span>
                                        </div>
                                        <input type="number" id="simple_price" name="price" value="<?php echo e($simplePrice); ?>" step="0.01" min="0" class="pl-7 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50" placeholder="0.00">
                                    </div>
                                </div>
                                <div>
                                    <label for="simple_cost" class="block text-sm font-medium text-gray-700">Cost Price ($)</label>
                                    <div class="mt-1 relative rounded-md shadow-sm">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <span class="text-gray-500 sm:text-sm">$</span>
                                        </div>
                                        <input type="number" id="simple_cost" name="cost" value="<?php echo e($simpleCost); ?>" step="0.01" min="0" class="pl-7 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50" placeholder="0.00">
                                    </div>
                                </div>
                            </div>

                        <!-- COMPLEX PRODUCT FORM -->
                        <div id="complex_product_section" style="<?php echo e($product->has_variants ? '' : 'display: none;'); ?>">
                            
                            <!-- Debug Information -->
                            <div class="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded">
                                <p class="text-sm text-yellow-800">
                                    <strong>Debug Info:</strong> 
                                    has_variants = <?php echo e($product->has_variants ? 'TRUE' : 'FALSE'); ?>, 
                                    variants count = <?php echo e($product->variants->count()); ?>

                                </p>
                            </div>
                            
                            <?php
                                logger('Edit Product Debug: has_variants = ' . $product->has_variants);
                                logger('Edit Product Debug: variants count = ' . $product->variants->count());
                                if ($product->variants->count() > 0) {
                                    foreach($product->variants as $index => $variant) {
                                        logger('Edit Product Debug: Variant ' . $index . ' = ' . $variant->name);
                                    }
                                }
                            ?>
                            
                            <!-- Step 1: Define Attributes -->
                            <div class="mb-8">
                                <h3 class="text-lg font-medium text-gray-900 border-b-2 border-indigo-100 pb-2 mb-6 flex items-center">
                                    <span class="bg-indigo-100 text-indigo-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">2</span>
                                    Define Attributes
                                </h3>
                                <div id="attributes_container" class="space-y-4">
                                    <?php
                                        // Extract Attributes logic
                                        $existingAttributes = [];
                                        if ($product->has_variants) {
                                            foreach($product->variants as $v) {
                                                foreach($v->attributes as $attr) {
                                                    $existingAttributes[$attr->name][] = $attr->value;
                                                }
                                            }
                                            foreach($existingAttributes as $name => $vals) {
                                                $existingAttributes[$name] = array_unique($vals);
                                            }
                                        }
                                    ?>

                                    <?php $__empty_1 = true; $__currentLoopData = $existingAttributes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $name => $vals): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                        <div class="attribute-row flex gap-4 items-start bg-indigo-50 p-4 rounded-md border border-indigo-100 mt-2">
                                            <div class="w-1/3">
                                                <label class="block text-xs font-medium text-gray-500 mb-1">Attribute Name</label>
                                                <input type="text" class="attribute-name mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="e.g. Color" value="<?php echo e($name); ?>">
                                            </div>
                                            <div class="w-1/2">
                                                <label class="block text-xs font-medium text-gray-500 mb-1">Values (comma separated)</label>
                                                <input type="text" class="attribute-values mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="e.g. Red, Blue, Green" value="<?php echo e(implode(', ', $vals)); ?>">
                                            </div>
                                            <div class="pt-6">
                                                <button type="button" class="remove-attribute text-red-400 hover:text-red-600 transition-colors">
                                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                                </button>
                                            </div>
                                        </div>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                        <div class="attribute-row flex gap-4 items-start bg-indigo-50 p-4 rounded-md border border-indigo-100">
                                            <div class="w-1/3">
                                                <label class="block text-xs font-medium text-gray-500 mb-1">Attribute Name</label>
                                                <input type="text" class="attribute-name mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="e.g. Color">
                                            </div>
                                            <div class="w-1/2">
                                                <label class="block text-xs font-medium text-gray-500 mb-1">Values (comma separated)</label>
                                                <input type="text" class="attribute-values mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="e.g. Red, Blue, Green">
                                            </div>
                                            <div class="pt-6">
                                                <button type="button" class="remove-attribute text-red-400 hover:text-red-600 transition-colors">
                                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                                </button>
                                            </div>
                                        <?php endif; ?>
                                </div>
                                <div class="mt-4">
                                    <button type="button" id="add_attribute_btn" class="inline-flex items-center px-3 py-2 border border-indigo-300 shadow-sm text-sm leading-4 font-medium rounded-md text-indigo-700 bg-white hover:bg-indigo-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                        + Add Another Attribute
                                    </button>
                                </div>
                            </div>

                            <!-- Step 2: Define Units -->
                            <div class="mb-8">
                                <h3 class="text-lg font-medium text-gray-900 border-b-2 border-purple-100 pb-2 mb-6 flex items-center">
                                    <span class="bg-purple-100 text-purple-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">3</span>
                                    Define Additional Units (Optional)
                                </h3>
                                <div id="units_container" class="space-y-4">
                                    <?php $__currentLoopData = $product->productUnits->where('is_base', false); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $unit): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <div class="unit-row flex gap-4 items-start bg-purple-50 p-4 rounded-md border border-purple-100 mt-2" data-index="<?php echo e($index); ?>">
                                            <div class="w-1/3">
                                                <label class="block text-xs font-medium text-gray-500 mb-1">Unit Name</label>
                                                <input type="text" name="product_units[<?php echo e($index); ?>][name]" class="unit-name mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-purple-500 focus:ring-purple-500" placeholder="e.g. Case" value="<?php echo e($unit->name); ?>">
                                            </div>
                                            <div class="w-1/3">
                                                <label class="block text-xs font-medium text-gray-500 mb-1">Conversion (1 Unit = X Base)</label>
                                                <input type="number" step="0.01" name="product_units[<?php echo e($index); ?>][conversion_factor]" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-purple-500 focus:ring-purple-500" placeholder="e.g. 24" value="<?php echo e($unit->conversion_factor); ?>">
                                            </div>
                                            <div class="w-1/4 pt-6 flex gap-4">
                                                <label class="inline-flex items-center">
                                                    <input type="checkbox" name="product_units[<?php echo e($index); ?>][is_sale]" class="form-checkbox h-4 w-4 text-purple-600 rounded focus:ring-purple-500" <?php echo e($unit->is_sale ? 'checked' : ''); ?>>
                                                    <span class="ml-2 text-xs text-gray-700">For Sale</span>
                                                </label>
                                            </div>
                                            <div class="pt-6">
                                                <button type="button" class="remove-unit text-red-400 hover:text-red-600 transition-colors">
                                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                                </button>
                                            </div>
                                        </div>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </div>
                                <div class="mt-4">
                                    <button type="button" id="add_unit_btn" class="inline-flex items-center px-3 py-2 border border-purple-300 shadow-sm text-sm leading-4 font-medium rounded-md text-purple-700 bg-white hover:bg-purple-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500">
                                        + Add Unit (e.g. Case, Pack)
                                    </button>
                                </div>
                            </div>

                            <!-- Step 3: Generate & Price -->
                            <div class="mb-8">
                                <div class="flex justify-between items-center border-b-2 border-gray-100 pb-2 mb-6">
                                    <h3 class="text-lg font-medium text-gray-900 flex items-center">
                                        <span class="bg-gray-200 text-gray-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">4</span>
                                        Variant Matrix & Pricing
                                    </h3>
                                    <div class="flex gap-2">
                                        <button type="button" id="add_manual_variant_btn" class="inline-flex items-center px-3 py-2 bg-blue-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-blue-700 active:bg-blue-900 focus:outline-none focus:ring ring-blue-300 disabled:opacity-25 transition ease-in-out duration-150">
                                            + Add Single Variant
                                        </button>
                                        <button type="button" onclick="autoGenerateAllSKUs()" class="inline-flex items-center px-3 py-2 bg-green-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-green-700 active:bg-green-900 focus:outline-none focus:border-green-900 focus:ring ring-green-300 disabled:opacity-25 transition ease-in-out duration-150">
                                            Generate All SKUs
                                        </button>
                                        <button type="button" id="generate_variants_btn" class="inline-flex items-center px-4 py-2 bg-indigo-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 disabled:opacity-25 transition ease-in-out duration-150">
                                            Regenerate Matrix
                                        </button>
                                    </div>
                                </div>
                                <p class="text-xs text-red-500 mb-4">* Warning: Regenerating variants may reset IDs if attributes change significantly. Ensure you verify pricing before saving.</p>

                                <div class="overflow-x-auto shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
                                    <table id="variants_table" class="min-w-full divide-y divide-gray-300" style="<?php echo e($product->has_variants ? '' : 'display: none;'); ?>">
                                        <thead class="bg-gray-50">
                                            <tr>
                                                <th scope="col" class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">Variant</th>
                                                <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">SKU</th>
                                                <th scope="col" class="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Pricing (Per Unit)</th>
                                                <th scope="col" class="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">Stock (Base)</th>
                                                <th scope="col" class="relative py-3.5 pl-3 pr-4 sm:pr-6">
                                                    <span class="sr-only">Delete</span>
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-200 bg-white">
                                            <?php if($product->has_variants): ?>
                                                <?php $__currentLoopData = $product->variants; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $vIndex => $variant): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <tr class="hover:bg-gray-50 transition-colors">
                                                        <td class="py-4 pl-4 pr-3 text-sm align-top sm:pl-6">
                                                            <input type="text" name="variants[<?php echo e($vIndex); ?>][name]" value="<?php echo e($variant->name); ?>" class="font-medium text-gray-900 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm mb-1" placeholder="Variant Name">
                                                            <input type="hidden" name="variants[<?php echo e($vIndex); ?>][id]" value="<?php echo e($variant->id); ?>">
                                                            <div class="text-xs text-gray-500 space-y-1 mt-1">
                                                                <?php $__currentLoopData = $variant->attributes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $attrIndex => $attr): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                    <div>
                                                                        <span class="font-medium text-gray-600"><?php echo e($attr->name); ?></span>: <span class="font-semibold text-gray-800"><?php echo e($attr->value); ?></span>
                                                                        <input type="hidden" name="variants[<?php echo e($vIndex); ?>][attributes][<?php echo e($attrIndex); ?>][name]" value="<?php echo e($attr->name); ?>">
                                                                        <input type="hidden" name="variants[<?php echo e($vIndex); ?>][attributes][<?php echo e($attrIndex); ?>][value]" value="<?php echo e($attr->value); ?>">
                                                                    </div>
                                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                            </div>
                                                        </td>
                                                        <td class="px-3 py-4 text-sm align-top">
                                                            <div class="flex gap-2">
                                                                <input type="text" name="variants[<?php echo e($vIndex); ?>][sku]" value="<?php echo e($variant->sku); ?>" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md" placeholder="Auto-generated SKU">
                                                                <button type="button" onclick="generateSKU(<?php echo e($vIndex); ?>)" class="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600">
                                                                    Generate
                                                                </button>
                                                            </div>
                                                        </td>
                                                        <td class="px-3 py-4 text-sm align-top">
                                                            <div class="space-y-3">
                                                                <?php $__currentLoopData = $variant->prices; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $priceIndex => $price): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                    <div class="flex gap-2 items-center <?php echo e($price->productUnit->is_base ?? false ? 'bg-gray-50 border-gray-200' : 'bg-purple-50 border-purple-100'); ?> p-2 rounded border">
                                                                        <span class="text-xs font-bold w-12 <?php echo e($price->productUnit->is_base ?? false ? 'text-gray-700' : 'text-purple-700'); ?> uppercase"><?php echo e($price->productUnit->name); ?></span>
                                                                        <input type="hidden" name="variants[<?php echo e($vIndex); ?>][prices][<?php echo e($priceIndex); ?>][unit_name]" value="<?php echo e($price->productUnit->name); ?>">
                                                                        <input type="number" step="0.01" name="variants[<?php echo e($vIndex); ?>][prices][<?php echo e($priceIndex); ?>][price]" value="<?php echo e($price->price); ?>" placeholder="Price" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                                                        <input type="number" step="0.01" name="variants[<?php echo e($vIndex); ?>][prices][<?php echo e($priceIndex); ?>][cost]" value="<?php echo e($price->cost); ?>" placeholder="Cost" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                                                    </div>
                                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                            </div>
                                                        </td>
                                                        <td class="px-3 py-4 text-sm align-top">
                                                            <input type="number" name="variants[<?php echo e($vIndex); ?>][stock]" value="<?php echo e($variant->stock); ?>" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 mx-auto sm:text-sm border-gray-300 rounded-md">
                                                        </td>
                                                        <td class="relative py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6 align-top">
                                                            <button type="button" class="remove-variant text-red-400 hover:text-red-600 transition-colors">
                                                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                                            </button>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                    <div id="variants_placeholder" class="text-center py-12 px-6 text-gray-500 bg-gray-50 border-t border-gray-100" style="<?php echo e($product->has_variants ? 'display: none;' : ''); ?>">
                                        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.384-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"></path></svg>
                                        <p class="mt-2 text-sm">Define attributes above and click "Generate Variants" to create the product matrix.</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="flex items-center justify-end mt-8 border-t pt-6">
                            <a href="<?php echo e(route('tenant.products.index')); ?>" class="text-gray-500 hover:text-gray-700 font-medium mr-6 transition-colors">Cancel</a>
                            <button type="submit" class="inline-flex items-center px-6 py-3 bg-green-600 border border-transparent rounded-md font-semibold text-base text-white uppercase tracking-widest hover:bg-green-700 active:bg-green-900 focus:outline-none focus:border-green-900 focus:ring ring-green-300 disabled:opacity-25 transition ease-in-out duration-150 shadow-lg">
                                Update Product
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery CDN -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        $(document).ready(function() {
            // --- Debug Information ---
            console.log('jQuery loaded');
            console.log('Simple section exists:', $('#simple_product_section').length > 0);
            console.log('Complex section exists:', $('#complex_product_section').length > 0);
            console.log('Checkbox exists:', $('#has_variants_checkbox').length > 0);
            console.log('Initial checkbox state:', $('#has_variants_checkbox').is(':checked'));
            
            // --- Product Image Upload Preview ---
            $('#product-image-upload').change(function() {
                var file = this.files[0];
                var fileName = $(this).val().split('\\').pop();
                
                if (file) {
                    // Update label text
                    $(this).parent().find('span').text(fileName);
                    $(this).closest('.border-dashed').addClass('border-green-400 bg-green-50');
                    
                    // Show preview
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        $('#image-preview img').attr('src', e.target.result);
                        $('#image-preview').removeClass('hidden');
                    }
                    reader.readAsDataURL(file);
                }
            });

            // --- Toggle Simple/Complex Form ---
            $('#has_variants_checkbox').change(function() {
                if ($(this).is(':checked')) {
                    $('#simple_product_section').slideUp(200);
                    $('#complex_product_section').slideDown(200);
                    $('#has_variants_input').val(1);
                    
                    // Show table if it has rows, otherwise show placeholder
                    if ($('#variants_table tbody tr').length > 0) {
                        $('#variants_table').show();
                        $('#variants_placeholder').hide();
                    } else {
                        $('#variants_table').hide();
                        $('#variants_placeholder').show();
                    }
                } else {
                    $('#simple_product_section').slideDown(200);
                    $('#complex_product_section').slideUp(200);
                    $('#has_variants_input').val(0);
                }
            });

            // --- Manual Variant Addition ---
            $('#add_manual_variant_btn').click(function() {
                const tbody = $('#variants_table tbody');
                const vIndex = tbody.find('tr').length;
                
                $('#variants_table').show();
                $('#variants_placeholder').hide();

                const productName = $('#product_name').val().trim() || 'Product';
                const skuPrefix = productName.toUpperCase().substring(0, 3);
                const sku = `${skuPrefix}-${Math.floor(Math.random() * 10000)}`;
                const baseUnitName = $('#base_unit option:selected').data('name') || 'Base Unit';
                
                // Get Custom Units
                const customUnits = [];
                $('#units_container .unit-row').each(function() {
                    const uName = $(this).find('.unit-name').val().trim();
                    if (uName) customUnits.push(uName);
                });

                let html = `<tr class="hover:bg-gray-50 transition-colors">`;
                
                // Name
                html += `<td class="py-4 pl-4 pr-3 text-sm align-top sm:pl-6">
                            <input type="text" name="variants[${vIndex}][name]" value="${productName} - New" class="font-medium text-gray-900 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm mb-1">
                            <div class="text-xs text-gray-400 italic">Manual entry (No attributes)</div>
                         </td>`;

                // SKU
                html += `<td class="px-3 py-4 text-sm align-top">
                            <div class="flex gap-2">
                                <input type="text" name="variants[${vIndex}][sku]" value="${sku}" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md">
                                <button type="button" onclick="generateSKU(${vIndex})" class="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600">Gen</button>
                            </div>
                         </td>`;

                // Pricing
                html += `<td class="px-3 py-4 text-sm align-top">
                            <div class="space-y-3">
                                <div class="flex gap-2 items-center bg-gray-50 p-2 rounded border border-gray-200">
                                    <span class="text-xs font-bold w-12 text-gray-700 uppercase">${baseUnitName}</span>
                                    <input type="hidden" name="variants[${vIndex}][prices][0][unit_name]" value="${baseUnitName}">
                                    <input type="number" step="0.01" name="variants[${vIndex}][prices][0][price]" value="" placeholder="Price" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                    <input type="number" step="0.01" name="variants[${vIndex}][prices][0][cost]" value="" placeholder="Cost" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                </div>`;
                
                customUnits.forEach((uName, uIndex) => {
                    const priceIndex = uIndex + 1;
                    html += `<div class="flex gap-2 items-center bg-purple-50 p-2 rounded border border-purple-100">
                                <span class="text-xs font-bold w-12 text-purple-700 uppercase">${uName}</span>
                                <input type="hidden" name="variants[${vIndex}][prices][${priceIndex}][unit_name]" value="${uName}">
                                <input type="number" step="0.01" name="variants[${vIndex}][prices][${priceIndex}][price]" value="" placeholder="Price" class="shadow-sm focus:ring-purple-500 focus:border-purple-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                <input type="number" step="0.01" name="variants[${vIndex}][prices][${priceIndex}][cost]" value="" placeholder="Cost" class="shadow-sm focus:ring-purple-500 focus:border-purple-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                             </div>`;
                });

                html += `   </div>
                         </td>`;

                // Stock
                html += `<td class="px-3 py-4 text-sm align-top text-center">
                            <input type="number" name="variants[${vIndex}][stock]" value="0" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 mx-auto sm:text-sm border-gray-300 rounded-md">
                         </td>`;

                // Remove
                html += `<td class="relative py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6 align-top">
                            <button type="button" class="remove-variant text-red-400 hover:text-red-600 transition-colors">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                            </button>
                         </td>`;

                html += `</tr>`;
                tbody.append(html);
            });

            // --- Attributes Management ---
            function addAttributeRow() {
                const row = `
                    <div class="attribute-row flex gap-4 items-start bg-indigo-50 p-4 rounded-md border border-indigo-100 mt-2">
                        <div class="w-1/3">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Attribute Name</label>
                            <input type="text" class="attribute-name mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="e.g. Size">
                        </div>
                        <div class="w-1/2">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Values (comma separated)</label>
                            <input type="text" class="attribute-values mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="e.g. Small, Medium, Large">
                        </div>
                        <div class="pt-6">
                            <button type="button" class="remove-attribute text-red-400 hover:text-red-600 transition-colors">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                            </button>
                        </div>
                    </div>
                `;
                $('#attributes_container').append(row);
            }

            $('#add_attribute_btn').click(function() {
                addAttributeRow();
            });

            $(document).on('click', '.remove-attribute', function() {
                if ($('#attributes_container .attribute-row').length > 1) {
                    $(this).closest('.attribute-row').remove();
                } else {
                    const row = $(this).closest('.attribute-row');
                    row.find('input').val('');
                }
            });

            // --- Units Management ---
            function addUnitRow() {
                const index = $('#units_container .unit-row').length + <?php echo e($product->productUnits->where('is_base', false)->count()); ?>; // Offset by existing
                const row = `
                    <div class="unit-row flex gap-4 items-start bg-purple-50 p-4 rounded-md border border-purple-100 mt-2" data-index="${index}">
                        <div class="w-1/3">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Unit Name</label>
                            <input type="text" name="product_units[${index}][name]" class="unit-name mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-purple-500 focus:ring-purple-500" placeholder="e.g. Case">
                        </div>
                        <div class="w-1/3">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Conversion (1 Unit = X Base)</label>
                            <input type="number" step="0.01" name="product_units[${index}][conversion_factor]" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm text-sm focus:border-purple-500 focus:ring-purple-500" placeholder="e.g. 24">
                        </div>
                        <div class="w-1/4 pt-6 flex gap-4">
                            <label class="inline-flex items-center">
                                <input type="checkbox" name="product_units[${index}][is_sale]" class="form-checkbox h-4 w-4 text-purple-600 rounded focus:ring-purple-500" checked>
                                <span class="ml-2 text-xs text-gray-700">For Sale</span>
                            </label>
                        </div>
                        <div class="pt-6">
                            <button type="button" class="remove-unit text-red-400 hover:text-red-600 transition-colors">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                            </button>
                        </div>
                    </div>
                `;
                $('#units_container').append(row);
            }

            $('#add_unit_btn').click(function() {
                addUnitRow();
            });

            $(document).on('click', '.remove-unit', function() {
                $(this).closest('.unit-row').remove();
                // reindexUnits(); // Not strictly necessary if we rely on random indices, but cleaner
            });

            // --- Generate Variants ---
            function cartesian(args) {
                var r = [], max = args.length - 1;
                function helper(arr, i) {
                    for (var j = 0, l = args[i].length; j < l; j++) {
                        var a = arr.slice(0); // clone arr
                        a.push(args[i][j]);
                        if (i == max)
                            r.push(a);
                        else
                            helper(a, i + 1);
                    }
                }
                helper([], 0);
                return r;
            }

            $('#generate_variants_btn').click(function() {
                if(!confirm('Regenerating variants will try to match existing pricing and stock. New combinations will be added, and missing ones removed. Continue?')) return;

                const attributes = [];
                $('#attributes_container .attribute-row').each(function() {
                    const name = $(this).find('.attribute-name').val().trim();
                    const valuesStr = $(this).find('.attribute-values').val().trim();
                    
                    if (name && valuesStr) {
                        const values = valuesStr.split(',').map(v => v.trim()).filter(v => v);
                        if (values.length > 0) {
                            attributes.push({ name: name, values: values });
                        }
                    }
                });

                if (attributes.length === 0) {
                    alert('Please define at least one attribute with values.');
                    return;
                }

                // 1. Capture existing variants data
                const existingVariantsMap = {};
                $('#variants_table tbody tr').each(function() {
                    const row = $(this);
                    const id = row.find('input[name*="[id]"]').val();
                    const name = row.find('input[name*="[name]"]').val();
                    const sku = row.find('input[name*="[sku]"]').val();
                    const stock = row.find('input[name*="[stock]"]').val();
                    
                    // Capture prices
                    const prices = [];
                    row.find('.space-y-3 > div').each(function() {
                        const priceRow = $(this);
                        prices.push({
                            unit_name: priceRow.find('input[name*="[unit_name]"]').val(),
                            price: priceRow.find('input[name*="[price]"]').val(),
                            cost: priceRow.find('input[name*="[cost]"]').val()
                        });
                    });

                    // Capture attributes to create a unique key
                    const attrs = [];
                    row.find('input[name*="[attributes]"]').each(function() {
                        const input = $(this);
                        if (input.attr('name').includes('[name]')) {
                            const valInput = row.find(`input[name="${input.attr('name').replace('[name]', '[value]')}"]`);
                            attrs.push({ name: input.val(), value: valInput.val() });
                        }
                    });

                    // Sort attributes by name to ensure consistent key
                    attrs.sort((a, b) => a.name.localeCompare(b.name));
                    const key = attrs.map(a => `${a.name}:${a.value}`).join('|');
                    
                    existingVariantsMap[key] = {
                        id: id,
                        name: name,
                        sku: sku,
                        stock: stock,
                        prices: prices,
                        attrs: attrs
                    };
                });

                // 2. Generate combinations
                const combinations = cartesian(attributes.map(a => a.values));
                const tbody = $('#variants_table tbody');
                tbody.empty();

                if (combinations.length > 0) {
                    $('#variants_table').show();
                    $('#variants_placeholder').hide();
                } else {
                    $('#variants_table').hide();
                    $('#variants_placeholder').show();
                    return;
                }

                // 3. Get Custom Units
                const customUnits = [];
                $('#units_container .unit-row').each(function() {
                    const uName = $(this).find('.unit-name').val().trim();
                    if (uName) customUnits.push(uName);
                });

                const productName = $('#product_name').val().trim();
                const skuPrefix = productName ? productName.toUpperCase().substring(0, 3) : 'PRD';
                const baseUnitName = $('#base_unit option:selected').data('name') || 'Base Unit';

                // 4. Render new matrix
                combinations.forEach((combo, vIndex) => {
                    const values = Array.isArray(combo) ? combo : [combo];
                    const variantName = values.join(' / ');
                    
                    // Create key for this combo
                    const currentAttrs = values.map((val, idx) => ({ name: attributes[idx].name, value: val }));
                    currentAttrs.sort((a, b) => a.name.localeCompare(b.name));
                    const key = currentAttrs.map(a => `${a.name}:${a.value}`).join('|');
                    
                    const existing = existingVariantsMap[key];
                    
                    // Use existing name or generate new one
                    let currentName = existing ? existing.name : variantName;
                    
                    // Generate or use existing SKU
                    let sku = existing ? existing.sku : '';
                    if (!sku) {
                        const skuSuffix = values.map(v => v.toUpperCase().substring(0, 3)).join('-');
                        sku = `${skuPrefix}-${skuSuffix}-${Math.floor(Math.random() * 1000)}`;
                    }

                    let html = `<tr class="hover:bg-gray-50 transition-colors">`;
                    
                    // Variant Name & Hidden Inputs
                    html += `<td class="py-4 pl-4 pr-3 text-sm align-top sm:pl-6">
                                <input type="text" name="variants[${vIndex}][name]" value="${currentName}" class="font-medium text-gray-900 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm mb-1" placeholder="Variant Name">
                                ${existing && existing.id ? `<input type="hidden" name="variants[${vIndex}][id]" value="${existing.id}">` : ''}
                                <div class="text-xs text-gray-500 space-y-1 mt-1">`;
                    
                    values.forEach((val, idx) => {
                        html += `<div>
                                    <span class="font-medium text-gray-600">${attributes[idx].name}</span>: <span class="font-semibold text-gray-800">${val}</span>
                                    <input type="hidden" name="variants[${vIndex}][attributes][${idx}][name]" value="${attributes[idx].name}">
                                    <input type="hidden" name="variants[${vIndex}][attributes][${idx}][value]" value="${val}">
                                 </div>`;
                    });
                    html += `   </div>
                             </td>`;

                    // SKU
                    html += `<td class="px-3 py-4 text-sm align-top">
                                <div class="flex gap-2">
                                    <input type="text" name="variants[${vIndex}][sku]" value="${sku}" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md">
                                    <button type="button" onclick="generateSKU(${vIndex})" class="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600">
                                        Gen
                                    </button>
                                </div>
                             </td>`;

                    // Pricing
                    html += `<td class="px-3 py-4 text-sm align-top">
                                <div class="space-y-3">
                                    <!-- Base Unit -->
                                    <div class="flex gap-2 items-center bg-gray-50 p-2 rounded border border-gray-200">
                                        <span class="text-xs font-bold w-12 text-gray-700 uppercase">${baseUnitName}</span>
                                        <input type="hidden" name="variants[${vIndex}][prices][0][unit_name]" value="${baseUnitName}">`;
                    
                    let basePrice = '';
                    let baseCost = '';
                    if (existing) {
                        const bp = existing.prices.find(p => p.unit_name === baseUnitName);
                        if (bp) {
                            basePrice = bp.price;
                            baseCost = bp.cost;
                        }
                    }

                    html += `           <input type="number" step="0.01" name="variants[${vIndex}][prices][0][price]" value="${basePrice}" placeholder="Price" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                        <input type="number" step="0.01" name="variants[${vIndex}][prices][0][cost]" value="${baseCost}" placeholder="Cost" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                    </div>`;
                    
                    // Custom Units
                    customUnits.forEach((uName, uIndex) => {
                        const priceIndex = uIndex + 1;
                        let uPrice = '';
                        let uCost = '';
                        if (existing) {
                            const up = existing.prices.find(p => p.unit_name === uName);
                            if (up) {
                                uPrice = up.price;
                                uCost = up.cost;
                            }
                        }

                        html += `<div class="flex gap-2 items-center bg-purple-50 p-2 rounded border border-purple-100">
                                    <span class="text-xs font-bold w-12 text-purple-700 uppercase">${uName}</span>
                                    <input type="hidden" name="variants[${vIndex}][prices][${priceIndex}][unit_name]" value="${uName}">
                                    <input type="number" step="0.01" name="variants[${vIndex}][prices][${priceIndex}][price]" value="${uPrice}" placeholder="Price" class="shadow-sm focus:ring-purple-500 focus:border-purple-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                    <input type="number" step="0.01" name="variants[${vIndex}][prices][${priceIndex}][cost]" value="${uCost}" placeholder="Cost" class="shadow-sm focus:ring-purple-500 focus:border-purple-500 block w-20 sm:text-xs border-gray-300 rounded-md">
                                 </div>`;
                    });

                    html += `   </div>
                             </td>`;

                    // Stock
                    const stock = existing ? existing.stock : 0;
                    html += `<td class="px-3 py-4 text-sm align-top text-center">
                                <input type="number" name="variants[${vIndex}][stock]" value="${stock}" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-20 mx-auto sm:text-sm border-gray-300 rounded-md">
                             </td>`;

                    // Remove Action
                    html += `<td class="relative py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6 align-top">
                                <button type="button" class="remove-variant text-red-400 hover:text-red-600 transition-colors">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                </button>
                             </td>`;

                    html += `</tr>`;
                    tbody.append(html);
                });
            });

            $(document).on('click', '.remove-variant', function() {
                $(this).closest('tr').remove();
                if ($('#variants_table tbody tr').length === 0) {
                    $('#variants_table').hide();
                    $('#variants_placeholder').show();
                }
            });
        });

        // --- SKU Generation Function ---
        function generateSKU(variantIndex) {
            const productName = '<?php echo e($product->name); ?>';
            const variantInputs = document.querySelectorAll(`input[name^="variants[${variantIndex}][attributes]"]`);
            
            // Create base SKU from product name
            let baseSKU = productName
                .toUpperCase()
                .replace(/[^A-Z0-9]/g, '')
                .substring(0, 6);
            
            // Add variant attributes
            let variantSuffix = '';
            variantInputs.forEach(input => {
                if (input.name.includes('value')) {
                    variantSuffix += input.value.toUpperCase().replace(/[^A-Z0-9]/g, '').substring(0, 3);
                }
            });
            
            // Generate random number
            const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
            
            // Combine to create SKU
            const generatedSKU = baseSKU + variantSuffix + randomNum;
            
            // Set the SKU input value
            const skuInput = document.querySelector(`input[name="variants[${variantIndex}][sku]"]`);
            if (skuInput) {
                skuInput.value = generatedSKU;
                skuInput.classList.add('bg-green-50', 'border-green-400');
                setTimeout(() => {
                    skuInput.classList.remove('bg-green-50', 'border-green-400');
                }, 2000);
            }
        }

        // Auto-generate SKUs for new variants
        function autoGenerateAllSKUs() {
            const variantRows = document.querySelectorAll('[data-variant-row]');
            variantRows.forEach((row, index) => {
                const variantIndex = row.dataset.variantIndex;
                if (variantIndex) {
                    generateSKU(variantIndex);
                }
            });
        }
    </script>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal3f11930a8702d3d700513f5d743b90ca)): ?>
<?php $attributes = $__attributesOriginal3f11930a8702d3d700513f5d743b90ca; ?>
<?php unset($__attributesOriginal3f11930a8702d3d700513f5d743b90ca); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal3f11930a8702d3d700513f5d743b90ca)): ?>
<?php $component = $__componentOriginal3f11930a8702d3d700513f5d743b90ca; ?>
<?php unset($__componentOriginal3f11930a8702d3d700513f5d743b90ca); ?>
<?php endif; ?>
<?php /**PATH D:\laragon\www\Laravel_gorsary\resources\views/tenant/products/edit.blade.php ENDPATH**/ ?>