

<?php $__env->startSection('title', 'Create Variant Product'); ?>

<?php $__env->startSection('styles'); ?>
<style>
.admin-section-header {
    margin-bottom: 1rem;
    padding-bottom: 0.5rem;
    border-bottom: 2px solid #e9ecef;
}

.admin-section-header h5 {
    color: #495057;
    font-weight: 600;
    margin: 0;
    font-size: 0.95rem;
}

.admin-section-header i {
    margin-right: 0.5rem;
    color: #6c757d;
}

.variant-combinations-table {
    max-height: 400px;
    overflow-y: auto;
    font-size: 0.875rem;
}

.variant-combinations-table table {
    margin-bottom: 0;
}

.variant-combinations-table th {
    position: sticky;
    top: 0;
    background: #f8f9fa;
    z-index: 10;
    font-size: 0.8rem;
    padding: 0.5rem;
}

.variant-combinations-table td {
    padding: 0.5rem;
    vertical-align: middle;
}

.variant-combinations-table input,
.variant-combinations-table select {
    font-size: 0.85rem;
    padding: 0.25rem 0.5rem;
}

.attribute-selection {
    background: #f8f9fa;
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1rem;
}

.attribute-group {
    margin-bottom: 3rem;
}

.attribute-group:last-child {
    margin-bottom: 0;
}

.attribute-checkboxes {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-top: 0.5rem;
}

.attribute-checkbox-item {
    display: flex;
    align-items: center;
    padding: 0.4rem 0.75rem;
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s;
    
}

.attribute-checkbox-item:hover {
    border-color: #0d6efd;
    background: #f0f7ff;
}

.attribute-checkbox-item input[type="checkbox"] {
    margin-right: 0.5rem;
    cursor: pointer;
}

.attribute-checkbox-item.selected {
    background: #0d6efd;
    color: white;
    border-color: #0d6efd;
}

.combinations-preview {
    background: #fff;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 1rem;
    margin-top: 1rem;
    max-height: 300px;
    overflow-y: auto;
}

.combination-badge {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    background: #e9ecef;
    border-radius: 4px;
    font-size: 0.8rem;
    margin: 0.25rem;
}

.form-compact .row {
    margin-bottom: 0.5rem;
}

.form-compact .mb-3 {
    margin-bottom: 0.75rem !important;
}

.variants-section {
    margin-top: 1.5rem;
}

.bulk-actions {
    background: #f8f9fa;
    padding: 0.75rem;
    border-radius: 6px;
    margin-bottom: 1rem;
    display: flex;
    gap: 1rem;
    align-items: center;
    flex-wrap: wrap;
}

.bulk-actions input {
    max-width: 120px;
}
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="admin-page-header">
    <h1>Create Variant Product</h1>
    <a href="<?php echo e(route('admin.products.index', ['type' => 'variant'])); ?>" class="admin-btn-primary">Back</a>
</div>


