<?php $__env->startPush('backend_css'); ?>
    <style>
        .attribute-input-group {
            display: flex;
            gap: 0.5rem;
            align-items: flex-end;
            margin-bottom: 0.5rem;
        }

        .preview-image {
            max-width: 56px;
            max-height: 56px;
            margin-top: 0.5rem;
            border-radius: 0.25rem;
        }

        .gallery-preview {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(72px, 1fr));
            gap: 0.75rem;
            margin-top: 1rem;
        }

        .gallery-preview-item {
            position: relative;
            max-width: 72px;
        }

        .gallery-preview-item img {
            max-width: 100%;
            height: auto;
            border-radius: 0.25rem;
        }

        .attribute-section {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 0.25rem;
            margin: 1rem 0;
        }

        .attribute-section h6 {
            margin-bottom: 1rem;
            color: #495057;
        }

        .attribute-input-group .attr-name {
            max-width: 220px;
        }

        .attribute-input-group .attr-values {
            flex: 1;
        }

        .variant-stock-group {
            display: grid;
            grid-template-columns: minmax(0, 1fr) 140px auto;
            gap: 0.5rem;
            align-items: end;
            margin-bottom: 0.5rem;
        }
    </style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('backend_content'); ?>
    <div class="container-fluid">
        
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h4 class="fw-bold mb-1">Add Product to <?php echo e($shop->name); ?></h4>
                <small class="text-muted">Create a new product</small>
            </div>
            <a href="<?php echo e(route('admin.shops.products.index', $shop)); ?>" class="btn btn-light">
                <i class="bx bx-arrow-back"></i> Back
            </a>
        </div>

        
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <form action="<?php echo e(route('admin.shops.products.store', $shop)); ?>" method="POST" enctype="multipart/form-data">
                    <?php echo csrf_field(); ?>

                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold">Product Title <span class="text-danger">*</span></label>
                            <input type="text" name="product_title"
                                class="form-control <?php $__errorArgs = ['product_title'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                value="<?php echo e(old('product_title')); ?>" placeholder="Enter product title" required>
                            <?php $__errorArgs = ['product_title'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold">SKU <span class="text-danger">*</span></label>
                            <input type="text" name="sku" class="form-control <?php $__errorArgs = ['sku'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                value="<?php echo e(old('sku')); ?>" placeholder="Enter unique SKU" required>
                            <?php $__errorArgs = ['sku'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>
                    </div>

                    
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label fw-semibold">Price <span class="text-danger">*</span></label>
                            <input type="number" name="price" class="form-control <?php $__errorArgs = ['price'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                value="<?php echo e(old('price')); ?>" placeholder="0.00" step="0.01" required>
                            <?php $__errorArgs = ['price'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label fw-semibold">Offer Price</label>
                            <input type="number" name="offer_price"
                                class="form-control <?php $__errorArgs = ['offer_price'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                value="<?php echo e(old('offer_price')); ?>" placeholder="0.00" step="0.01">
                            <?php $__errorArgs = ['offer_price'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label fw-semibold">Offer Expiry Date</label>
                            <input type="datetime-local" name="offer_expiry_date"
                                class="form-control <?php $__errorArgs = ['offer_expiry_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                value="<?php echo e(old('offer_expiry_date')); ?>">
                            <small class="text-muted">Leave empty for always-on offer price.</small>
                            <?php $__errorArgs = ['offer_expiry_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label fw-semibold">Stock <span class="text-danger">*</span></label>
                            <input type="number" name="stock" class="form-control <?php $__errorArgs = ['stock'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                value="<?php echo e(old('stock')); ?>" placeholder="0" required>
                            <?php $__errorArgs = ['stock'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>
                    </div>

                    
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Feature Image <span class="text-danger">*</span></label>
                        <input type="file" name="feature_image"
                            class="form-control <?php $__errorArgs = ['feature_image'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                            accept="image/jpeg,image/png,image/jpg,image/gif,image/webp" id="featureImageInput" required>
                        <?php $__errorArgs = ['feature_image'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback" style="display: block;"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        <small class="text-muted">Max size: 2MB. Formats: JPEG, PNG, JPG, GIF, WebP</small>
                        <div id="featureImagePreview" class="mt-2"></div>
                    </div>

                    
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Gallery Images</label>
                        <input type="file" name="gallery_images[]"
                            class="form-control <?php $__errorArgs = ['gallery_images'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                            accept="image/jpeg,image/png,image/jpg,image/gif,image/webp" id="galleryImagesInput" multiple>
                        <?php $__errorArgs = ['gallery_images'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback" style="display: block;"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        <small class="text-muted">Select multiple images. Max size per image: 2MB. Formats: JPEG, PNG, JPG,
                            GIF, WebP</small>
                        <div id="galleryPreview" class="gallery-preview mt-2"></div>
                    </div>

                    
                    <div class="attribute-section">
                        <h6 class="fw-semibold">Product Variations / Attributes</h6>
                        <small class="text-muted d-block mb-2">
                            Add dynamic attributes based on product type. Example: RAM = 4GB,8GB · Type = Inverter,Non
                            Inverter
                        </small>

                        <div id="attributesContainer"></div>

                        <button type="button" class="btn btn-sm btn-outline-secondary" id="addAttributeBtn">
                            <i class="bx bx-plus"></i> Add Attribute
                        </button>

                        <input type="hidden" name="attributes" id="attributesInput">
                    </div>

                    <div class="attribute-section">
                        <h6 class="fw-semibold">Variant Availability</h6>
                        <small class="text-muted d-block mb-2">
                            Track stock for sellable variants like Black, White, 64GB, or XL. When variants are added,
                            product stock is calculated automatically from these rows.
                        </small>

                        <div id="variantInventoryContainer"></div>

                        <button type="button" class="btn btn-sm btn-outline-secondary" id="addVariantInventoryBtn">
                            <i class="bx bx-plus"></i> Add Variant Stock
                        </button>

                        <input type="hidden" name="variant_inventory" id="variantInventoryInput"
                            value="<?php echo e(old('variant_inventory')); ?>">
                    </div>

                    <div class="d-flex gap-2 mt-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="bx bx-save"></i> Create Product
                        </button>
                        <a href="<?php echo e(route('admin.shops.products.index', $shop)); ?>" class="btn btn-light">Cancel</a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Feature Image Preview
        document.getElementById('featureImageInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const preview = document.getElementById('featureImagePreview');

            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.innerHTML = `<img src="${e.target.result}" class="preview-image" alt="Preview">`;
                };
                reader.readAsDataURL(file);
            } else {
                preview.innerHTML = '';
            }
        });

        // Gallery Images Preview
        document.getElementById('galleryImagesInput').addEventListener('change', function(e) {
            const files = e.target.files;
            const preview = document.getElementById('galleryPreview');
            preview.innerHTML = '';

            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const reader = new FileReader();

                reader.onload = function(e) {
                    const item = document.createElement('div');
                    item.className = 'gallery-preview-item';
                    item.innerHTML = `<img src="${e.target.result}" alt="Gallery preview">`;
                    preview.appendChild(item);
                };

                reader.readAsDataURL(file);
            }
        });

        function parseAttributes(rawValue) {
            if (!rawValue) {
                return {};
            }

            if (typeof rawValue === 'object') {
                return rawValue;
            }

            try {
                return JSON.parse(rawValue);
            } catch (error) {
                return {};
            }
        }

        function parseVariantInventory(rawValue) {
            if (!rawValue) {
                return [];
            }

            if (Array.isArray(rawValue)) {
                return rawValue;
            }

            try {
                const parsed = JSON.parse(rawValue);
                return Array.isArray(parsed) ? parsed : [];
            } catch (error) {
                return [];
            }
        }

        function createAttributeRow(name = '', values = '') {
            const group = document.createElement('div');
            group.className = 'attribute-input-group';
            group.innerHTML = `
                <input type="text" class="form-control attr-name" placeholder="Attribute (e.g., RAM, Type)" value="${name}">
                <input type="text" class="form-control attr-values" placeholder="Values separated by comma (e.g., 4GB, 8GB)" value="${values}">
                <button type="button" class="btn btn-sm btn-danger" onclick="this.parentElement.remove(); updateAttributes();">
                    <i class="bx bx-trash"></i>
                </button>
            `;

            return group;
        }

        function createVariantRow(label = '', stock = '') {
            const group = document.createElement('div');
            group.className = 'variant-stock-group';
            group.innerHTML = `
                <input type="text" class="form-control variant-label" placeholder="Variant label (e.g., Black, 64GB)" value="${label}">
                <input type="number" class="form-control variant-stock" placeholder="Stock" min="0" value="${stock}">
                <button type="button" class="btn btn-sm btn-danger" onclick="this.parentElement.remove(); updateVariantInventory();">
                    <i class="bx bx-trash"></i>
                </button>
            `;

            return group;
        }

        document.getElementById('addAttributeBtn').addEventListener('click', function() {
            document.getElementById('attributesContainer').appendChild(createAttributeRow());
        });

        document.getElementById('addVariantInventoryBtn').addEventListener('click', function() {
            document.getElementById('variantInventoryContainer').appendChild(createVariantRow());
        });

        function updateAttributes() {
            const attributes = {};
            const groups = document.querySelectorAll('#attributesContainer .attribute-input-group');

            groups.forEach(group => {
                const name = group.querySelector('.attr-name').value.trim();
                const valuesRaw = group.querySelector('.attr-values').value;

                if (!name) {
                    return;
                }

                const values = valuesRaw
                    .split(',')
                    .map(value => value.trim())
                    .filter(value => value.length > 0);

                if (values.length > 0) {
                    attributes[name] = [...new Set(values)];
                }
            });

            document.getElementById('attributesInput').value = JSON.stringify(attributes);
        }

        function updateVariantInventory() {
            const rows = [];
            const groups = document.querySelectorAll('#variantInventoryContainer .variant-stock-group');

            groups.forEach(group => {
                const label = group.querySelector('.variant-label').value.trim();
                const stockValue = group.querySelector('.variant-stock').value;

                if (!label) {
                    return;
                }

                rows.push({
                    label,
                    stock: Math.max(0, parseInt(stockValue || '0', 10) || 0),
                });
            });

            document.getElementById('variantInventoryInput').value = JSON.stringify(rows);
        }

        // Update attributes when dynamic inputs change.
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('attr-name') || e.target.classList.contains('attr-values')) {
                updateAttributes();
            }

            if (e.target.classList.contains('variant-label') || e.target.classList.contains('variant-stock')) {
                updateVariantInventory();
            }
        });

        const oldAttributes = parseAttributes(<?php echo json_encode(old('attributes'), 15, 512) ?>);
        const attributeEntries = Object.entries(oldAttributes || {});
        const oldVariantInventory = parseVariantInventory(<?php echo json_encode(old('variant_inventory'), 15, 512) ?>);

        if (attributeEntries.length > 0) {
            attributeEntries.forEach(([name, values]) => {
                const normalizedValues = Array.isArray(values) ? values.join(', ') : String(values ?? '');
                document.getElementById('attributesContainer').appendChild(createAttributeRow(name,
                    normalizedValues));
            });
        } else {
            document.getElementById('attributesContainer').appendChild(createAttributeRow());
        }

        if (oldVariantInventory.length > 0) {
            oldVariantInventory.forEach(variant => {
                document.getElementById('variantInventoryContainer').appendChild(createVariantRow(
                    variant.label || variant.name || variant.value || '',
                    variant.stock ?? 0,
                ));
            });
        }

        // Keep attributes JSON synchronized on submit.
        document.querySelector('form').addEventListener('submit', function() {
            updateAttributes();
            updateVariantInventory();
        });

        updateVariantInventory();
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('backend.layout', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Abdur Rahman\Desktop\faa\resources\views/backend/products/create.blade.php ENDPATH**/ ?>