


<?php $__env->startSection('content'); ?>


<script src="https://kit.fontawesome.com/4b4effb0ed.js" crossorigin="anonymous"></script>


<div id="main-wrapper" class="p-10"
    x-data="editProductAlpine()" x-init="initForm()">

    
    <div x-show="isLoading || isSavingDetails || isSavingSettings || isSavingOptions || isSavingAllergens"
        class="fixed inset-0 bg-black bg-opacity-80 z-50 flex items-center justify-center" style="display: none;">
        <div class="text-white text-lg flex flex-col items-center gap-2">
            <i class="fa-solid fa-spinner fa-spin text-4xl"></i>
            <span class="text-base" x-text="savingMessage"></span>
        </div>
    </div>

    
    <div x-show="errorMessage" class="w-full text-center p-10 bg-white rounded-lg shadow-md" style="display: none;">
        <h3 class="text-xl font-bold text-red-600"><?php echo e(trans('lang.error')); ?></h3>
        <p class="text-slate-600 mt-2" x-text="errorMessage"></p>
    </div>

    
    <div x-show="!errorMessage && !isLoading" class="flex flex-col gap-8" style="display: none;">

        
        <div
            class="rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0] p-6 bg-gradient-to-r from-slate-900 via-blue-800 to-blue-500 flex items-center justify-between">
            <div>
                <h3 class="text-2xl font-bold text-slate-50"><?php echo trans('lang.edit_menu_item'); ?></h3>
                <p class="text-sm text-slate-200 mt-1 m-0"><?php echo trans('lang.edit_menu_item_desc'); ?></p>
            </div>
            <a href="<?php echo route('foods'); ?>"
                class="px-4 py-2 rounded-md bg-white text-slate-600 text-sm hover:bg-slate-100 hover:text-slate-900 hover:no-underline transition focus:outline-none focus:ring-0 flex items-center gap-2">
                <i class="fa fa-rotate-left"></i>
                <?php echo e(trans('lang.go_back_to_menu')); ?>

            </a>
        </div>

        
        <div class="flex flex-col gap-8">

            
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">

                
                <div
                    class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">

                    
                    <div class="bg-slate-900 px-6 py-4">
                        <h3 class="text-xl font-bold text-white m-0"><?php echo e(trans('lang.item_details')); ?></h3>
                    </div>

                    
                    <div class="p-6 bg-white flex flex-col gap-5 flex-grow">

                        
                        <div class="w-full">
                            <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.food_name')); ?></label>
                            <input type="text" x-model="product.name" @input.debounce.500ms="validate('details')"
                                class="text-slate-700 border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:bg-blue-50"
                                :class="{'!border-red-500': errors.name}">
                            <p x-show="errors.name" x-text="errors.name" class="text-sm text-red-600 mt-1"></p>
                        </div>

                        
                        <div class="w-full">
                            <label class="block text-sm text-slate-500 font-medium mb-2"><?php echo e(trans('lang.product_type')); ?></label>
                            <div class="grid grid-cols-2 gap-3">
                                
                                <button type="button"
                                    @click="productType = 'single'"
                                    class="relative p-4 rounded-lg transition-all cursor-pointer"
                                    :class="productType === 'single' ? 'border-2 border-blue-500 bg-blue-50/50' : 'border border-slate-300 bg-white'">
                                    <div class="flex flex-col items-center gap-2">
                                        <div class="w-8 h-8 flex items-center justify-center">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" 
                                                 :stroke="productType === 'single' ? '#3b82f6' : '#94a3b8'" 
                                                 stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                <path d="M12 16H4a2 2 0 1 1 0-4h16a2 2 0 1 1 0 4h-4.25"/>
                                                <path d="M5 12a2 2 0 0 1-2-2 9 7 0 0 1 18 0 2 2 0 0 1-2 2"/>
                                                <path d="M5 16a2 2 0 0 0-2 2 3 3 0 0 0 3 3h12a3 3 0 0 0 3-3 2 2 0 0 0-2-2q0 0 0 0"/>
                                                <path d="m6.67 12 6.13 4.6a2 2 0 0 0 2.8-.4l3.15-4.2"/>
                                            </svg>
                                        </div>
                                        <div class="text-center">
                                            <p class="font-semibold text-sm"
                                               :class="productType === 'single' ? 'text-slate-800' : 'text-slate-600'">
                                                <?php echo e(trans('lang.single_product')); ?>

                                            </p>
                                            <p class="text-xs mt-1"
                                               :class="productType === 'single' ? 'text-slate-600' : 'text-slate-400'">
                                                <?php echo e(trans('lang.single_product_desc')); ?>

                                            </p>
                                        </div>
                                    </div>
                                    <div x-show="productType === 'single'" 
                                         class="absolute top-2 right-2">
                                        <i class="fa-solid fa-circle-check text-blue-500"></i>
                                    </div>
                                </button>

                                
                                <button type="button"
                                    @click="productType = 'combo'; product.price = 0"
                                    class="relative p-4 rounded-lg transition-all cursor-pointer"
                                    :class="productType === 'combo' ? 'border-2 border-purple-500 bg-purple-50/50' : 'border border-slate-300 bg-white'">
                                    <div class="flex flex-col items-center gap-2">
                                        <div class="w-8 h-8 flex items-center justify-center">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" 
                                                 :stroke="productType === 'combo' ? '#a855f7' : '#94a3b8'" 
                                                 stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                <path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z"/>
                                                <path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12"/>
                                                <path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17"/>
                                            </svg>
                                        </div>
                                        <div class="text-center">
                                            <p class="font-semibold text-sm"
                                               :class="productType === 'combo' ? 'text-slate-800' : 'text-slate-600'">
                                                <?php echo e(trans('lang.combo_product')); ?>

                                            </p>
                                            <p class="text-xs mt-1"
                                               :class="productType === 'combo' ? 'text-slate-600' : 'text-slate-400'">
                                                <?php echo e(trans('lang.combo_product_desc')); ?>

                                            </p>
                                        </div>
                                    </div>
                                    <div x-show="productType === 'combo'" 
                                         class="absolute top-2 right-2">
                                        <i class="fa-solid fa-circle-check text-purple-500"></i>
                                    </div>
                                </button>
                            </div>
                        </div>

                        
                        <div x-show="productType === 'combo'" x-transition
                             class="w-full p-4 bg-purple-50/50 border border-slate-300 rounded-lg">
                            <div class="flex items-start gap-3">
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-book-alert-icon lucide-book-alert text-purple-500 flex-shrink-0">
                                    <path d="M12 13h.01"/>
                                    <path d="M12 6v3"/>
                                    <path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20"/>
                                </svg>
                                <div class="flex-1">
                                    <p class="text-sm font-semibold text-slate-700"><?php echo e(trans('lang.combo_info_title')); ?></p>
                                    <ul class="text-xs text-slate-700 mt-1 space-y-1">
                                        <li>• <?php echo e(trans('lang.combo_info_1')); ?></li>
                                        <li>• <?php echo e(trans('lang.combo_info_2')); ?></li>
                                        <li>• <?php echo e(trans('lang.combo_info_3')); ?></li>
                                    </ul>
                                </div>
                            </div>
                        </div>

                        
                        <div class="w-full">
                            <label class="block text-sm text-slate-500 font-medium mb-1">
                                <span x-text="productType === 'combo' ? '<?php echo e(trans('lang.combo_base_price')); ?>' : '<?php echo e(trans('lang.food_price')); ?>'"></span>
                            </label>
                            
                            <div x-show="productType === 'single'" class="flex rounded-lg shadow-sm border !border-slate-300 overflow-hidden"
                                :class="{'!border-red-500': errors.price}">
                                <span
                                    class="inline-flex items-center px-3 rounded-l-lg border-r border-slate-300 bg-slate-50 text-slate-500 sm:text-sm">€</span>
                                <input type="number" step="0.01" x-model.number="product.price"
                                    @input="validate('details')"
                                    class="text-slate-700 no-spinners py-2 px-3 w-full transition duration-150 focus:outline-none focus:bg-blue-50 focus:ring-0 border-0">
                                <div class="flex flex-col border-l border-slate-300">
                                    <button @click="adjustNumber(product, 'price', 0.01); validate('details')"
                                        type="button"
                                        class="flex-1 px-2 text-slate-500 hover:bg-slate-100 border-b border-slate-300 focus:outline-none"><i
                                            class="fa-solid fa-chevron-up text-xs"></i></button>
                                    <button @click="adjustNumber(product, 'price', -0.01); validate('details')"
                                        type="button"
                                        class="flex-1 px-2 text-slate-500 hover:bg-slate-100 focus:outline-none"><i
                                            class="fa-solid fa-chevron-down text-xs"></i></button>
                                </div>
                            </div>
                            
                            
                            <div x-show="productType === 'combo'" 
                                 class="flex items-center justify-between p-3 bg-purple-50/50 border border-slate-300 rounded-lg">
                                <div class="flex items-center gap-2">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-calculator-icon lucide-calculator text-purple-500 flex-shrink-0">
                                        <rect width="16" height="20" x="4" y="2" rx="2"/>
                                        <line x1="8" x2="16" y1="6" y2="6"/>
                                        <line x1="16" x2="16" y1="14" y2="18"/>
                                        <path d="M16 10h.01"/>
                                        <path d="M12 10h.01"/>
                                        <path d="M8 10h.01"/>
                                        <path d="M12 14h.01"/>
                                        <path d="M8 14h.01"/>
                                        <path d="M12 18h.01"/>
                                        <path d="M8 18h.01"/>
                                    </svg>
                                    <span class="text-sm text-slate-700 font-medium"><?php echo e(trans('lang.combo_price_calculated')); ?></span>
                                </div>
                                <span class="text-lg font-bold text-purple-500" x-text="'€ ' + calculateBundlePrice().toFixed(2)"></span>
                            </div>
                            
                            <p x-show="errors.price && productType === 'single'" x-text="errors.price" class="text-sm text-red-600 mt-1"></p>
                        </div>

                        
                        <div class="w-full">
                            <label
                                class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.food_description')); ?></label>
                            <textarea rows="5" x-model="product.description"
                                @input="if (product.description.length > descriptionCharLimit) product.description = product.description.substring(0, descriptionCharLimit)"
                                class="text-slate-700 border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:bg-blue-50"></textarea>
                            <div class="text-right text-xs text-slate-500 mt-1"
                                :class="{'!text-red-600 font-semibold': product.description.length >= descriptionCharLimit}">
                                <span x-text="product.description.length"></span> / <span
                                    x-text="descriptionCharLimit"></span>
                            </div>
                        </div>
                        
                        
                        <div class="w-full">
                            <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.restaurant_image')); ?></label>
                            <div class="mt-2">
                                <input type="file" @change="selectFile($event.target.files[0])" id="product_image_input"
                                    class="hidden" accept="image/png, image/jpeg, image/webp">

                                <template x-if="!isUploading && product.photo">
                                    <div class="flex items-center gap-4">
                                        <img :src="imagePreview" alt="Podgląd produktu"
                                            class="w-32 h-32 rounded-lg object-cover border-2 border-slate-200">
                                        <div class="flex flex-col gap-3">
                                            <button @click="triggerFileInput()" type="button"
                                                class="flex items-center gap-2 px-3 py-2 text-sm text-slate-700 rounded-md hover:bg-blue-100 hover:text-blue-500 border !border-slate-300 transition">
                                                <i class="fa-solid fa-pencil text-xs"></i>
                                                <span><?php echo e(trans('lang.change_photo')); ?></span>
                                            </button>
                                            <button @click="removeImage()" type="button"
                                                class="flex items-center gap-2 px-3 py-2 text-sm text-slate-700 rounded-md hover:bg-red-100 hover:text-red-600 border !border-slate-300 transition">
                                                <i class="fa-solid fa-trash text-xs"></i>
                                                <span><?php echo e(trans('lang.remove_photo')); ?></span>
                                            </button>
                                        </div>
                                    </div>
                                </template>

                                <template x-if="isUploading">
                                    <div class="w-full">
                                        <div class="w-full bg-slate-200 rounded-full h-8 p-1 relative overflow-hidden">
                                            <div class="bg-blue-500 h-full rounded-full flex items-center justify-end px-2 text-white text-xs font-bold transition-all duration-300"
                                                :style="`width: ${uploadProgress}%`">
                                                <span x-text="`${Math.round(uploadProgress)}%`"></span>
                                            </div>
                                        </div>
                                        <button @click="cancelUpload()" title="<?php echo e(trans('lang.cancel_upload')); ?>"
                                            class="w-full text-center mt-2 text-sm text-slate-600 hover:text-black">
                                            <?php echo e(trans('lang.cancel')); ?>

                                        </button>
                                    </div>
                                </template>

                                <template x-if="!isUploading && !product.photo">
                                    <div @click="triggerFileInput()" @dragover.prevent="isDragging = true"
                                        @dragleave.prevent="isDragging = false"
                                        @drop.prevent="selectFile($event.dataTransfer.files[0])"
                                        class="w-full p-6 border-2 border-dashed border-slate-300 rounded-lg text-center cursor-pointer transition-colors"
                                        :class="{'bg-blue-50 border-blue-400': isDragging}">
                                        <div class="flex flex-col items-center justify-center gap-2 text-slate-500">
                                            <i class="fa-solid fa-cloud-arrow-up text-3xl"></i>
                                            <p class="font-semibold"><?php echo e(trans('lang.drag_and_drop_file_here')); ?></p>
                                            <p class="text-sm"><?php echo e(trans('lang.or')); ?></p>
                                            <p class="font-semibold text-blue-500"><?php echo e(trans('lang.click_to_select_from_disk')); ?></p>
                                            <p class="text-xs text-slate-400 mt-2"><?php echo e(trans('lang.uploader_file_types_info')); ?></p>
                                        </div>
                                    </div>
                                </template>

                                <p x-show="uploadError" x-text="uploadError" class="text-sm text-red-600 mt-2"></p>
                            </div>
                        </div>
                    </div>

                    
                    <div class="p-4 bg-slate-50 border-t border-slate-200 text-right">
                        <button @click="saveDetails()" :disabled="!isDetailsDirty || isSavingDetails || isUploading"
                            class="uppercase w-full bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-0">
                            <span x-show="!isSavingDetails"><?php echo e(trans('lang.save_details')); ?></span>
                            <span x-show="isSavingDetails"><i class="fa-solid fa-spinner fa-spin"></i>
                                <?php echo e(trans('lang.saving')); ?></span>
                        </button>
                    </div>
                </div>

                
                
                <div class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">

                    
                    <div class="bg-slate-900 px-6 py-4">
                        <h3 class="text-xl font-bold text-white m-0"><?php echo e(trans('lang.settings')); ?></h3>
                    </div>

                    
                    <div class="p-6 bg-white flex flex-col gap-5 flex-grow">

                        
                        <div class="w-full">
                            <label
                                class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.subcategory_title')); ?>

                            </label>
                            
                            <div class="relative">
                                <button type="button"
                                    @click="openDropdown = (openDropdown === 'subcategory' ? null : 'subcategory')"
                                    class="relative w-full text-left cursor-pointer rounded-lg border !border-slate-300 py-2 px-3 transition duration-150 focus:outline-none focus:ring-0 text-base"
                                    :class="{'!border-red-500': errors.subcategoryId, 'bg-blue-50': openDropdown === 'subcategory', 'bg-white': openDropdown !== 'subcategory' }">
                                    <span class="block truncate text-slate-700" x-text="selectedSubcategoryName"></span>
                                    <span
                                        class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2"><i
                                            class="fa-solid fa-chevron-down text-xs text-gray-400 transition-transform" :class="{'rotate-180': openDropdown === 'subcategory'}"></i></span>
                                </button>
                                <ul x-show="openDropdown === 'subcategory'" @click.away="openDropdown = null"
                                    x-transition
                                    class="absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-lg bg-white shadow-lg border !border-slate-300 overflow-hidden"
                                    style="display:none;">
                                    <li @click="product.subcategoryId = ''; openDropdown = null; validate('settings')"
                                        class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                        <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="!product.subcategoryId ? 'opacity-100' : 'opacity-0'"></i>
                                        <span><?php echo e(trans('lang.subcategory_select')); ?></span>
                                    </li>
                                    <template x-for="cat in subcategories" :key="cat.id">
                                        <li @click="product.subcategoryId = cat.id; openDropdown = null; validate('settings')"
                                            class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                            <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="product.subcategoryId === cat.id ? 'opacity-100' : 'opacity-0'"></i>
                                            <span x-text="cat.name"></span>
                                        </li>
                                    </template>
                                </ul>
                            </div>
                            <p x-show="errors.subcategoryId" x-text="errors.subcategoryId"
                                class="text-sm text-red-600 mt-1"></p>
                        </div>

                        
                        <div class="w-full" x-show="productType === 'single'" x-transition>
                            <label
                                class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.tax_rate_title')); ?></label>
                            <div class="relative">
                                <button type="button"
                                    @click="openDropdown = (openDropdown === 'tax_rate' ? null : 'tax_rate')"
                                    class="relative w-full text-left cursor-pointer rounded-lg border !border-slate-300 py-2 px-3 transition duration-150 focus:outline-none focus:ring-0 text-base"
                                    :class="{'!border-red-500': errors.taxId, 'bg-blue-50': openDropdown === 'tax_rate', 'bg-white': openDropdown !== 'tax_rate'}">
                                    <span class="block truncate text-slate-700" x-text="selectedTaxRateName"></span>
                                    <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                                        <i class="fa-solid fa-chevron-down text-xs text-gray-400 transition-transform" :class="{'rotate-180': openDropdown === 'tax_rate'}"></i></span>
                                </button>
                                <ul x-show="openDropdown === 'tax_rate'" @click.away="openDropdown = null"
                                    x-transition
                                    class="absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-lg bg-white shadow-lg border !border-slate-300 overflow-hidden"
                                    style="display:none;">
                                    <li @click="product.taxId = ''; openDropdown = null; validate('settings')"
                                        class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                        <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="!product.taxId ? 'opacity-100' : 'opacity-0'"></i>
                                        <span><?php echo e(trans('lang.tax_rate_select')); ?></span>
                                    </li>
                                    <template x-for="tax in taxRates" :key="tax.id">
                                        <li @click="product.taxId = tax.id; openDropdown = null; validate('settings')"
                                            class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                            <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="product.taxId === tax.id ? 'opacity-100' : 'opacity-0'"></i>
                                            <span x-text="formatTaxTitle(tax)"></span>
                                        </li>
                                    </template>
                                </ul>
                            </div>
                            <p x-show="errors.taxId" x-text="errors.taxId" class="text-sm text-red-600 mt-1"></p>
                        </div>

                        
                        <div class="w-full">
                            <label
                                class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.printer_destination')); ?></label>
                            <div class="relative">
                                <button type="button"
                                    @click="openDropdown = (openDropdown === 'printer' ? null : 'printer')"
                                    class="relative w-full text-left cursor-pointer rounded-lg border !border-slate-300 py-2 px-3 transition duration-150 focus:outline-none focus:ring-0 text-base"
                                    :class="{'bg-blue-50': openDropdown === 'printer', 'bg-white': openDropdown !== 'printer'}">
                                    <span class="block truncate text-slate-700" x-text="selectedPrinterDestinationLabel"></span>

                                    <span
                                        class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2"><i
                                            class="fa-solid fa-chevron-down text-xs text-gray-400 transition-transform" :class="{'rotate-180': openDropdown === 'printer'}"></i></span>
                                </button>
                                <ul x-show="openDropdown === 'printer'" @click.away="openDropdown = null"
                                    x-transition
                                    class="absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-lg bg-white shadow-lg border !border-slate-300 overflow-hidden"
                                    style="display:none;">

                                    <template x-for="dest in printerDestinations" :key="dest.value">
                                        <li @click="product.printerDestination = dest.value; openDropdown = null"
                                            class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                            <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="product.printerDestination === dest.value ? 'opacity-100' : 'opacity-0'"></i>
                                            <span x-text="dest.label"></span>
                                        </li>
                                    </template>
                                </ul>
                            </div>
                        </div>
                        
                        
                        <div class="mt-3 p-3 bg-blue-50/50 rounded-md border border-slate-300 flex flex-col space-y-2">
                            <div class="flex justify-between items-center">
                                <label class="font-semibold text-slate-700"><?php echo e(trans('lang.food_publish')); ?></label>
                                <label class="inline-flex items-center cursor-pointer">
                                    <input type="checkbox" x-model="product.publish" class="sr-only peer">
                                    <div class="relative w-11 h-6 bg-slate-300 rounded-full peer-checked:bg-blue-500 transition-colors 
                                        after:content-[''] after:absolute after:top-0.5 after:left-[2px] 
                                        after:bg-white after:border after:border-slate-300 after:rounded-full 
                                        after:h-5 after:w-5 after:transition-all peer-checked:after:translate-x-full 
                                        peer-checked:after:border-white">
                                    </div>
                                </label>
                            </div>
                            <p class="text-xs text-slate-600">
                                <?php echo e(trans('lang.food_publish_info')); ?>

                            </p>
                        </div>

                        
                        <div class="mt-3 p-3 bg-blue-50/50 rounded-md border !border-slate-300 flex flex-col space-y-2">
                            <div class="flex justify-between items-center">
                                <label class="font-semibold text-slate-700"><?php echo e(trans('lang.alcohol_age_restriction')); ?></label>
                                <label class="inline-flex items-center cursor-pointer">
                                    <input type="checkbox" x-model="product.ageRestriction" class="sr-only peer">
                                    <div class="relative w-11 h-6 bg-slate-300 rounded-full peer-checked:bg-red-500 transition-colors
                                        after:content-[''] after:absolute after:top-0.5 after:left-[2px]
                                        after:bg-white after:border after:border-slate-300
                                        after:rounded-full after:h-5 after:w-5 after:transition-all
                                        peer-checked:after:translate-x-full peer-checked:after:border-white">
                                    </div>
                                </label>
                            </div>
                            <p class="text-xs text-slate-600">
                                <?php echo e(trans('lang.alcohol_age_restriction_info')); ?>

                            </p>
                        </div>

                    </div>

                    
                    <div class="p-4 bg-slate-50 border-t border-slate-200 text-right">
                        <button @click="saveSettings()" :disabled="!isSettingsDirty || isSavingSettings"
                            class="uppercase w-full bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-0">
                            <span x-show="!isSavingSettings"><?php echo e(trans('lang.save_settings')); ?></span>
                            <span x-show="isSavingSettings"><i class="fa-solid fa-spinner fa-spin"></i>
                                <?php echo e(trans('lang.saving')); ?></span>
                        </button>
                    </div>

                </div>
            </div>

            
            <div
                class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col lg:col-span-2">

                
                <div class="bg-slate-900 px-6 py-4 flex justify-between items-center">
                    <div>
                        <h3 class="text-xl font-bold text-white m-0"><?php echo trans('lang.item_extras_group'); ?></h3>
                    </div>
                    <button @click="addGroup()" type="button"
                        class="flex items-center gap-2 px-4 py-2 text-sm bg-white text-slate-600 rounded-md hover:bg-slate-100 hover:text-slate-900 transition focus:outline-none focus:ring-0 whitespace-nowrap">
                        <i class="fa-solid fa-plus text-xs"></i><span><?php echo e(trans('lang.options_group_add')); ?></span>
                    </button>
                </div>

                
                <div class="p-6 bg-white flex flex-col gap-6 flex-grow">
                    <template x-for="(group, groupIndex) in product.options" :key="groupIndex">
                        <div class="p-4 border !border-slate-300 rounded-lg bg-blue-50/20"
                            :class="{'!border-red-500': errors.options[groupIndex]?.hasError}">

                            
                            <div class="flex flex-col md:flex-row items-end gap-4 pb-4">
                                <div class="flex-grow w-full">

                                    
                                    <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.group_title')); ?>

                                    </label>

                                    
                                    <input type="text" x-model="group.title" @input.debounce.500ms="validate('options')"
                                        class="text-slate-700 border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:bg-blue-50"
                                        :class="{'!border-red-500': errors.options[groupIndex]?.title}">

                                    
                                    <p x-show="errors.options[groupIndex]?.title"
                                        x-text="errors.options[groupIndex]?.title" class="text-sm text-red-600 mt-1">
                                    </p>
                                </div>

                                
                                <div x-data="{ tooltipVisible: false }" class="relative">
                                    <button @click="removeGroup(groupIndex)" type="button"
                                        @mouseenter="tooltipVisible = true" @mouseleave="tooltipVisible = false"
                                        class="flex h-10 w-10 items-center justify-center rounded-lg text-slate-400 hover:bg-red-100 hover:text-red-600 transition">
                                        <i class="fa-solid fa-trash"></i>
                                    </button>
                                    <div x-show="tooltipVisible"
                                        x-transition:enter="transition ease-out duration-300"
                                        x-transition:enter-start="opacity-0 translate-y-2"
                                        x-transition:enter-end="opacity-100 translate-y-0"
                                        x-transition:leave="transition ease-in duration-200"
                                        x-transition:leave-start="opacity-100 translate-y-0"
                                        x-transition:leave-end="opacity-0 translate-y-2"
                                        class="absolute top-full right-0 mt-2 w-max max-w-xs bg-slate-800 text-white text-center text-xs rounded py-2 px-3 z-10 pointer-events-none"
                                        style="display: none;">
                                        <?php echo e(trans('lang.remove_group')); ?>

                                        <div class="absolute right-3 bottom-full w-0 h-0 border-x-8 border-x-transparent border-b-8 border-b-slate-800"></div>
                                    </div>
                                </div>
                            </div>

                            
                            <div class="flex flex-col lg:flex-row gap-3 pb-2"> 

                                <div class="pt-3 pb-4 px-3 bg-white rounded-md border border-slate-200 w-full lg:w-auto">
                                   
                                    
                                    <div class="flex items-center gap-6 h-full">
                                        <fieldset class="flex items-center gap-4">
                                            <legend class="text-xs text-slate-500 font-semibold mb-2"><?php echo e(trans('lang.selection_type')); ?>

                                            </legend>

                                            
                                            <div class="flex gap-4">

                                                
                                                <label :for="'single-choice-' + groupIndex"
                                                    class="flex items-center cursor-pointer select-none">
                                                    <input type="radio" :id="'single-choice-' + groupIndex"
                                                        :name="'selection-type-' + groupIndex" value="single"
                                                        x-model="group.selectionType" class="hidden">
                                                    <div class="w-5 h-5 border rounded-full flex items-center justify-center transition-colors"
                                                        :class="{ 'border-blue-500': group.selectionType === 'single', '!border-slate-400': group.selectionType !== 'single' }">
                                                        <div class="w-3 h-3 bg-blue-500 rounded-full transition-transform"
                                                            :class="{ 'scale-100': group.selectionType === 'single', 'scale-0': group.selectionType !== 'single' }">
                                                        </div>
                                                    </div>
                                                    <span class="ml-2 text-slate-800 text-sm"><?php echo e(trans('lang.single_choice')); ?></span>
                                                </label>

                                                
                                                <label :for="'multi-choice-' + groupIndex"
                                                    class="flex items-center cursor-pointer select-none">
                                                    <input type="radio" :id="'multi-choice-' + groupIndex"
                                                        :name="'selection-type-' + groupIndex" value="multiple"
                                                        x-model="group.selectionType" class="hidden">
                                                    <div class="w-5 h-5 border rounded-full flex items-center justify-center transition-colors"
                                                        :class="{ 'border-blue-500': group.selectionType === 'multiple', '!border-slate-400': group.selectionType !== 'multiple' }">
                                                        <div class="w-3 h-3 bg-blue-500 rounded-full transition-transform"
                                                            :class="{ 'scale-100': group.selectionType === 'multiple', 'scale-0': group.selectionType !== 'multiple' }">
                                                        </div>
                                                    </div>
                                                    <span class="ml-2 text-slate-800 text-sm"><?php echo e(trans('lang.multiple_choice')); ?></span>
                                                </label>
                                            </div>
                                        </fieldset>

                                        <div class="h-10 w-px bg-slate-300"></div>

                                        
                                        <div>
                                            <legend class="text-xs text-slate-500 font-semibold mb-2"><?php echo e(trans('lang.requirements')); ?></legend>
                                            <label class="flex items-center cursor-pointer select-none">
                                                <input type="checkbox" x-model="group.isRequired" class="sr-only peer">
                                                <div
                                                    class="relative w-11 h-6 bg-slate-300 rounded-full peer-checked:bg-blue-500 transition-colors after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border after:border-slate-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:after:translate-x-full peer-checked:after:border-white">
                                                </div>
                                                <span class="ml-3 text-slate-800 text-sm"><?php echo e(trans('lang.required')); ?></span>
                                            </label>
                                            
                                            
                                            <div x-show="group.selectionType === 'multiple'" class="mt-2">
                                                <label class="flex items-center cursor-pointer select-none">
                                                    <input type="checkbox" x-model="group.isPreselected" class="sr-only peer">
                                                    <div
                                                        class="relative w-11 h-6 bg-slate-300 rounded-full peer-checked:bg-green-500 transition-colors after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border after:border-slate-300 after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:after:translate-x-full peer-checked:after:border-white">
                                                    </div>
                                                    <span class="ml-3 text-slate-800 text-sm"><?php echo e(trans('lang.preselected')); ?></span>
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                
                                <div x-show="group.selectionType === 'multiple' && group.isRequired" x-transition>
                                    <div
                                        class="pt-3 pb-2 px-3 bg-white rounded-md border border-slate-200 w-full h-full">
                                        <legend class="text-xs text-slate-500 font-semibold mb-2"><?php echo e(trans('lang.choice_limits')); ?></legend>
                                        <div class="flex items-start gap-4">
                                            <div>
                                                <div class="flex rounded-lg shadow-sm border !border-slate-300 w-28 overflow-hidden"
                                                    :class="{'!border-red-500': errors.options[groupIndex]?.minChoices}">
                                                    <input type="number" min="1" :max="group.elements.length || 1" x-model.number="group.minChoices"
                                                        @input="validateChoiceLimits(groupIndex); validate('options')" placeholder="Min."
                                                        class="text-slate-700 no-spinners py-2 px-3 w-full transition duration-150 focus:outline-none focus:bg-blue-50 focus:ring-0 border-0">
                                                    <div class="flex flex-col border-l border-slate-300">
                                                        <button
                                                            @click="adjustNumber(group, 'minChoices', 1); validate('options')"
                                                            type="button"
                                                            class="flex-1 px-2 text-slate-500 hover:bg-slate-100 border-b border-slate-300 focus:outline-none">
                                                            <i class="fa-solid fa-chevron-up text-xs"></i>
                                                        </button>
                                                        <button
                                                            @click="adjustNumber(group, 'minChoices', -1); validate('options')"
                                                            type="button"
                                                            class="flex-1 px-2 text-slate-500 hover:bg-slate-100 focus:outline-none">
                                                            <i class="fa-solid fa-chevron-down text-xs"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                                <p x-show="errors.options[groupIndex]?.minChoices"
                                                    x-text="errors.options[groupIndex]?.minChoices"
                                                    class="text-sm text-red-600 mt-1"></p>
                                            </div>
                                            <div>
                                                <div class="flex rounded-lg shadow-sm border !border-slate-300 w-28 overflow-hidden"
                                                    :class="{'!border-red-500': errors.options[groupIndex]?.maxChoices}">
                                                    <input type="number" :min="group.minChoices || 1" :max="group.elements.length || 1" x-model.number="group.maxChoices"
                                                        @input="validateChoiceLimits(groupIndex); validate('options')" placeholder="Maks."
                                                        class="text-slate-700 no-spinners py-2 px-3 w-full transition duration-150 focus:outline-none focus:bg-blue-50 focus:ring-0 border-0">
                                                    <div class="flex flex-col border-l border-slate-300">
                                                        <button
                                                            @click="adjustNumber(group, 'maxChoices', 1); validate('options')"
                                                            type="button"
                                                            class="flex-1 px-2 text-slate-500 hover:bg-slate-100 border-b border-slate-300 focus:outline-none">
                                                            <i class="fa-solid fa-chevron-up text-xs"></i>
                                                        </button>
                                                        <button
                                                            @click="adjustNumber(group, 'maxChoices', -1); validate('options')"
                                                            type="button"
                                                            class="flex-1 px-2 text-slate-500 hover:bg-slate-100 focus:outline-none">
                                                            <i class="fa-solid fa-chevron-down text-xs"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                                <p x-show="errors.options[groupIndex]?.maxChoices"
                                                    x-text="errors.options[groupIndex]?.maxChoices"
                                                    class="text-sm text-red-600 mt-1"></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            
                            <div class="flex flex-col gap-3 pt-4 ">
                                <template x-for="(element, elementIndex) in group.elements" :key="elementIndex">
                                    <div class="flex items-end gap-3">

                                        
                                        <div class="flex-grow">
                                            <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.option_name')); ?></label>
                                            <input type="text" x-model="element.name"
                                                @input.debounce.500ms="validate('options')"
                                                class="text-slate-700 border !border-slate-300 rounded-lg py-2 px-3 w-full transition focus:outline-none focus:ring-0 focus:bg-blue-50"
                                                :class="{'!border-red-500': errors.options[groupIndex]?.elements[elementIndex]?.name}">
                                            <p x-show="errors.options[groupIndex]?.elements[elementIndex]?.name"
                                                x-text="errors.options[groupIndex]?.elements[elementIndex]?.name"
                                                class="text-sm text-red-600 mt-1"></p>
                                        </div>

                                        
                                        <div class="w-48">
                                            <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.price_plus')); ?></label>
                                            <div class="flex rounded-lg shadow-sm border !border-slate-300 overflow-hidden"
                                                :class="{'!border-red-500': errors.options[groupIndex]?.elements[elementIndex]?.price}">
                                                <span
                                                    class="inline-flex items-center px-3 rounded-l-lg border-r border-slate-300 bg-slate-50 text-slate-500 sm:text-sm">€</span>
                                                <input type="number" step="0.01" x-model.number="element.price"
                                                    @input="validate('options')"
                                                    class="text-slate-700 no-spinners py-2 px-3 w-full transition duration-150 focus:outline-none focus:bg-blue-50 focus:ring-0 border-0">
                                                <div class="flex flex-col border-l border-slate-300">
                                                    <button
                                                        @click="adjustNumber(element, 'price', 0.01); validate('options')"
                                                        type="button"
                                                        class="flex-1 px-2 text-slate-500 hover:bg-slate-100 border-b border-slate-300 focus:outline-none focus:ring-0"><i
                                                            class="fa-solid fa-chevron-up text-xs"></i></button>
                                                    <button
                                                        @click="adjustNumber(element, 'price', -0.01); validate('options')"
                                                        type="button"
                                                        class="flex-1 px-2 text-slate-500 hover:bg-slate-100 focus:outline-none focus:ring-0"><i
                                                            class="fa-solid fa-chevron-down text-xs"></i></button>
                                                </div>
                                            </div>
                                            <p x-show="errors.options[groupIndex]?.elements[elementIndex]?.price"
                                                x-text="errors.options[groupIndex]?.elements[elementIndex]?.price"
                                                class="text-sm text-red-600 mt-1"></p>
                                        </div>

                                        
                                        <div class="w-48">
                                            <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.tax')); ?></label>
                                            <div class="relative">
                                                <button @click="openDropdown = `tax-${groupIndex}-${elementIndex}`"
                                                    type="button"
                                                    class="relative w-full text-left cursor-pointer rounded-lg border !border-slate-300 py-2 px-3 transition duration-150 focus:outline-none focus:ring-0 text-base"
                                                    :class="{'!border-red-500': errors.options[groupIndex]?.elements[elementIndex]?.taxId, 'bg-blue-50': openDropdown === `tax-${groupIndex}-${elementIndex}`, 'bg-white': openDropdown !== `tax-${groupIndex}-${elementIndex}`}">
                                                    <span class="block truncate text-slate-700"
                                                        x-text="getTaxRateName(element.taxId)"></span>
                                                    <span
                                                        class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2"><i
                                                            class="fa-solid fa-chevron-down text-xs text-gray-400 transition-transform" :class="{'rotate-180': openDropdown === `tax-${groupIndex}-${elementIndex}`}"></i></span>
                                                </button>
                                                <ul x-show="openDropdown === `tax-${groupIndex}-${elementIndex}`"
                                                    @click.away="openDropdown = null"
                                                    x-transition
                                                    class="absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-lg bg-white shadow-lg border !border-slate-300 overflow-hidden"
                                                    style="display:none;">
                                                    <li @click="element.taxId = ''; openDropdown = null; validate('options')"
                                                        class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                                        <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="!element.taxId ? 'opacity-100' : 'opacity-0'"></i>
                                                        <span><?php echo e(trans('lang.placeholders.no_tax')); ?></span>
                                                    </li>
                                                    <template x-for="tax in taxRates" :key="tax.id">
                                                        <li @click="element.taxId = tax.id; openDropdown = null; validate('options')"
                                                            class="flex items-center gap-2 cursor-pointer px-3 py-2 hover:bg-blue-100 text-base text-slate-700 whitespace-nowrap">
                                                            <i class="fa-solid fa-check text-blue-500 transition-opacity" :class="element.taxId === tax.id ? 'opacity-100' : 'opacity-0'"></i>
                                                            <span x-text="formatTaxTitle(tax)"></span>
                                                        </li>
                                                    </template>
                                                </ul>
                                            </div>
                                            <p x-show="errors.options[groupIndex]?.elements[elementIndex]?.taxId"
                                                x-text="errors.options[groupIndex]?.elements[elementIndex]?.taxId"
                                                class="text-sm text-red-600 mt-1"></p>
                                        </div>

                                        
                                        <div>
                                            <div class="relative" x-data="{ tooltipVisible: false }">
                                                <button @click="removeOption(groupIndex, elementIndex)" type="button"
                                                    @mouseenter="tooltipVisible = true" @mouseleave="tooltipVisible = false"
                                                    class="flex h-10 w-10 items-center justify-center rounded-lg text-slate-400 hover:bg-red-100 hover:text-red-600 transition self-end">
                                                    <i class="fa-solid fa-trash"></i>
                                                </button>
                                                <div x-show="tooltipVisible"
                                                    x-transition:enter="transition ease-out duration-300"
                                                    x-transition:enter-start="opacity-0 translate-y-2"
                                                    x-transition:enter-end="opacity-100 translate-y-0"
                                                    x-transition:leave="transition ease-in duration-200"
                                                    x-transition:leave-start="opacity-100 translate-y-0"
                                                    x-transition:leave-end="opacity-0 translate-y-2"
                                                    class="absolute top-full right-0 mt-2 w-max max-w-xs bg-slate-800 text-white text-center text-xs rounded py-2 px-3 z-10 pointer-events-none"
                                                    style="display: none;">
                                                    <?php echo e(trans('lang.remove_option')); ?>

                                                    <div class="absolute right-3 bottom-full w-0 h-0 border-x-8 border-x-transparent border-b-8 border-b-slate-800"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </div>

                            
                            <div class="pt-4 mt-4 border-t border-slate-200">
                                <button @click="addOption(groupIndex)" type="button"
                                    class="flex items-center space-x-2 px-3 py-2 text-sm bg-white text-slate-700 rounded-md hover:bg-slate-100 border !border-slate-300 transition whitespace-nowrap"><i
                                        class="fa-solid fa-plus text-xs"></i><span><?php echo e(trans('lang.add_option')); ?></span></button>
                            </div>
                        </div>
                    </template>
                    
                    
                    <div x-show="product.options.length > 0" class="flex justify-center pt-4">
                        <button @click="addGroup()" type="button"
                            class="flex items-center gap-2 px-3 py-2 text-sm text-slate-500 hover:text-slate-700 hover:bg-slate-50 rounded-md transition-colors duration-200 group">
                            <div class="w-5 h-5 rounded-full border border-slate-300 group-hover:border-slate-400 flex items-center justify-center group-hover:bg-slate-100 transition-colors duration-200">
                                <i class="fa-solid fa-plus text-xs"></i>
                            </div>
                            <span class="text-xs"><?php echo e(trans('lang.options_group_add')); ?></span>
                        </button>
                    </div>
                </div>

                
                <div class="p-4 bg-slate-50 border-t border-slate-200 text-right">
                    <button @click="saveOptions()" :disabled="!isOptionsDirty || isSavingOptions"
                        class="uppercase w-full bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-0">
                        <span x-show="!isSavingOptions"><?php echo e(trans('lang.save_options_and_extras')); ?></span>
                        <span x-show="isSavingOptions"><i class="fa-solid fa-spinner fa-spin"></i> <?php echo e(trans('lang.saving')); ?></span>
                    </button>
                </div>
            </div>

            
            <div
                class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col lg:col-span-2">

                
                <div class="bg-slate-900 px-6 py-4 flex items-center justify-between">
                    <h3 class="text-xl font-bold text-white m-0"><?php echo e(trans('lang.allergens')); ?></h3>
                    <span x-show="product.allergenIds && product.allergenIds.length > 0" 
                          class="w-8 h-6 flex items-center justify-center bg-white/20 text-white text-xs font-medium rounded-md"
                          x-text="product.allergenIds.length"></span>
                </div>

                
                <div class="p-6 bg-white flex flex-col gap-5 flex-grow">
                    
                    <div class="p-4 bg-blue-50/50 border border-slate-300 rounded-lg">
                        <div class="flex items-start gap-3">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-book-alert-icon lucide-book-alert text-blue-500 flex-shrink-0">
                                <path d="M12 13h.01"/>
                                <path d="M12 6v3"/>
                                <path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20"/>
                            </svg>
                            <div class="flex-1">
                                <p class="text-sm font-semibold text-slate-700"><?php echo e(trans('lang.allergens_info_title')); ?></p>
                                <ul class="text-xs text-slate-700 mt-1 space-y-1">
                                    <li>• <?php echo e(trans('lang.allergens_info_1')); ?></li>
                                    <li>• <?php echo e(trans('lang.allergens_info_2')); ?></li>
                                    <li>• <?php echo e(trans('lang.allergens_info_3')); ?></li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    
                    <div class="flex flex-wrap gap-3">
                        <button type="button" @click="selectCommonAllergens()" 
                                class="flex items-center gap-2 px-3 py-2 text-sm bg-white text-slate-700 rounded-md hover:bg-slate-100 border border-slate-300 transition focus:outline-none focus:ring-0">
                            <i class="fa-solid fa-star text-xs"></i>
                            <span><?php echo e(trans('lang.select_common_allergens')); ?></span>
                        </button>
                        <button type="button" @click="product.allergenIds = []" 
                                x-show="product.allergenIds && product.allergenIds.length > 0"
                                class="flex items-center gap-2 px-3 py-2 text-sm bg-white text-slate-700 rounded-md hover:bg-red-100 hover:text-red-600 border border-slate-300 transition focus:outline-none focus:ring-0">
                            <i class="fa-solid fa-xmark text-xs"></i>
                            <span><?php echo e(trans('lang.clear_all')); ?></span>
                        </button>
                    </div>

                    <template x-if="allergens.length === 0">
                        <div class="text-center py-8 text-slate-500">
                            <i class="fa-solid fa-spinner fa-spin text-2xl mb-2"></i>
                            <p><?php echo e(trans('lang.loading_allergens')); ?></p>
                        </div>
                    </template>

                    <template x-if="allergens.length > 0">
                        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                            <template x-for="allergen in allergens" :key="allergen.id">
                                <label class="flex flex-col items-center gap-2 p-3 rounded-lg border cursor-pointer transition-all"
                                    :class="{
                                        'border-2 border-blue-500 bg-blue-50': product.allergenIds && product.allergenIds.includes(allergen.id),
                                        'border-slate-300 hover:bg-slate-50': !product.allergenIds || !product.allergenIds.includes(allergen.id)
                                    }">
                                    <div class="w-10 h-10 flex items-center justify-center rounded-full"
                                         :class="{
                                             'bg-blue-100': product.allergenIds && product.allergenIds.includes(allergen.id),
                                             'bg-slate-100': !product.allergenIds || !product.allergenIds.includes(allergen.id)
                                         }">
                                        <span class="text-2xl" x-text="getAllergenIcon(allergen.id)"></span>
                                    </div>
                                    <span class="text-xs text-center font-medium"
                                          :class="{
                                              'text-blue-700': product.allergenIds && product.allergenIds.includes(allergen.id),
                                              'text-slate-700': !product.allergenIds || !product.allergenIds.includes(allergen.id)
                                          }"
                                          x-text="allergen.name"></span>
                                    <input type="checkbox" 
                                        :value="allergen.id"
                                        x-model="product.allergenIds"
                                        @change="validate('allergens')"
                                        class="sr-only">
                                </label>
                            </template>
                        </div>
                    </template>
                </div>

                
                <div class="p-4 bg-slate-50 border-t border-slate-200 text-right">
                    <button @click="saveAllergens()" :disabled="!isAllergensDirty || isSavingAllergens"
                        class="uppercase w-full bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-0">
                        <span x-show="!isSavingAllergens"><?php echo e(trans('lang.save_allergens')); ?></span>
                        <span x-show="isSavingAllergens"><i class="fa-solid fa-spinner fa-spin"></i>
                            <?php echo e(trans('lang.saving')); ?></span>
                    </button>
                </div>
            </div>

            
            <div x-show="notification.show" x-transition
                class="fixed top-5 right-5 z-50 max-w-lg rounded-lg shadow-lg pointer-events-auto"
                :class="{ 'bg-green-100 border-l-4 border-green-500': notification.type === 'success', 'bg-red-100 border-l-4 border-red-500': notification.type === 'error' }"
                style="display: none;">
                <div class="p-4">
                    
                    
                    
                    <div class="grid grid-cols-[auto,1fr,auto] items-center gap-x-3">

                        
                        <div class="flex-shrink-0">
                            <i x-show="notification.type === 'success'"
                                class="fa-solid fa-check-circle text-green-500 text-xl"></i>
                            <i x-show="notification.type === 'error'"
                                class="fa-solid fa-times-circle text-red-500 text-xl"></i>
                        </div>

                        
                        <div>
                            <p class="text-sm font-medium break-words"
                                :class="{ 'text-green-800': notification.type === 'success', 'text-red-800': notification.type === 'error' }"
                                x-text="notification.message"></p>
                        </div>

                        
                        <div class="flex-shrink-0">
                            <button @click="notification.show = false"
                                class="inline-flex text-slate-500 hover:text-slate-600 focus:outline-none">
                                <span class="sr-only"><?php echo e(trans('lang.close')); ?></span>
                                <i class="fa-solid fa-times"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php $__env->stopSection(); ?>

        <script>
            var cuser_id = "<?php echo e(Auth::id()); ?>";
            const currentLanguage = "<?php echo e(App::getLocale()); ?>";

    // Obiekt z danymi dla list rozwijanych
    const printerDestinationsData = [
        { value: 'Kitchen', label: '<?php echo e(trans("lang.kitchen")); ?>' },
        { value: 'Bar',     label: '<?php echo e(trans("lang.bar")); ?>' }
    ];

    // Obiekt z wszystkimi tłumaczeniami dla skryptu JS
    const translationStrings = {
        // Wiadomości walidacyjne
        validation: {
            product_name_required: '<?php echo e(trans("lang.validation.product_name_required")); ?>',
            price_must_be_number: '<?php echo e(trans("lang.validation.price_must_be_number")); ?>',
            subcategory_required: '<?php echo e(trans("lang.validation.subcategory_required")); ?>',
            tax_required: '<?php echo e(trans("lang.validation.tax_required")); ?>',
            group_title_required: '<?php echo e(trans("lang.validation.group_title_required")); ?>',
            min_non_negative: '<?php echo e(trans("lang.validation.min_non_negative")); ?>',
            max_non_negative: '<?php echo e(trans("lang.validation.max_non_negative")); ?>',
            min_gt_max: '<?php echo e(trans("lang.validation.min_gt_max")); ?>',
            option_name_required: '<?php echo e(trans("lang.validation.option_name_required")); ?>',
            price_must_be_positive_number: '<?php echo e(trans("lang.validation.price_must_be_positive_number")); ?>',
        },
        // Powiadomienia i komunikaty
            notifications: {
                please_correct_errors: '<?php echo e(trans("lang.notifications.please_correct_errors")); ?>',
                details_saved_success: '<?php echo e(trans("lang.notifications.details_saved_success")); ?>',
                settings_saved_success: '<?php echo e(trans("lang.notifications.settings_saved_success")); ?>',
                options_saved_success: '<?php echo e(trans("lang.notifications.options_saved_success")); ?>',
                allergens_saved_success: '<?php echo e(trans("lang.notifications.allergens_saved_success")); ?>',
                photo_upload_success: '<?php echo e(trans("lang.notifications.photo_upload_success")); ?>',
                details_save_error: '<?php echo e(trans("lang.notifications.details_save_error")); ?>',
                settings_save_error: '<?php echo e(trans("lang.notifications.settings_save_error")); ?>',
                options_save_error: '<?php echo e(trans("lang.notifications.options_save_error")); ?>',
                allergens_save_error: '<?php echo e(trans("lang.notifications.allergens_save_error")); ?>',
            },
        // Błędy krytyczne i błędy uploadu
        errors: {
            cuser_id_undefined: '<?php echo e(trans("lang.errors.cuser_id_undefined")); ?>',
            vendor_not_found: '<?php echo e(trans("lang.errors.vendor_not_found")); ?>',
            product_not_found: '<?php echo e(trans("lang.errors.product_not_found")); ?>',
            data_loading_error: '<?php echo e(trans("lang.errors.data_loading_error")); ?>',
            invalid_file_format: '<?php echo e(trans("lang.errors.invalid_file_format")); ?>',
            file_too_large: '<?php echo e(trans("lang.errors.file_too_large")); ?>',
            file_upload_error: '<?php echo e(trans("lang.errors.file_upload_error")); ?>',
            image_url_error: '<?php echo e(trans("lang.errors.image_url_error")); ?>',
            image_compression_error: '<?php echo e(trans("lang.errors.image_compression_error")); ?>',
        },
        // Teksty tymczasowe i zastępcze
            placeholders: {
                processing: '<?php echo e(trans("lang.placeholders.processing")); ?>',
                saving_details: '<?php echo e(trans("lang.placeholders.saving_details")); ?>',
                saving_settings: '<?php echo e(trans("lang.placeholders.saving_settings")); ?>',
                saving_options: '<?php echo e(trans("lang.placeholders.saving_options")); ?>',
                saving_allergens: '<?php echo e(trans("lang.placeholders.saving_allergens")); ?>',
                no_tax: '<?php echo e(trans("lang.placeholders.no_tax")); ?>',
            },
        general: {
            vat: '<?php echo e(trans("lang.vat_short")); ?>'
        }
    };

    const serverData = {
        taxRates:         <?php echo json_encode($taxRates, 15, 512) ?>,
        subcategories:    <?php echo json_encode($subcategories, 15, 512) ?>,
        allergens:        <?php echo json_encode($allergens, 15, 512) ?>,
        placeholderImage: '<?php echo e($placeholderImage); ?>',
        csrfToken:        '<?php echo e(csrf_token()); ?>',
        apiGetProduct:    '<?php echo e(url("/api/foods")); ?>',
        apiUpdate:        '<?php echo e(url("/api/foods/" . $id)); ?>',
        apiUploadPhoto:   '<?php echo e(route("api.foods.upload-photo")); ?>',
        routeFoods:       '<?php echo e(route("foods")); ?>',
    };
        </script>

        <?php $__env->startSection('scripts'); ?>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/compressorjs/1.2.1/compressor.min.js"
            integrity="sha512-gcAUkasjUYVTYy/eMyjuKzKr/RE5NcL7wG2tG1Mr2A5gN3AmGr0FmfnHMP2v1EwuL_Z4J_S9ImQgnfkU2KzwWg=="
            crossorigin="anonymous" referrerpolicy="no-referrer"></script>

        <style>
            .no-spinners::-webkit-outer-spin-button,
            .no-spinners::-webkit-inner-spin-button {
                -webkit-appearance: none;
                margin: 0;
            }

            .no-spinners {
                -moz-appearance: textfield;
            }
        </style>

        <script>
            function editProductAlpine() {
        return {
            // === STATE ===
            productId: "<?php echo e($id); ?>",
            descriptionCharLimit: 300,
            isLoading: true,
            isSavingDetails: false,
            isSavingSettings: false,
            isSavingOptions: false,
            isSavingAllergens: false,
            savingMessage: translationStrings.placeholders.processing,
            notification: {
                show: false,
                type: 'success',
                message: ''
            },
            placeholderImage: '',
            imagePreview: '',
            isDragging: false,
            isUploading: false,
            uploadProgress: 0,
            uploadError: '',
            uploadTask: null,
            errorMessage: '',
            openDropdown: null,
            productType: 'single', // 'single' lub 'combo' - typ produktu
            product: {
                name: '',
                price: 0,
                taxId: '',
                subcategoryId: '',
                printerDestination: 'Kitchen',
                photo: '',
                description: '',
                publish: true,
                ageRestriction: false,
                options: [],
                allergenIds: []
            },
            taxRates: [],
            subcategories: [],
            allergens: [],
            printerDestinations: printerDestinationsData,
            originalProduct: null,
            errors: {
                name: '',
                price: '',
                subcategoryId: '',
                taxId: '',
                options: []
            },

            // === METHODS ===

            async initForm() {
                this.isLoading = true;
                try {
                    this.placeholderImage = serverData.placeholderImage;
                    this.imagePreview     = serverData.placeholderImage;
                    this.taxRates         = serverData.taxRates.map(t => ({ id: t.id, tax: String(t.tax) }));
                    this.subcategories    = serverData.subcategories.map(s => ({ id: s.id, name: s.name }));
                    this.allergens        = serverData.allergens.map(a => ({
                        id:   a.id,
                        name: a[currentLanguage] || a.en || a.de || a.pl || 'Unknown',
                    })).sort((a, b) => a.name.localeCompare(b.name));

                    const res = await fetch(`${serverData.apiGetProduct}/${this.productId}`, {
                        headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': serverData.csrfToken },
                    });
                    if (!res.ok) throw new Error(translationStrings.errors.product_not_found);
                    const json = await res.json();
                    if (!json.success) throw new Error(translationStrings.errors.product_not_found);

                    const p = json.product;
                    const rawOptions = p.options_id
                        ? (typeof p.options_id === 'string' ? JSON.parse(p.options_id) : p.options_id)
                        : {};
                    const rawAllergens = p.allergen_ids
                        ? (typeof p.allergen_ids === 'string' ? JSON.parse(p.allergen_ids) : p.allergen_ids)
                        : [];

                    this.product = {
                        name:               p.name || '',
                        price:              parseFloat(p.price ?? 0),
                        taxId:              p.tax_id ?? '',
                        subcategoryId:      p.subcategory_id ?? '',
                        printerDestination: p.printer_destination || 'Kitchen',
                        photo:              p.photo || '',
                        description:        p.description || '',
                        publish:            !!p.publish,
                        ageRestriction:     !!p.age_restriction,
                        options:            this.formatOptions(rawOptions),
                        allergenIds:        Array.isArray(rawAllergens) ? rawAllergens : [],
                    };
                    this.imagePreview = p.photo || this.placeholderImage;

                    const hasPreselectedOptions = this.product.options.some(g =>
                        g.selectionType === 'multiple' && g.isPreselected && g.elements && g.elements.length > 0
                    );
                    this.productType = (this.product.price === 0 && hasPreselectedOptions) ? 'combo' : 'single';

                    this.originalProduct = JSON.parse(JSON.stringify(this.product));
                    this.syncErrorsStructure();
                } catch (error) {
                    this.errorMessage = translationStrings.errors.data_loading_error + error.message;
                } finally {
                    this.isLoading = false;
                }
            },

            validate(section) {
                const newErrors = { name: '', price: '', subcategoryId: '', taxId: '', options: this.errors.options || [] };
                let isValid = true;
                if (section === 'allergens') {
                    // Allergens don't require validation, but we can add it if needed
                    return true;
                }
                if (section === 'details') {
                    newErrors.name = !this.product.name.trim() ? translationStrings.validation.product_name_required : '';
                    if (newErrors.name) isValid = false;
                    newErrors.price = (typeof this.product.price !== 'number' || this.product.price < 0) ? translationStrings.validation.price_must_be_number : '';
                    if (newErrors.price) isValid = false;
                }
                if (section === 'settings') {
                    newErrors.subcategoryId = !this.product.subcategoryId ? translationStrings.validation.subcategory_required : '';
                    if (newErrors.subcategoryId) isValid = false;
                    
                    // VAT is required unless it's a bundle (price = 0 with options that have their own VAT)
                    // Walidacja VAT tylko jeśli nie jest to combo
                    newErrors.taxId = (!this.product.taxId && this.productType !== 'combo') ? translationStrings.validation.tax_required : '';
                    if (newErrors.taxId) isValid = false;
                    
                    // For combo, ensure price is 0
                    if (this.productType === 'combo' && this.product.price !== 0) {
                        this.product.price = 0;
                    }
                }
                if (section === 'options') {
                    this.product.options.forEach((group, groupIndex) => {
                        let groupHasError = false;
                        if (!group.title.trim()) {
                            newErrors.options[groupIndex].title = translationStrings.validation.group_title_required;
                            isValid = false; groupHasError = true;
                        } else { newErrors.options[groupIndex].title = ''; }
                        const min = group.minChoices ? parseInt(group.minChoices, 10) : 0;
                        const max = group.maxChoices ? parseInt(group.maxChoices, 10) : 0;
                        if (min < 0) {
                            newErrors.options[groupIndex].minChoices = translationStrings.validation.min_non_negative;
                            isValid = false; groupHasError = true;
                        } else { newErrors.options[groupIndex].minChoices = '';}
                        if (max < 0) {
                            newErrors.options[groupIndex].maxChoices = translationStrings.validation.max_non_negative;
                            isValid = false; groupHasError = true;
                        } else { newErrors.options[groupIndex].maxChoices = ''; }
                        if (min > 0 && max > 0 && min > max) {
                            newErrors.options[groupIndex].minChoices = translationStrings.validation.min_gt_max;
                            isValid = false; groupHasError = true;
                        }
                        group.elements.forEach((element, elementIndex) => {
                            if (!element.name.trim()) {
                                newErrors.options[groupIndex].elements[elementIndex].name = translationStrings.validation.option_name_required;
                                isValid = false; groupHasError = true;
                            } else { newErrors.options[groupIndex].elements[elementIndex].name = ''; }
                            if (typeof element.price !== 'number' || element.price < 0) {
                                newErrors.options[groupIndex].elements[elementIndex].price = translationStrings.validation.price_must_be_positive_number;
                                isValid = false; groupHasError = true;
                            } else { newErrors.options[groupIndex].elements[elementIndex].price = ''; }
                        });
                        newErrors.options[groupIndex].hasError = groupHasError;
                    });
                }
                this.errors = newErrors;
                return isValid;
            },

            syncErrorsStructure() {
                this.errors.options = this.product.options.map(group => ({ title: '', minChoices: '', maxChoices: '', hasError: false, elements: group.elements.map(() => ({ name: '', price: '', taxId: '' })) }));
            },
            
            getAllergenIcon(allergenId) {
                // Znajdź pełny obiekt alergenu
                const allergen = this.allergens.find(a => a.id === allergenId);
                const allergenName = allergen ? allergen.name.toLowerCase() : allergenId.toLowerCase();
                
                const icons = {
                    // Gluten
                    'gluten': '🌾',
                    'cereals': '🌾',
                    'wheat': '🌾',
                    // Crustaceans / Krebstiere
                    'crustaceans': '🦐',
                    'krebstiere': '🦐',
                    'shrimp': '🦐',
                    'crab': '🦐',
                    'skorupiaki': '🦐',
                    // Eggs / Eier
                    'eggs': '🥚',
                    'egg': '🥚',
                    'eier': '🥚',
                    'jaja': '🥚',
                    // Fish / Fisch
                    'fish': '🐟',
                    'fisch': '🐟',
                    'ryby': '🐟',
                    // Peanuts / Erdnüsse
                    'peanuts': '🥜',
                    'peanut': '🥜',
                    'erdnüsse': '🥜',
                    'orzeszki ziemne': '🥜',
                    // Soybeans / Sojabohnen
                    'soybeans': '🫘',
                    'soy': '🫘',
                    'soja': '🫘',
                    'sojabohnen': '🫘',
                    // Milk / Milch
                    'milk': '🥛',
                    'dairy': '🥛',
                    'lactose': '🥛',
                    'milch': '🥛',
                    'mleko': '🥛',
                    // Nuts / Schalenfrüchte
                    'nuts': '🌰',
                    'tree nuts': '🌰',
                    'schalenfrüchte': '🌰',
                    'orzechy': '🌰',
                    // Celery / Sellerie
                    'celery': '🥬',
                    'sellerie': '🥬',
                    'seler': '🥬',
                    // Mustard / Senf
                    'mustard': '🌭',
                    'senf': '🌭',
                    'gorczyca': '🌭',
                    // Sesame / Sesam
                    'sesame': '🫘',
                    'sesam': '🫘',
                    'sezam': '🫘',
                    // Sulphites / Sulfite
                    'sulphites': '🍷',
                    'sulfite': '🍷',
                    'sulphur': '🍷',
                    'siarczyny': '🍷',
                    // Lupin / Lupinen
                    'lupin': '🌱',
                    'lupine': '🌱',
                    'lupinen': '🌱',
                    'łubin': '🌱',
                    // Molluscs / Weichtiere
                    'molluscs': '🦪',
                    'mollusk': '🦪',
                    'shellfish': '🦪',
                    'weichtiere': '🦪',
                    'mięczaki': '🦪'
                };
                
                // Próbuj dopasować nazwę alergenu do ikony
                for (const [key, icon] of Object.entries(icons)) {
                    if (allergenName.includes(key)) {
                        return icon;
                    }
                }
                
                // Domyślna ikona
                return '⚠️';
            },
            
            selectCommonAllergens() {
                // Wybierz najpopularniejsze alergeny (gluten, mleko, jaja, orzechy)
                const commonAllergenKeys = ['gluten', 'milk', 'eggs', 'nuts', 'peanuts'];
                const commonIds = this.allergens
                    .filter(a => commonAllergenKeys.some(key => a.id.toLowerCase().includes(key)))
                    .map(a => a.id);
                
                this.product.allergenIds = [...new Set([...this.product.allergenIds, ...commonIds])];
            },
            
            calculateBundlePrice() {
                let totalPrice = 0;
                // Oblicz sumę cen składników zestawu (tylko dla grup oznaczonych jako preselected)
                this.product.options.forEach(group => {
                    if (group.selectionType === 'multiple' && group.isPreselected && group.elements) {
                        group.elements.forEach(element => {
                            totalPrice += parseFloat(element.price) || 0;
                        });
                    }
                });
                return totalPrice;
            },

            async saveDetails() {
                if (!this.validate('details')) { this.showNotification(translationStrings.notifications.please_correct_errors, 'error'); return; }
                this.isSavingDetails = true;
                this.savingMessage = translationStrings.placeholders.saving_details;
                try {
                    const res = await fetch(serverData.apiUpdate, {
                        method: 'PATCH',
                        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': serverData.csrfToken },
                        body: JSON.stringify({ name: this.product.name, price: parseFloat(this.product.price) || 0, description: this.product.description || '', photo: this.product.photo || null }),
                    });
                    if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.message ?? 'Server error'); }
                    this.originalProduct.name = this.product.name;
                    this.originalProduct.price = this.product.price;
                    this.originalProduct.description = this.product.description;
                    this.originalProduct.photo = this.product.photo;
                    this.showNotification(translationStrings.notifications.details_saved_success, 'success');
                } catch (error) {
                    this.showNotification(translationStrings.notifications.details_save_error + error.message, 'error');
                } finally {
                    this.isSavingDetails = false;
                }
            },
            async saveSettings() {
                if (!this.validate('settings')) { this.showNotification(translationStrings.notifications.please_correct_errors, 'error'); return; }
                this.isSavingSettings = true;
                this.savingMessage = translationStrings.placeholders.saving_settings;
                try {
                    const res = await fetch(serverData.apiUpdate, {
                        method: 'PATCH',
                        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': serverData.csrfToken },
                        body: JSON.stringify({ subcategory_id: this.product.subcategoryId, tax_id: this.product.taxId || null, printer_destination: this.product.printerDestination, publish: this.product.publish, age_restriction: this.product.ageRestriction }),
                    });
                    if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.message ?? 'Server error'); }
                    this.originalProduct.subcategoryId = this.product.subcategoryId;
                    this.originalProduct.taxId = this.product.taxId;
                    this.originalProduct.printerDestination = this.product.printerDestination;
                    this.originalProduct.publish = this.product.publish;
                    this.originalProduct.ageRestriction = this.product.ageRestriction;
                    this.showNotification(translationStrings.notifications.settings_saved_success, 'success');
                } catch (error) {
                    this.showNotification(translationStrings.notifications.settings_save_error + error.message, 'error');
                } finally {
                    this.isSavingSettings = false;
                }
            },
            async saveOptions() {
                if (!this.validate('options')) { this.showNotification(translationStrings.notifications.please_correct_errors, 'error'); return; }
                this.isSavingOptions = true;
                this.savingMessage = translationStrings.placeholders.saving_options;
                try {
                    const res = await fetch(serverData.apiUpdate, {
                        method: 'PATCH',
                        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': serverData.csrfToken },
                        body: JSON.stringify({ options_id: this.formatOptionsForSave(this.product.options) }),
                    });
                    if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.message ?? 'Server error'); }
                    this.originalProduct.options = JSON.parse(JSON.stringify(this.product.options));
                    this.showNotification(translationStrings.notifications.options_saved_success, 'success');
                } catch (error) {
                    this.showNotification(translationStrings.notifications.options_save_error + error.message, 'error');
                } finally {
                    this.isSavingOptions = false;
                }
            },
            async saveAllergens() {
                this.isSavingAllergens = true;
                this.savingMessage = translationStrings.placeholders.saving_allergens;
                try {
                    const res = await fetch(serverData.apiUpdate, {
                        method: 'PATCH',
                        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': serverData.csrfToken },
                        body: JSON.stringify({ allergen_ids: this.product.allergenIds || [] }),
                    });
                    if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.message ?? 'Server error'); }
                    this.originalProduct.allergenIds = JSON.parse(JSON.stringify(this.product.allergenIds));
                    this.showNotification(translationStrings.notifications.allergens_saved_success, 'success');
                } catch (error) {
                    this.showNotification(translationStrings.notifications.allergens_save_error + error.message, 'error');
                } finally {
                    this.isSavingAllergens = false;
                }
            },

            triggerFileInput() { this.uploadError = ''; document.getElementById('product_image_input').click(); },
            selectFile(file) {
                if (!file) return;
                this.uploadError = '';
                const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
                if (!allowedTypes.includes(file.type)) { this.uploadError = translationStrings.errors.invalid_file_format; return; }
                const maxSize = 5 * 1024 * 1024;
                if (file.size > maxSize) { this.uploadError = translationStrings.errors.file_too_large; return; }
                this.imagePreview = URL.createObjectURL(file);
                this.uploadAndTrackProgress(file);
            },
            async uploadAndTrackProgress(file) {
                this.isUploading = true;
                this.uploadProgress = 0;
                new Compressor(file, {
                    quality: 0.8, maxWidth: 1920,
                    success: async (compressedResult) => {
                        try {
                            const formData = new FormData();
                            formData.append('photo', compressedResult, compressedResult.name || 'photo.jpg');
                            this.uploadProgress = 50;
                            const res = await fetch(serverData.apiUploadPhoto, {
                                method: 'POST',
                                headers: { 'X-CSRF-TOKEN': serverData.csrfToken, 'Accept': 'application/json' },
                                body: formData,
                            });
                            if (!res.ok) throw new Error(translationStrings.errors.file_upload_error);
                            const json = await res.json();
                            this.uploadProgress = 100;
                            this.product.photo = json.url;
                            this.imagePreview = json.url;
                            this.showNotification(translationStrings.notifications.photo_upload_success, 'success');
                        } catch (err) {
                            this.uploadError = translationStrings.errors.file_upload_error;
                        } finally {
                            this.isUploading = false;
                            this.uploadTask = null;
                        }
                    },
                    error: (err) => { this.uploadError = translationStrings.errors.image_compression_error + err.message; this.isUploading = false; },
                });
            },
            removeImage() { this.product.photo = ''; this.imagePreview = this.placeholderImage; this.uploadError = ''; },
            cancelUpload() { this.isUploading = false; this.uploadProgress = 0; this.uploadTask = null; this.imagePreview = this.originalProduct ? (this.originalProduct.photo || this.placeholderImage) : this.placeholderImage; },

            adjustNumber(object, property, amount) {
                let currentValue = parseFloat(object[property]) || 0;
                let newValue = currentValue + amount;
                
                // Specjalna walidacja dla choice limits
                if (property === 'minChoices' || property === 'maxChoices') {
                    const elementsCount = object.elements ? object.elements.length : 1;
                    
                    if (property === 'minChoices') {
                        newValue = Math.max(1, Math.min(newValue, elementsCount));
                    } else if (property === 'maxChoices') {
                        const minChoices = object.minChoices || 1;
                        newValue = Math.max(minChoices, Math.min(newValue, elementsCount));
                    }
                    
                    object[property] = parseInt(newValue);
                } else {
                    if (newValue < 0) { newValue = 0; }
                    object[property] = parseFloat(newValue.toFixed(2));
                }
            },

            formatOptions(optionsObject) {
                if (!optionsObject || typeof optionsObject !== 'object') return [];
                return Object.values(optionsObject).map(group => ({ ...group, selectionType: group.isMultiChoice ? 'multiple' : 'single', isRequired: group.isRequired || false, isPreselected: group.isPreselected || false, minChoices: group.minChoices || null, maxChoices: group.maxChoices || null, elements: group.elements ? Object.values(group.elements) : [] }));
            },

            formatOptionsForSave(optionsArray) {
                const obj = {};
                optionsArray.forEach((group, groupIndex) => {
                    const elementsObj = {};
                    group.elements.forEach((el, elIndex) => { 
                        // Upewnij się, że taxId jest zawsze zapisany
                        elementsObj[elIndex] = {
                            ...el,
                            taxId: el.taxId || null
                        };
                    });
                    const groupToSave = { ...group };
                    const isMultiChoice = group.selectionType === 'multiple';
                    
                    // Jeśli nie jest wymagane, to limity są zawsze null (nieograniczone)
                    const maxChoices = (!group.isRequired) ? null : ((group.maxChoices && group.maxChoices > 0) ? group.maxChoices : null);
                    const minChoices = (!group.isRequired) ? null : ((group.minChoices && group.minChoices > 0) ? group.minChoices : null);
                    
                    obj[groupIndex] = { 
                        ...groupToSave, 
                        isMultiChoice, 
                        isPreselected: group.isPreselected || false,
                        maxChoices: maxChoices,
                        minChoices: minChoices,
                        elements: elementsObj 
                    };
                });
                return obj;
            },

            addGroup() { this.product.options.push({ title: '', selectionType: 'single', isRequired: false, isPreselected: false, minChoices: 1, maxChoices: 1, elements: [] }); this.syncErrorsStructure(); },
            removeGroup(index) { this.product.options.splice(index, 1); this.syncErrorsStructure(); },
            addOption(groupIndex) { 
                this.product.options[groupIndex].elements.push({ name: '', price: 0, taxId: '' }); 
                this.updateChoiceLimits(groupIndex);
                this.syncErrorsStructure(); 
            },
            removeOption(groupIndex, elementIndex) { 
                this.product.options[groupIndex].elements.splice(elementIndex, 1); 
                this.updateChoiceLimits(groupIndex);
                this.syncErrorsStructure(); 
            },
            updateChoiceLimits(groupIndex) {
                const group = this.product.options[groupIndex];
                const elementsCount = group.elements.length;
                
                // Ustaw maxChoices na liczbę dostępnych opcji
                if (elementsCount > 0) {
                    group.maxChoices = elementsCount;
                    // Upewnij się, że minChoices nie przekracza maxChoices
                    if (group.minChoices > elementsCount) {
                        group.minChoices = elementsCount;
                    }
                    // Upewnij się, że minChoices jest co najmniej 1
                    if (group.minChoices < 1) {
                        group.minChoices = 1;
                    }
                } else {
                    group.maxChoices = 1;
                    group.minChoices = 1;
                }
            },
            validateChoiceLimits(groupIndex) {
                const group = this.product.options[groupIndex];
                const elementsCount = group.elements.length || 1;
                
                // Walidacja minChoices
                if (group.minChoices < 1) {
                    group.minChoices = 1;
                }
                if (group.minChoices > elementsCount) {
                    group.minChoices = elementsCount;
                }
                
                // Walidacja maxChoices
                if (group.maxChoices < group.minChoices) {
                    group.maxChoices = group.minChoices;
                }
                if (group.maxChoices > elementsCount) {
                    group.maxChoices = elementsCount;
                }
            },
            showNotification(message, type = 'success', duration = 4000) { this.notification.message = message; this.notification.type = type; this.notification.show = true; setTimeout(() => { this.notification.show = false; }, duration); },
            formatTaxTitle(tax) {
                if (!tax) return '';
                const vatLabel = translationStrings.general.vat || 'VAT';
                return `${tax.tax}% ${vatLabel}`;
            },

            // === COMPUTED PROPERTIES ===

            get isDetailsDirty() { if (!this.originalProduct) return false; return this.product.name !== this.originalProduct.name || this.product.price !== this.originalProduct.price || this.product.description !== this.originalProduct.description || this.product.photo !== this.originalProduct.photo; },
            get isSettingsDirty() { if (!this.originalProduct) return false; return this.product.subcategoryId !== this.originalProduct.subcategoryId || this.product.taxId !== this.originalProduct.taxId || this.product.printerDestination !== this.originalProduct.printerDestination || this.product.publish !== this.originalProduct.publish || this.product.ageRestriction !== this.originalProduct.ageRestriction; },
            get isOptionsDirty() { if (!this.originalProduct) return false; return JSON.stringify(this.product.options) !== JSON.stringify(this.originalProduct.options); },
            get isAllergensDirty() { if (!this.originalProduct) return false; return JSON.stringify((this.product.allergenIds || []).sort()) !== JSON.stringify((this.originalProduct.allergenIds || []).sort()); },

            get selectedSubcategoryName() { const subcategory = this.subcategories.find(s => s.id === this.product.subcategoryId); return subcategory ? subcategory.name : '<?php echo e(trans("lang.subcategory_select")); ?>'; },
            get selectedTaxRateName() { 
                const tax = this.taxRates.find(t => t.id === this.product.taxId); 
                return tax ? this.formatTaxTitle(tax) : '<?php echo e(trans("lang.tax_rate_select")); ?>'; 
            },
            getTaxRateName(taxId) { 
                if (!taxId) return translationStrings.placeholders.no_tax; 
                const tax = this.taxRates.find(t => t.id === taxId); 
                return tax ? this.formatTaxTitle(tax) : translationStrings.placeholders.no_tax; 
            },
            get selectedPrinterDestinationLabel() { const destination = this.printerDestinations.find(d => d.value === this.product.printerDestination); return destination ? destination.label : '...'; }
        }
    }
        </script>
        <?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\pub-and-go-merchant-np\resources\views/foods/edit.blade.php ENDPATH**/ ?>