<form action="<?php echo e(route('admin.products.variant.store')); ?>" method="POST" enctype="multipart/form-data" id="variantProductForm">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="product_type" value="variant">

    <!-- Basic Information Section -->
  <div class="admin-card m-3">
    <div class="card-body">
            <div class="admin-section-header">
                <h5><i class="bi bi-info-circle"></i> Basic Information</h5>
            </div>
            <div class="row form-compact">
                <div class="col-md-6 mb-3">
                    <label class="admin-form-label">Product Name *</label>
                    <input type="text" name="name" class="admin-form-control form-control form-control-sm  form-control-border" value="<?php echo e(old('name')); ?>" required placeholder="Enter product name">
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Category *</label>
                    <select name="category_id" class="admin-form-control form-select form-select-sm" required>
                        <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(old('category_id') == $category->id ? 'selected' : ''); ?>>
                                <?php echo e($category->name); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Brand</label>
                    <select name="brand_id" class="admin-form-control form-select form-select-sm">
                        <option value="">Select Brand</option>
                        <?php $__currentLoopData = $brands; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $brand): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php
                                $isSelected = false;
                                if (old('brand_id')) {
                                    $isSelected = old('brand_id') == $brand->id;
                                } else {
                                    $isSelected = $loop->first;
                                }
                            ?>
                            <option value="<?php echo e($brand->id); ?>" <?php echo e($isSelected ? 'selected' : ''); ?>>
                                <?php echo e($brand->name); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Unit</label>
                    <select name="unit_id" class="admin-form-control form-select form-select-sm">
                        <option value="">Select Unit</option>
                        <?php $__currentLoopData = $units; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $unit): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($unit->id); ?>" <?php echo e(old('unit_id') == $unit->id ? 'selected' : ''); ?>>
                                <?php echo e(ucfirst($unit->name)); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Tax</label>
                    <select name="tax_id" class="admin-form-control form-select form-select-sm">
                        <option value="">No Tax</option>
                        <?php $__currentLoopData = $taxes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $tax): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php
                                $isSelected = false;
                                if (old('tax_id')) {
                                    $isSelected = old('tax_id') == $tax->id;
                                } else {
                                    $isSelected = $loop->first;
                                }
                            ?>
                            <option value="<?php echo e($tax->id); ?>" <?php echo e($isSelected ? 'selected' : ''); ?>>
                                <?php echo e($tax->name); ?> (<?php echo e(number_format($tax->rate, 2)); ?>%)
                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Barcode</label>
                    <div class="input-group input-group-sm">
                        <input type="text" name="barcode" id="barcode" class="admin-form-control form-control form-control-sm" value="<?php echo e(old('barcode')); ?>" maxlength="8" placeholder="Auto-generated" style="font-weight: 600; font-family: 'Courier New', monospace;">
                        <button type="button" class="btn btn-outline-secondary" onclick="generateNewBarcode()" title="Generate">
                            <i class="bi bi-arrow-clockwise"></i>
                        </button>
                    </div>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Product Image</label>
                    <input type="file" name="image" class="admin-form-control form-control form-control-sm" accept="image/jpeg,image/png,image/jpg,image/webp">
                </div>

                <div class="col-md-6 mb-3">
                    <label class="admin-form-label">Product Tags</label>
                    <textarea name="tags" id="productTagsTextarea" class="admin-form-control form-control form-control-sm" rows="1" placeholder="Type keywords and press Enter..."><?php echo e(old('tags')); ?></textarea>
                    <div class="tags-display" id="tagsDisplay"></div>
                </div>

                <div class="col-md-6 mb-3">
                    <label class="admin-form-label">Short Description</label>
                    <textarea name="short_desc" class="admin-form-control form-control form-control-sm" rows="2"><?php echo e(old('short_desc')); ?></textarea>
                </div>

                <div class="col-md-3 mb-3">
                    <label class="admin-form-label">Shipping Days</label>
                    <input type="number" name="shipping_days" class="admin-form-control form-control form-control-sm" value="<?php echo e(old('shipping_days', \App\Models\Setting::get('default_shipping_days'))); ?>" min="0" placeholder="e.g. 3">
                </div>

                <div class="col-md-3 mb-3">
                    <div class="form-check form-check-sm">
                        <input type="hidden" name="is_active" value="0">
                        <input type="checkbox" name="is_active" class="form-check-input" id="isActive" value="1" <?php echo e(old('is_active', true) ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="isActive">Active</label>
                    </div>
                    
                </div>

                <div class="col-md-3 mb-3">
                    <div class="form-check form-check-sm">
                        <input type="hidden" name="is_featured" value="0">
                        <input type="checkbox" name="is_featured" class="form-check-input" id="isFeatured" value="1" <?php echo e(old('is_featured') ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="isFeatured">Featured</label>
                    </div>
                </div>

                <div class="col-md-3 mb-3">
                    <div class="form-check form-check-sm">
                        <input type="hidden" name="is_verified" value="0">
                        <input type="checkbox" name="is_verified" class="form-check-input" id="isVerified" value="1" <?php echo e(old('is_verified') ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="isVerified">Verified</label>
                    </div>
                </div>

                <div class="col-md-3 mb-3">
                    <div class="form-check form-check-sm">
                        <input type="checkbox" name="is_prebooking" class="form-check-input" id="isPrebooking" value="1" <?php echo e(old('is_prebooking') ? 'checked' : ''); ?>>
                        <label class="form-check-label" for="isPrebooking">Pre Booking</label>
                    </div>
                </div>

                <div class="col-md-12 mb-3">
                    <label class="admin-form-label">Show Product In *</label>
                    <div class="d-flex flex-wrap gap-3 mt-1">
                        <div class="form-check form-check-sm">
                            <input class="form-check-input" type="radio" name="channel_visibility" id="channelBoth" value="both" <?php echo e(old('channel_visibility', 'both') === 'both' ? 'checked' : ''); ?>>
                            <label class="form-check-label" for="channelBoth">Both POS and Website</label>
                        </div>
                        <div class="form-check form-check-sm">
                            <input class="form-check-input" type="radio" name="channel_visibility" id="channelWebsiteOnly" value="website_only" <?php echo e(old('channel_visibility') === 'website_only' ? 'checked' : ''); ?>>
                            <label class="form-check-label" for="channelWebsiteOnly">Only Website</label>
                        </div>
                        <div class="form-check form-check-sm">
                            <input class="form-check-input" type="radio" name="channel_visibility" id="channelPosOnly" value="pos_only" <?php echo e(old('channel_visibility') === 'pos_only' ? 'checked' : ''); ?>>
                            <label class="form-check-label" for="channelPosOnly">Only POS</label>
                        </div>
                    </div>
                </div>
            </div>
            </div>
             </div>

            <!-- Variant Attributes Selection -->
              <div class="admin-card m-3">
    <div class="card-body">
            <div class="admin-section-header mt-3">
                <h5><i class="bi bi-tags"></i> Variant Attributes</h5>
            </div>
            <div class="attribute-selection my-3">
                <p class="text-muted mb-3" style="font-size: 0.875rem;">Select attributes to create variants. All combinations will be generated automatically.</p>
                <?php $__currentLoopData = $attributes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $attribute): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <div class="attribute-group my-3">
                    <label class="admin-form-label fw-bold" style="font-size: 0.9rem;"><?php echo e($attribute->name); ?> *</label>
                    <div class="attribute-checkboxes" data-attribute-id="<?php echo e($attribute->id); ?>" data-attribute-name="<?php echo e($attribute->name); ?>">
                        <?php $__currentLoopData = $attribute->activeValues; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <label class="attribute-checkbox-item me-2 p-2">
                            <input type="checkbox"
                                   name="attributes[<?php echo e($attribute->id); ?>][]" 
                                   value="<?php echo e($value->id); ?>" 
                                   data-attribute-id="<?php echo e($attribute->id); ?>"
                                   data-attribute-name="<?php echo e($attribute->name); ?>"
                                   data-value-name="<?php echo e($value->value); ?>"
                                   onchange="updateVariantCombinations()">
                            <span><?php echo e($value->value); ?></span>
                        </label>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>
                </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>

            <!-- Variant Combinations Preview -->
            <div id="combinationsPreview" style="display: none;">
                <div class="admin-section-header my-3">
                    <h5><i class="bi bi-list-ul"></i> Variant Combinations (<span id="combinationCount">0</span>)</h5>
                </div>
                <div class="combinations-preview" id="combinationsList"></div>
               </div>
              </div>
              </div>


            <!-- Variants Section -->
     <div class="admin-card m-3">
    <div class="card-body">
            <div class="variants-section" id="variantsSection">
                <div class="admin-section-header">
                    <h5><i class="bi bi-box"></i> Variant Details</h5>
                </div>

                <!-- Bulk Actions -->
  <div class="bulk-actions my-3">
    <strong style="font-size: 0.9rem;">Bulk Apply:</strong>
           <div class=" row align-items-center gap-3 mt-2">
        <div class="col-auto">
            <label class="form-label mb-0" style="font-size: 0.85rem;">Price</label>
            <div class="d-flex gap-2">
                <input type="number" step="0.01" id="bulkPrice"class="form-control form-control-sm rounded-4" style="width:100px;" placeholder="0.00">
                <button type="button" class="btn rounded-4 btn-outline-primary" onclick="applyBulkValue('price')">Apply</button>
            </div>
        </div>

        <div class="col-auto">
            <label class="form-label mb-0" style="font-size: 0.85rem;">MRP</label>
            <div class="d-flex gap-2">
                <input type="number" step="0.01" id="bulkMrp"class="form-control form-control-sm rounded-4" style="width:100px;" placeholder="0.00">
                <button type="button" class="btn rounded-4  btn-outline-primary "onclick="applyBulkValue('mrp')">Apply</button>
            </div>
        </div>

        <div class="col-auto">
            <label class="form-label mb-0" style="font-size: 0.85rem;">Purchase</label>
            <div class="d-flex gap-2">
                <input type="number" step="0.01" id="bulkPurchasePrice"class="form-control form-control-sm rounded-4" style="width:100px;" placeholder="0.00">
                <button type="button" class="btn rounded-4 btn-outline-primary"onclick="applyBulkValue('purchase_price')">Apply</button>
            </div>
        </div>
       
        <div class="col-auto">
            <label class="form-label mb-0" style="font-size: 0.85rem;">Wholesale</label>
            <div class="d-flex gap-2">
                <input type="number" step="0.01" id="bulkWholesalePrice" class="form-control form-control-sm rounded-4" style="width:100px;" placeholder="0.00">
                <button type="button" class="btn btn-outline-primary rounded-4"onclick="applyBulkValue('wholesale_price')">Apply</button>
            </div>
        </div>

        <div class="col-auto">
            <label class="form-label mb-0" style="font-size: 0.85rem;">Stock</label>
            <div class="d-flex gap-2">
                <input type="number" id="bulkOpeningStock"class="form-control form-control-sm rounded-4" style="width:100px;" placeholder="0">
                <button type="button" class="btn rounded-4 btn-outline-primary"onclick="applyBulkValue('opening_stock')">Apply</button>
            </div>
        </div>
   
    </div>

   
</div>


                <!-- Variants Table -->
                <div class="variant-combinations-table ">
                    <table class="table table-bordered table-sm ">
                        <thead>
                            <tr>
                                <th style="width: 200px;">Variant</th>
                                <th style="width: 120px;">SKU</th>
                                <th style="width: 100px;">Price *</th>
                                <th style="width: 100px;">MRP</th>
                                <th style="width: 100px;">Purchase</th>
                                <th style="width: 100px;">Wholesale</th>
                                <th style="width: 80px;">Stock *</th>
                                <th style="width: 90px;">Ship Days</th>
                                <th style="width: 100px;">Barcode</th>
                                <th style="width: 80px;">Image</th>
                            </tr>
                        </thead>
                        <tbody id="variantsTableBody">
                            <!-- Variants will be generated here -->
                        </tbody>
                    </table>
                </div>
            </div>
            </div>
          </div>

            <div class="mt-4">
                <button type="submit" class="admin-btn-primary" id="submitBtn" disabled>
                    <i class="bi bi-check-circle"></i> Create Variant Product & All Variants
                </button>
                <a href="<?php echo e(route('admin.products.index', ['type' => 'variant'])); ?>" class="btn btn-secondary">Cancel</a>
            </div>
            </form>
   

<?php $__env->startPush('styles'); ?>
<style>
    .tags-input-container {
        position: relative;
        margin-bottom: 0.5rem;
    }

    .tags-textarea {
        resize: vertical;
        min-height: 35px;
        height: 35px;
        padding: 0.4rem 0.6rem;
        border: 1px solid var(--admin-border-color);
        border-radius: 6px;
        transition: var(--admin-transition);
        font-size: 0.85rem;
    }

    .tags-display {
        display: flex;
        flex-wrap: wrap;
        gap: 0.4rem;
        margin-top: 0.5rem;
        /* min-height: 28px; */
    }
    .admin-main .btn-sm {
        height: 32px;
    }

    .tag-item {
        display: inline-flex;
        align-items: center;
        gap: 0.4rem;
        background-color: #e9ecef;
        color: #495057;
        padding: 0.3rem 0.6rem;
        border-radius: 16px;
        font-size: 0.8rem;
        font-weight: 500;
    }

    .tag-remove {
        background: none;
        border: none;
        color: #6c757d;
        cursor: pointer;
        padding: 0;
        width: 16px;
        height: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        font-size: 0.75rem;
    }

    .tag-remove:hover {
        background-color: #dc3545;
        color: #ffffff;
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
// Attributes data
const attributesData = <?php echo json_encode($attributes->mapWithKeys(function($attr) {
    return [$attr->id => [
        'name' => $attr->name, 'values' => $attr->activeValues->map(function($val) {
            return ['id' => $val->id, 'value' => $val->value];
        })
    ]];
})) ?>;

let variantCombinations = [];

// Generate all combinations from selected attributes
function generateCombinations() {
    const selectedAttributes = {};
    
    // Collect selected values for each attribute
    document.querySelectorAll('.attribute-checkboxes input[type="checkbox"]:checked').forEach(checkbox => {
        const attrId = checkbox.dataset.attributeId;
        const attrName = checkbox.dataset.attributeName;
        const valueId = checkbox.value;
        const valueName = checkbox.dataset.valueName;
        
        if (!selectedAttributes[attrId]) {
            selectedAttributes[attrId] = {
                name: attrName,
                values: []
            };
        }
        
        selectedAttributes[attrId].values.push({
            id: valueId,
            name: valueName
        });
    });
    
    // Check if at least one attribute has selections
    const attributeIds = Object.keys(selectedAttributes);
    if (attributeIds.length === 0) {
        return [];
    }
    
    // Generate cartesian product of all attribute value combinations
    const attributeArrays = attributeIds.map(attrId => 
        selectedAttributes[attrId].values.map(val => ({
            attributeId: attrId,
            attributeName: selectedAttributes[attrId].name,
            valueId: val.id,
            valueName: val.name
        }))
    );
    
    // Cartesian product function
    function cartesianProduct(arrays) {
        return arrays.reduce((acc, curr) => {
            const result = [];
            acc.forEach(accItem => {
                curr.forEach(currItem => {
                    result.push([...accItem, currItem]);
                });
            });
            return result;
        }, [[]]);
    }
    
    const combinations = cartesianProduct(attributeArrays);
    
    return combinations.map(combo => {
        const variantName = combo.map(item => `${item.attributeName}: ${item.valueName}`).join(' - ');
        const attributeValueIds = combo.map(item => item.valueId);
        
        return {
            name: variantName,
            attributeValueIds: attributeValueIds,
            attributes: combo
        };
    });
}

// Update variant combinations when attributes change
function updateVariantCombinations() {
    variantCombinations = generateCombinations();
    
    const previewDiv = document.getElementById('combinationsPreview');
    const variantsSection = document.getElementById('variantsSection');
    const submitBtn = document.getElementById('submitBtn');
    const countSpan = document.getElementById('combinationCount');
    
    if (variantCombinations.length === 0) {
        previewDiv.style.display = 'none';
        variantsSection.style.display = 'none';
        submitBtn.disabled = true;
        return;
    }
    
    countSpan.textContent = variantCombinations.length;
    previewDiv.style.display = 'block';
    variantsSection.style.display = 'block';
    submitBtn.disabled = false;
    
    // Update preview
    const combinationsList = document.getElementById('combinationsList');
    combinationsList.innerHTML = variantCombinations.map((combo, index) => 
        `<span class="combination-badge">${combo.name}</span>`
    ).join('');
    
    // Generate variants table
    generateVariantsTable();
}

// Generate variants table
function generateVariantsTable() {
    const tbody = document.getElementById('variantsTableBody');
    tbody.innerHTML = '';
    
    variantCombinations.forEach((combo, index) => {
        const row = document.createElement('tr');
        const variantId = `variant_${index}`;
        
        // Generate unique SKU
        const baseSku = document.querySelector('input[name="name"]').value.replace(/\s+/g, '').substring(0, 10).toUpperCase() || 'PROD';
        const sku = `${baseSku}-${index + 1}`;
        
        row.innerHTML = `
            <td>
                <strong style="font-size: 0.85rem;">${combo.name}</strong>
                ${combo.attributeValueIds.map(id => `<input type="hidden" name="variants[${index}][attribute_value_ids][]" value="${id}">`).join('')}
            </td>
            <td>
                <input type="text" name="variants[${index}][sku]" class="form-control form-control-sm rounded-4" value="${sku}" required>
            </td>
            <td>
                <input type="number" step="0.01" name="variants[${index}][price]" class="form-control form-control-sm variant-price rounded-4" value="0" required min="0">
            </td>
            <td>
                <input type="number" step="0.01" name="variants[${index}][mrp]" class="form-control form-control-sm variant-mrp rounded-4" value="0" min="0">
            </td>
            <td>
                <input type="number" step="0.01" name="variants[${index}][purchase_price]" class="form-control form-control-sm variant-purchase_price rounded-4" value="0" min="0">
            </td>
            <td>
                <input type="number" step="0.01" name="variants[${index}][wholesale_price]" class="form-control form-control-sm variant-wholesale_price rounded-4" value="0" min="0">
            </td>
            <td>
                <input type="number" name="variants[${index}][opening_stock]" class="form-control form-control-xl variant-opening_stock rounded-4" value="0" required min="0">
            </td>
            <td>
                <input type="number" name="variants[${index}][shipping_days]" class="form-control form-control-sm variant-shipping_days rounded-4" value="" min="0" placeholder="auto">
            </td>
            <td>
                <input type="text" name="variants[${index}][barcode]" class="form-control form-control-sm rounded-4" maxlength="8" placeholder="Auto" style="font-family: 'Courier New', monospace;">
            </td>
            <td>
                <input type="file" name="variants[${index}][image]" class="form-control form-control-sm rounded-4" accept="image/jpeg,image/png,image/jpg,image/webp">
            </td>
        `;
        
        tbody.appendChild(row);
    });
}

// Convert field name to camelCase (e.g., purchase_price -> PurchasePrice)
function toCamelCase(str) {
    return str.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('');
}

// Bulk apply values
function applyBulkValue(field) {
    const camelField = toCamelCase(field);
    const input = document.getElementById(`bulk${camelField}`);
    if (!input) {
        console.error(`Input not found: bulk${camelField}`);
        return;
    }
    
    const value = input.value;
    
    if (!value && value !== '0') return;
    
    const selector = `.variant-${field}`;
    const inputs = document.querySelectorAll(selector);
    
    if (inputs.length === 0) {
        console.warn(`No inputs found with selector: ${selector}`);
        return;
    }
    
    inputs.forEach(inputEl => {
        inputEl.value = value;
    });
    
    input.value = '';
}

// Tags management
(function() {
    const textarea = document.getElementById('productTagsTextarea');
    const tagsDisplay = document.getElementById('tagsDisplay');
    let tags = [];

    // Initialize tags from textarea value
    function initTags() {
        const value = textarea.value.trim();
        if (value) {
            tags = value.split(',').map(tag => tag.trim()).filter(tag => tag.length > 0);
            renderTags();
        }
    }

    function renderTags() {
        tagsDisplay.innerHTML = '';
        if (tags.length === 0) {
            return;
        }

        tags.forEach((tag, index) => {
            const tagElement = document.createElement('div');
            tagElement.className = 'tag-item';
            tagElement.innerHTML = `
                <span class="tag-text">${escapeHtml(tag)}</span>
                <button type="button" class="tag-remove" data-index="${index}" title="Remove tag">
                    <i class="bi bi-x"></i>
                </button>
            `;
            tagsDisplay.appendChild(tagElement);
        });

        // Add remove event listeners
        tagsDisplay.querySelectorAll('.tag-remove').forEach(btn => {
            btn.addEventListener('click', function() {
                const index = parseInt(this.getAttribute('data-index'));
                removeTag(index);
            });
        });

        updateTextareaValue();
    }

    function removeTag(index) {
        tags.splice(index, 1);
        renderTags();
    }

    function addTag(tag) {
        const trimmedTag = tag.trim();
        if (trimmedTag && !tags.includes(trimmedTag)) {
            tags.push(trimmedTag);
            renderTags();
            return true;
        }
        return false;
    }

    function updateTextareaValue() {
        textarea.value = tags.join(', ');
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    textarea.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault();

            // Get current cursor position
            const cursorPos = textarea.selectionStart;
            const textBeforeCursor = textarea.value.substring(0, cursorPos);
            const textAfterCursor = textarea.value.substring(cursorPos);

            // Find the last comma or newline before cursor
            const lastSeparator = Math.max(
                textBeforeCursor.lastIndexOf(','),
                textBeforeCursor.lastIndexOf('\n')
            );

            // Extract the tag
            const tagText = textBeforeCursor.substring(lastSeparator + 1).trim();

            if (tagText) {
                if (addTag(tagText)) {
                    // Clear textarea and insert remaining text
                    textarea.value = textAfterCursor.trim();
                    textarea.setSelectionRange(0, 0);
                }
            }
        }
    });

    // Handle paste events
    textarea.addEventListener('paste', function() {
        setTimeout(() => {
            const value = textarea.value;
            const lines = value.split(/[,\n]/);
            let added = false;

            lines.forEach(line => {
                const trimmed = line.trim();
                if (trimmed) {
                    if (addTag(trimmed)) {
                        added = true;
                    }
                }
            });

            if (added) {
                textarea.value = '';
                textarea.setSelectionRange(0, 0);
            }
        }, 10);
    });

    textarea.addEventListener('blur', function() {
        const value = textarea.value.trim();
        if (value) {
            const parts = value.split(',');
            parts.forEach(part => {
                const trimmed = part.trim();
                if (trimmed) addTag(trimmed);
            });
            textarea.value = '';
        }
    });

    // Sync tags to textarea before form submit so tags are always sent
    const form = textarea.closest('form');
    if (form) {
        form.addEventListener('submit', function() {
            updateTextareaValue();
        });
    }

    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        initTags();
    });

    // Also initialize immediately (in case DOMContentLoaded already fired)
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initTags);
    } else {
        initTags();
    }
})();

