@extends('layouts.app')

@section('title', 'السلة')

@section('content')
<div class="min-h-screen pb-32">
    
    <a href="/" class="inline-flex items-center text-gray-500 dark:text-gray-400 hover:text-orange-600 mb-6 transition font-medium text-sm group mr-4 mt-4">
        <div class="w-8 h-8 bg-white dark:bg-gray-800 rounded-full flex items-center justify-center shadow-sm ml-2 group-hover:shadow-md transition">
            <svg class="w-4 h-4 transform rotate-0" 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>
        </div>
        رجوع للمينيو
    </a>

    <div class="container mx-auto px-4 max-w-lg">
        <h1 class="text-3xl font-extrabold mb-8 text-gray-900 dark:text-white flex items-center gap-3">
            <span>🛒</span> سلة مشترياتك
        </h1>

        @if(count($cart) > 0)
            <div class="space-y-4">
                @foreach($cart as $key => $item)
                <div class="bg-white dark:bg-gray-800 p-4 rounded-[20px] shadow-sm hover:shadow-md transition border border-gray-100 dark:border-gray-700 relative overflow-hidden group" id="cart-item-{{ $key }}">
                    
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <h3 class="font-bold text-gray-800 dark:text-white text-lg">{{ $item['name'] }}</h3>
                            
                            @if($item['variant_label'])
                                <span class="inline-block mt-1 text-[11px] bg-orange-50 dark:bg-orange-900/30 text-orange-700 dark:text-orange-400 px-2 py-0.5 rounded-md font-medium">
                                    {{ $item['variant_label'] }}
                                </span>
                            @endif

                            @if(!empty($item['addons']))
                                <div class="text-[11px] text-gray-500 dark:text-gray-400 mt-2 space-y-1">
                                    @foreach($item['addons'] as $addon)
                                        <span class="flex items-center gap-1">
                                            <span class="w-1 h-1 bg-gray-300 dark:bg-gray-600 rounded-full"></span>
                                            {{ $addon }}
                                        </span>
                                    @endforeach
                                </div>
                            @endif

                            @if(!empty($item['exclusions']))
                                <div class="text-[11px] text-red-500 mt-1 space-y-1">
                                    @foreach($item['exclusions'] as $exc)
                                        <span class="flex items-center gap-1">🚫 بدون {{ $exc }}</span>
                                    @endforeach
                                </div>
                            @endif

                            @if(!empty($item['notes']))
                                <div class="text-[10px] text-gray-400 mt-1 italic">
                                    📝 {{Str::limit($item['notes'], 30) }}
                                </div>
                            @endif
                            
                            <div class="mt-1 text-xs text-gray-400">سعر الوحدة: {{ $item['price'] }} ر.س</div>
                        </div>

                        <div class="flex flex-col gap-2">
                            {{-- زر الحذف --}}
                            <button onclick="removeFromCart('{{ $key }}')" class="p-2 text-gray-300 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-full transition">
                                <svg 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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                            </button>

                            {{-- ✅ زر التعديل (جديد) --}}
                            <a href="{{ route('cart.edit', ['id' => $item['id'], 'key' => $key]) }}" class="p-2 text-gray-300 hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-full transition flex justify-center">
                                <svg 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                            </a>
                        </div>
                    </div>

                    <div class="mt-4 pt-4 border-t border-dashed border-gray-100 dark:border-gray-700 flex justify-between items-center">
                        <div class="flex items-center bg-gray-50 dark:bg-gray-700 rounded-xl p-1 shadow-inner">
                            <button onclick="updateQuantity('{{ $key }}', -1)" class="w-8 h-8 flex items-center justify-center bg-white dark:bg-gray-600 rounded-lg shadow-sm text-gray-600 dark:text-gray-200 hover:text-orange-600 active:scale-95 transition font-bold disabled:opacity-50" id="btn-minus-{{ $key }}">-</button>
                            <input type="text" readonly value="{{ $item['quantity'] }}" id="qty-{{ $key }}" class="w-8 text-center bg-transparent border-none text-gray-800 dark:text-white font-bold text-sm focus:ring-0 p-0">
                            <button onclick="updateQuantity('{{ $key }}', 1)" class="w-8 h-8 flex items-center justify-center bg-white dark:bg-gray-600 rounded-lg shadow-sm text-gray-600 dark:text-gray-200 hover:text-orange-600 active:scale-95 transition font-bold">+</button>
                        </div>
                        <div class="text-lg font-extrabold text-orange-600 dark:text-orange-500">
                            <span id="price-{{ $key }}">{{ $item['total_price'] }}</span> <span class="text-xs font-normal text-gray-500 dark:text-gray-400">ر.س</span>
                        </div>
                    </div>

                </div>
                @endforeach
            </div>

            <div class="fixed bottom-0 left-0 right-0 bg-white/90 dark:bg-gray-900/90 backdrop-blur-md shadow-[0_-5px_30px_rgba(0,0,0,0.08)] rounded-t-[30px] z-50 border-t border-gray-100 dark:border-gray-800 p-6 pb-8">
                <div class="container mx-auto max-w-lg">
                    <div class="flex justify-between items-end mb-4">
                        <span class="text-gray-500 dark:text-gray-400 font-medium">الإجمالي الكلي</span>
                        <div class="font-extrabold text-3xl text-gray-900 dark:text-white">
                            <span id="cart-total">{{ $total }}</span> <span class="text-sm font-medium text-gray-400">ر.س</span>
                        </div>
                    </div>
                    <button onclick="checkout()" class="w-full bg-gray-900 dark:bg-orange-600 text-white font-bold py-4 rounded-2xl shadow-xl hover:bg-black dark:hover:bg-orange-700 transition transform active:scale-[0.98] flex justify-center gap-3 items-center text-lg">
                        <span>إرسال الطلب واتساب</span>
                        <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.556 5.338-11.891 11.893-11.891 3.181.001 6.167 1.24 8.413 3.488 2.245 2.248 3.481 5.236 3.48 8.414-.003 6.557-5.338 11.892-11.893 11.892-1.99-.001-3.951-.5-5.688-1.448l-6.305 1.654zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884-.001 2.225.651 3.891 1.746 5.634l-.999 3.648 3.742-.981zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.017-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.695.248-1.29.173-1.414z"/></svg>
                    </button>
                </div>
            </div>

        @else
            <div class="flex flex-col items-center justify-center min-h-[60vh] text-center">
                <div class="relative mb-8">
                    <div class="absolute inset-0 bg-orange-100 dark:bg-orange-900/20 rounded-full blur-xl opacity-50 animate-pulse"></div>
                    <div class="bg-white dark:bg-gray-800 w-32 h-32 rounded-full flex items-center justify-center text-6xl shadow-xl border border-gray-50 dark:border-gray-700 relative z-10">
                        🛒
                    </div>
                </div>
                <h3 class="text-2xl font-bold text-gray-800 dark:text-white mb-2">السلة فاضية!</h3>
                <p class="text-gray-400 mb-8 max-w-xs mx-auto font-light leading-relaxed">
                    لسى ما اخترت شي.. تصفح المنيو واختار اللي يعجبك 😋
                </p>
                <a href="/" class="bg-gray-900 dark:bg-orange-600 text-white px-8 py-3.5 rounded-full font-bold shadow-lg hover:bg-black transition transform hover:-translate-y-1">
                    تصفح المنيو
                </a>
            </div>
        @endif
    </div>
