@extends('layouts.app')

@section('content')

<div class="min-h-screen bg-gray-50 dark:bg-gray-900 pb-32" x-data="productCalculator()">

    <div class="relative h-72 md:h-96 bg-gray-200 dark:bg-gray-800">
        {{-- إذا كنا في وضع تعديل، زر الرجوع يرجع للسلة --}}
        @if(isset($existingItem))
            <a href="{{ route('cart.index') }}" class="absolute top-6 right-6 z-10 bg-white/20 backdrop-blur-md p-2 rounded-full text-white hover:bg-white/30 transition shadow-lg">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"></path></svg>
            </a>
        @else
            <a href="{{ route('menu.index') }}" class="absolute top-6 right-6 z-10 bg-white/20 backdrop-blur-md p-2 rounded-full text-white hover:bg-white/30 transition shadow-lg">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"></path></svg>
            </a>
        @endif
        
        @if($item->image)
            <img src="{{ asset('storage/' . $item->image) }}" class="w-full h-full object-cover">
        @else
            <div class="w-full h-full flex items-center justify-center text-gray-400">
                <svg class="w-20 h-20" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
            </div>
        @endif
        <div class="absolute bottom-0 inset-x-0 h-32 bg-gradient-to-t from-gray-900/90 to-transparent"></div>
    </div>

    <div class="container mx-auto px-4 -mt-10 relative z-10">
        <div class="bg-white dark:bg-gray-800 rounded-3xl shadow-xl p-6 border border-gray-100 dark:border-gray-700">
            
            <div class="flex justify-between items-start mb-4">
                <div>
                    <h1 class="text-2xl md:text-3xl font-bold text-gray-800 dark:text-white mb-2">{{ $item->name }}</h1>
                    <p class="text-gray-500 dark:text-gray-400 text-sm leading-relaxed">{{ $item->description }}</p>
                </div>
                <div class="text-xl font-bold text-orange-600 dark:text-orange-500" x-text="formatMoney(totalPrice)"></div>
            </div>

            <hr class="my-6 border-gray-100 dark:border-gray-700">

            @if(!empty($item->sizes))
            <div class="mb-8">
                <h3 class="font-bold text-gray-800 dark:text-gray-200 mb-4 flex items-center gap-2"><span>📏</span> اختر الحجم</h3>
                <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
                    @foreach($item->sizes as $index => $size)
                        <button 
                            @click="selectSize('{{ $size['price'] }}', '{{ $index }}', '{{ $size['name'] }}')"
                            :class="selectedSizeName === '{{ $size['name'] }}' ? 'border-orange-500 bg-orange-50 dark:bg-orange-900/20 text-orange-700 dark:text-orange-400' : 'border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:border-orange-300'"
                            class="border-2 rounded-xl p-4 text-center relative transition-all duration-200 group">
                            <span class="block font-bold mb-1">{{ $size['name'] }}</span>
                            <span class="text-sm opacity-80">{{ $size['price'] }} ر.س</span>
                            <div x-show="selectedSizeName === '{{ $size['name'] }}'" class="absolute top-2 left-2 text-orange-500">
                                <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"></path></svg>
                            </div>
                        </button>
                    @endforeach
                </div>
            </div>
            @endif

            @if($item->addons->count() > 0)
            <div class="mb-8">
                <h3 class="font-bold text-gray-800 dark:text-gray-200 mb-4 flex items-center gap-2"><span>🧀</span> إضافات</h3>
                <div class="space-y-3">
                    @foreach($item->addons as $addon)
                    <label class="flex items-center justify-between p-3 rounded-xl border border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/30 cursor-pointer hover:bg-orange-50 dark:hover:bg-gray-700 transition">
                        <div class="flex items-center gap-3">
                            <input type="checkbox" 
                                   :checked="selectedAddonsNames.includes('{{ $addon->name }}')"
                                   @change="toggleAddon({{ $addon->price }}, '{{ $addon->name }}')" 
                                   class="w-5 h-5 text-orange-600 rounded bg-white dark:bg-gray-600 border-gray-300 focus:ring-orange-500">
                            <span class="text-gray-700 dark:text-gray-200 font-medium">{{ $addon->name }}</span>
                        </div>
                        <span class="text-sm font-bold text-gray-500 dark:text-gray-400">+{{ $addon->price }} ر.س</span>
                    </label>
                    @endforeach
                </div>
            </div>
            @endif

            @if($item->exclusionList && $item->exclusionList->count() > 0)
            <div class="mb-8">
                <h3 class="font-bold text-gray-800 dark:text-gray-200 mb-4 flex items-center gap-2"><span>🚫</span> تعديلات (بدون)</h3>
                <div class="flex flex-wrap gap-2">
                    @foreach($item->exclusionList as $exclusion)
                        <button @click="toggleExclusion('{{ $exclusion->name }}')"
                            :class="exclusions.includes('{{ $exclusion->name }}') ? 'bg-red-100 text-red-700 border-red-300 dark:bg-red-900/30 dark:text-red-300' : 'bg-gray-100 text-gray-600 border-transparent dark:bg-gray-700 dark:text-gray-300'"
                            class="px-4 py-2 rounded-lg text-sm font-bold border transition-colors flex items-center gap-2">
                            <span x-show="exclusions.includes('{{ $exclusion->name }}')">✖</span>
                            {{ $exclusion->name }}
                        </button>
                    @endforeach
                </div>
            </div>
            @endif

            <div class="mb-6">
                <h3 class="font-bold text-gray-800 dark:text-gray-200 mb-2 flex items-center gap-2"><span>📝</span> ملاحظات للمطبخ</h3>
                <textarea x-model="notes" class="w-full p-4 rounded-xl border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700 focus:ring-orange-500 focus:border-orange-500 outline-none transition" rows="3" placeholder="مثلاً: كثر صوص..."></textarea>
            </div>
        </div>
    </div>

    <div class="fixed bottom-0 inset-x-0 bg-white dark:bg-gray-800 border-t border-gray-100 dark:border-gray-700 p-4 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.1)] z-50">
        <div class="container mx-auto max-w-4xl flex items-center justify-between gap-4">
            <div class="flex flex-col">
                <span class="text-xs text-gray-400">الإجمالي</span>
                <span class="text-2xl font-bold text-gray-800 dark:text-white" x-text="formatMoney(totalPrice)"></span>
            </div>
            
            <button @click="addToCartServer()" 
                    :disabled="loading"
                    class="flex-1 bg-orange-600 hover:bg-orange-700 text-white font-bold py-3 px-6 rounded-xl shadow-lg transition transform active:scale-95 flex items-center justify-center gap-2 disabled:opacity-50">
                <span x-show="!loading">{{ isset($existingItem) ? 'تحديث الطلب' : 'إضافة للسلة' }}</span>
                <span x-show="loading">جاري التنفيذ...</span>
                <svg x-show="!loading" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path></svg>
            </button>
        </div>
    </div>

