<?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;
        }

        .gallery-preview-item .btn-remove {
            position: absolute;
            top: 2px;
            right: 2px;
            opacity: 0;
            transition: opacity 0.2s;
        }

        .gallery-preview-item:hover .btn-remove {
            opacity: 1;
        }

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

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

        .existing-gallery-item {
            position: relative;
        }

        .existing-gallery-item .btn-remove {
            position: absolute;
            top: 2px;
            right: 2px;
            opacity: 0;
        }

        .existing-gallery-item:hover .btn-remove {
            opacity: 1;
        }

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

        .attribute-input-group .attr-values {
            flex: 1;
        }
    </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">Edit Product</h4>
                <small class="text-muted"><?php echo e($product->product_title); ?> (<?php echo e($shop->name); ?>)</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.update', [$shop, $product])); ?>" method="POST"
                    enctype="multipart/form-data">
                    <?php echo csrf_field(); ?>
                    <?php echo method_field('PUT'); ?>

                    
                    <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', $product->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', $product->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', $product->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', $product->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', $product->offer_expiry_date ? $product->offer_expiry_date->format('Y-m-d\TH:i') : '')); ?>">
                            <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', $product->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</label>
                        <div class="mb-2">
                            <?php if($product->feature_image): ?>
                                <img src="<?php echo e(asset('storage/' . $product->feature_image)); ?>"
                                    alt="<?php echo e($product->product_title); ?>" class="preview-image">
                            <?php endif; ?>
                        </div>
                        <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">
                        <?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 (Leave empty to keep
                            current)</small>
                        <div id="featureImagePreview" class="mt-2"></div>
                    </div>

                    
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Gallery Images</label>

                        <?php if($product->images->count() > 0): ?>
                            <div class="mb-3">
                                <small class="text-muted d-block mb-2">Current Gallery Images:</small>
                                <div class="gallery-preview">
                                    <?php $__currentLoopData = $product->images; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $image): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <div class="gallery-preview-item existing-gallery-item"
                                            data-image-id="<?php echo e($image->id); ?>">
                                            <img src="<?php echo e(asset('storage/' . $image->image_path)); ?>" alt="Gallery image">
                                            <button type="button" class="btn btn-sm btn-danger btn-remove"
                                                onclick="confirmRemoveImage(<?php echo e($image->id); ?>)">
                                                <i class="bx bx-trash"></i>
                                            </button>
                                        </div>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <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">Add more images. Max size per image: 2MB. Formats: JPEG, PNG, JPG,
                            GIF</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="d-flex gap-2 mt-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="bx bx-save"></i> Update 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>
        const existingProduct = <?php echo json_encode($product); ?>;
        const oldAttributesRaw = <?php echo json_encode(old('attributes'), 15, 512) ?>;

        // 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);
            }
        });

        let pendingDeleteImageId = null;

        function confirmRemoveImage(imageId) {
            pendingDeleteImageId = imageId;
            const modal = new bootstrap.Modal(document.getElementById('deleteImageModal'));
            modal.show();
        }

        function removeExistingImage() {
            if (!pendingDeleteImageId) {
                return;
            }

            const form = document.querySelector('form');
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'remove_images[]';
            input.value = pendingDeleteImageId;
            form.appendChild(input);

            const imageElement = document.querySelector(`[data-image-id="${pendingDeleteImageId}"]`);
            if (imageElement) {
                imageElement.remove();
            }

            pendingDeleteImageId = null;
            const modal = bootstrap.Modal.getInstance(document.getElementById('deleteImageModal'));
            if (modal) {
                modal.hide();
            }
        }

        function parseAttributes(rawValue) {
            if (!rawValue) {
                return existingProduct.attributes || {};
            }

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

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

        function normalizeAttributesForRows(attributes) {
            const rows = [];

            if (!attributes || typeof attributes !== 'object') {
                return rows;
            }

            Object.entries(attributes).forEach(([key, rawValues]) => {
                const label = String(key).trim();
                if (!label) {
                    return;
                }

                if (label.toLowerCase() === 'colors' && Array.isArray(rawValues)) {
                    const values = rawValues
                        .map(item => (typeof item === 'object' && item !== null) ? (item.name || item.code || '') :
                            item)
                        .map(item => String(item).trim())
                        .filter(Boolean);

                    if (values.length > 0) {
                        rows.push({
                            name: 'Color',
                            values: values
                        });
                    }

                    return;
                }

                if (label.toLowerCase() === 'sizes' && Array.isArray(rawValues)) {
                    const values = rawValues
                        .map(item => (typeof item === 'object' && item !== null) ? (item.name || item.value || '') :
                            item)
                        .map(item => String(item).trim())
                        .filter(Boolean);

                    if (values.length > 0) {
                        rows.push({
                            name: 'Size',
                            values: values
                        });
                    }

                    return;
                }

                const values = Array.isArray(rawValues) ? rawValues : [rawValues];
                const normalized = values
                    .map(item => {
                        if (typeof item === 'object' && item !== null) {
                            return item.name || item.value || item.code || '';
                        }
                        return item;
                    })
                    .map(item => String(item).trim())
                    .filter(Boolean);

                if (normalized.length > 0) {
                    rows.push({
                        name: label,
                        values: normalized
                    });
                }
            });

            return rows;
        }

        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;
        }

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

        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);
        }

        // 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();
            }
        });

        const parsedAttributes = parseAttributes(oldAttributesRaw);
        const normalizedRows = normalizeAttributesForRows(parsedAttributes);

        if (normalizedRows.length > 0) {
            normalizedRows.forEach(row => {
                document.getElementById('attributesContainer').appendChild(createAttributeRow(row.name, row.values
                    .join(', ')));
            });
        } else {
            document.getElementById('attributesContainer').appendChild(createAttributeRow());
        }

        updateAttributes();

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

    <div class="modal fade" id="deleteImageModal" tabindex="-1" aria-labelledby="deleteImageModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteImageModalLabel">Remove Gallery Image</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    Are you sure you want to remove this gallery image? This change will be applied when you save the
                    product.
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" onclick="removeExistingImage()">Remove Image</button>
                </div>
            </div>
        </div>
    </div>
<?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\edit.blade.php ENDPATH**/ ?>