</div>

<script>
    function updateQuantity(key, change) {
        let input = document.getElementById(`qty-${key}`);
        let currentQty = parseInt(input.value);
        let newQty = currentQty + change;
        if (newQty < 1) return;
        input.value = newQty;
        fetch('{{ route("cart.update") }}', {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json', 
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') 
            },
            body: JSON.stringify({ key: key, quantity: newQty })
        })
        .then(r => r.json())
        .then(data => {
            if(data.success) {
                document.getElementById(`price-${key}`).innerText = data.new_item_total;
                document.getElementById(`cart-total`).innerText = data.cart_total;
            } else {
                input.value = currentQty; 
            }
        });
    }

    function removeFromCart(key) {
        Swal.fire({
            title: 'حذف الصنف؟',
            text: "متأكد تبي تحذفه من السلة؟",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#EF4444',
            cancelButtonColor: '#F3F4F6',
            confirmButtonText: 'نعم، احذف',
            cancelButtonText: 'تراجع',
            background: document.documentElement.classList.contains('dark') ? '#1f2937' : '#fff',
            color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
            customClass: {
                popup: 'rounded-[25px] font-arabic',
                confirmButton: 'rounded-xl px-6 py-2.5 font-bold',
                cancelButton: 'rounded-xl px-6 py-2.5 text-gray-800 font-bold hover:bg-gray-200'
            }
        }).then((result) => {
            if (result.isConfirmed) {
                fetch('{{ route("cart.remove") }}', {
                    method: 'DELETE',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') },
                    body: JSON.stringify({ key: key })
                })
                .then(r => r.json())
                .then(data => {
                    if(data.success) { 
                        let item = document.getElementById(`cart-item-${key}`);
                        item.style.opacity = '0';
                        item.style.transform = 'translateX(20px)';
                        setTimeout(() => location.reload(), 300); 
                    }
                });
            }
        })
    }

    function checkout() {
        let msg = "مرحباً، أرغب بطلب جديد:%0a-------------------%0a";
        @if(count($cart) > 0)
            @foreach($cart as $item)
                msg += "▫️ *{{ $item['quantity'] }}x* {{ $item['name'] }} ";
                @if($item['variant_label']) msg += "({{ $item['variant_label'] }}) "; @endif
                @if(!empty($item['addons'])) 
                    msg += "%0a   └ [ @foreach($item['addons'] as $addon){{ $addon }} @endforeach] "; 
                @endif
                @if(!empty($item['exclusions'])) 
                    msg += "%0a   └ 🚫 بدون [ @foreach($item['exclusions'] as $exc){{ $exc }} @endforeach] "; 
                @endif
                @if(!empty($item['notes']))
                    msg += "%0a   📝 ملاحظة: {{ $item['notes'] }}";
                @endif
                msg += "%0a";
            @endforeach
            
            let finalTotal = document.getElementById('cart-total').innerText;
            msg += "-------------------%0a💰 *الإجمالي: " + finalTotal + " ر.س*";
        @endif

        let phone = "966534480484"; 
        window.open(`https://wa.me/${phone}?text=${msg}`, '_blank');
    }
</script>
@endsection