</div>

<script>
    function productCalculator() {
        return {
            basePrice: {{ $item->price ?? 0 }},
            sizePrice: 0,
            addonsPrice: 0,
            selectedSizeName: null,
            selectedAddonsNames: [],
            exclusions: [],
            notes: '',
            loading: false,
            quantity: 1,

            // هنا يكمن السحر: تعبئة البيانات إذا كانت موجودة
            init() {
                @if(isset($existingItem))
                    // وضع التعديل
                    this.notes = '{{ $existingItem['notes'] ?? '' }}';
                    this.quantity = {{ $existingItem['quantity'] ?? 1 }};
                    
                    // استرجاع الاستبعادات
                    this.exclusions = @json($existingItem['exclusions'] ?? []);

                    // استرجاع الحجم
                    @if($existingItem['variant_label'])
                        this.selectedSizeName = '{{ $existingItem['variant_label'] }}';
                        // نحتاج لمعرفة سعر الحجم المختار
                        @foreach($item->sizes as $size)
                            if('{{ $size['name'] }}' === this.selectedSizeName) {
                                this.sizePrice = parseFloat('{{ $size['price'] }}');
                            }
                        @endforeach
                    @else
                        this.basePrice = {{ $item->price ?? 0 }};
                    @endif

                    // استرجاع الإضافات
                    let savedAddons = @json($existingItem['addons'] ?? []);
                    this.selectedAddonsNames = savedAddons;
                    
                    // إعادة حساب سعر الإضافات
                    @foreach($item->addons as $addon)
                        if(savedAddons.includes('{{ $addon->name }}')) {
                            this.addonsPrice += parseFloat('{{ $addon->price }}');
                        }
                    @endforeach

                @else
                    // وضع الإضافة الجديد: اختيار أول حجم تلقائياً
                    @if(!empty($item->sizes))
                        this.selectSize('{{ $item->sizes[0]['price'] }}', '0', '{{ $item->sizes[0]['name'] }}');
                        this.basePrice = 0; 
                    @endif
                @endif
            },

            selectSize(price, index, name) {
                this.sizePrice = parseFloat(price);
                this.selectedSizeName = name;
            },

            toggleAddon(price, name) {
                let checkbox = this.$event.target;
                if (checkbox.checked) {
                    this.addonsPrice += parseFloat(price);
                    this.selectedAddonsNames.push(name);
                } else {
                    this.addonsPrice -= parseFloat(price);
                    this.selectedAddonsNames = this.selectedAddonsNames.filter(n => n !== name);
                }
            },

            toggleExclusion(name) {
                if (this.exclusions.includes(name)) {
                    this.exclusions = this.exclusions.filter(e => e !== name);
                } else {
                    this.exclusions.push(name);
                }
            },

            addToCartServer() {
                this.loading = true;

                let data = {
                    id: '{{ $item->id }}',
                    name: '{{ $item->name }}',
                    price: this.totalPrice,
                    variant_label: this.selectedSizeName,
                    addons: this.selectedAddonsNames,
                    exclusions: this.exclusions,
                    notes: this.notes,
                    quantity: this.quantity, // نحافظ على الكمية
                    @if(isset($existingItem))
                        old_key: '{{ $key }}' // نرسل مفتاح العنصر القديم لحذفه
                    @endif
                };

                fetch('{{ route("cart.add") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {
                    if(data.success) {
                        window.location.href = "{{ route('cart.index') }}"; // الرجوع للسلة بعد التعديل
                    } else {
                        alert('حدث خطأ');
                    }
                })
                .finally(() => { this.loading = false; });
            },

            get totalPrice() {
                let productPrice = this.sizePrice > 0 ? this.sizePrice : this.basePrice;
                return (productPrice + this.addonsPrice).toFixed(2);
            },
            
            formatMoney(value) {
                return value + ' ر.س';
            }
        }
    }
</script>

@endsection