// Barcode generation
function generateNewBarcode() {
    const randomBarcode = Math.floor(Math.random() * 90000000 + 10000000).toString();
    document.getElementById('barcode').value = randomBarcode;
}

// Form validation
document.getElementById('variantProductForm').addEventListener('submit', function(e) {
    if (variantCombinations.length === 0) {
        e.preventDefault();
        alert('Please select at least one attribute value to create variants.');
        return false;
    }
    
    // Validate all variants have price and stock
    let hasError = false;
    document.querySelectorAll('input[name*="[price]"]').forEach(input => {
        if (!input.value || parseFloat(input.value) < 0) {
            hasError = true;
            input.classList.add('is-invalid');
        } else {
            input.classList.remove('is-invalid');
        }
    });
    
    document.querySelectorAll('input[name*="[opening_stock]"]').forEach(input => {
        if (!input.value || parseInt(input.value) < 0) {
            hasError = true;
            input.classList.add('is-invalid');
        } else {
            input.classList.remove('is-invalid');
        }
    });
    
    if (hasError) {
        e.preventDefault();
        alert('Please fill in all required fields (Price and Stock) for all variants.');
        return false;
    }
});
</script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.admin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/sudheerkt_uat/resources/views/admin/products/create-variant.blade.php ENDPATH**/ ?>