@extends('layouts.user.app')
{{-- @include('layouts.user.header') --}}

@section('content')
<div class="container mx-auto px-4">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-[#8B0000]">Daftar Menu</h1>
    </div>

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <!-- Filter Menu -->
    <div class="flex justify-center space-x-4 mb-8">
        <button class="filter-btn bg-[#8B0000] text-white px-6 py-2 rounded-full hover:bg-[#660000] transition" data-category="all">
            Semua Menu
        </button>
        @foreach($categories as $category)
            <button class="filter-btn bg-white text-[#8B0000] border border-[#8B0000] px-6 py-2 rounded-full hover:bg-[#ffebeb] transition" data-category="{{ $category->id }}">
                {{ $category->name }}
            </button>
        @endforeach
    </div>

    <!-- Menu Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        @foreach($menus as $menu)
        <div class="menu-item bg-white rounded-xl overflow-hidden shadow-lg hover:-translate-y-1 transition duration-300" data-category="{{ $menu->category_id }}">
            <img src="{{ asset('storage/' . $menu->image) }}" alt="{{ $menu->name }}" class="w-full h-48 object-cover">
            <div class="p-6">
                <h3 class="text-xl font-bold mb-2">{{ $menu->name }}</h3>
                <p class="text-[#8B0000] font-bold mb-4">Rp {{ number_format($menu->price, 0, ',', '.') }}</p>
                <p class="text-gray-600 mb-4">{{ $menu->description }}</p>
                <button class="add-to-cart w-full bg-[#8B0000] text-white py-2 rounded-lg hover:bg-[#660000] transition"
                        data-id="{{ $menu->id }}"
                        data-name="{{ $menu->name }}"
                        data-price="{{ $menu->price }}"
                        data-image="{{ $menu->image }}">
                    Pesan Sekarang
                </button>
            </div>
        </div>
        @endforeach
    </div>

    <!-- Cart Sidebar -->
    <div class="fixed top-0 right-0 h-full w-80 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50" id="cartSidebar">
        <div class="p-6 h-full flex flex-col">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold">Keranjang</h2>
                <button id="closeCart" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="flex-1 overflow-y-auto cart-items">
                <!-- Cart items will be inserted here -->
            </div>

            <div class="border-t pt-4 mt-4">
                <div class="flex justify-between items-center mb-4">
                    <span class="font-bold">Total:</span>
                    <span class="font-bold text-[#8B0000]" id="cartTotal">Rp 0</span>
                </div>
                <a href="{{ route('meja.index') }}" class="block w-full bg-[#8B0000] text-white text-center py-2 rounded-lg hover:bg-[#660000] transition">
                    Lanjut Pilih Meja
                </a>
            </div>
        </div>
    </div>

    <!-- Cart Toggle Button -->
    <button id="cartToggle" class="fixed bottom-4 right-4 bg-[#8B0000] text-white p-4 rounded-full shadow-lg hover:bg-[#660000] transition z-40">
        <i class="fas fa-shopping-cart"></i>
        <span class="cart-count absolute -top-2 -right-2 bg-white text-[#8B0000] rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">0</span>
    </button>
</div>

@push('scripts')
<script>
// Function to open cart
function openCart() {
    $('#cartSidebar').removeClass('translate-x-full');
    updateCartDisplay();
}

$(document).ready(function() {
    // Filter menu
    $('.filter-btn').click(function() {
        const category = $(this).data('category');
        $('.filter-btn').removeClass('bg-[#8B0000] text-white').addClass('bg-white text-[#8B0000]');
        $(this).removeClass('bg-white text-[#8B0000]').addClass('bg-[#8B0000] text-white');
        
        if (category === 'all') {
            $('.menu-item').show();
        } else {
            $('.menu-item').hide();
            $(`.menu-item[data-category="${category}"]`).show();
        }
    });

    // Cart functionality
    const cartToggle = $('#cartToggle');
    const cartSidebar = $('#cartSidebar');
    const closeCart = $('#closeCart');
    
    function updateCartDisplay() {
        $.ajax({
            url: '{{ route("cart.get") }}',
            method: 'GET',
            success: function(response) {
                console.log('Get cart response:', response); // Debug log
                
                if (response.status === 'success') {
                    const cartItems = response.cartItems || [];
                    let cartHtml = '';

                    if (cartItems.length > 0) {
                        cartItems.forEach(item => {
                            console.log('Processing cart item:', item); // Debug log
                            
                            cartHtml += `
                                <div class="flex items-center mb-4 cart-item" data-id="${item.id}">
                                    <img src="${item.image ? '/storage/' + item.image : '/images/default.jpg'}" class="w-16 h-16 object-cover rounded-lg mr-4">
                                    <div class="flex-1">
                                        <h4 class="font-medium">${item.name}</h4>
                                        <p class="text-[#8B0000]">Rp ${new Intl.NumberFormat('id-ID').format(item.price)}</p>
                                        <div class="flex items-center mt-2">
                                            <button class="decrease-qty bg-gray-200 px-2 py-1 rounded-l hover:bg-gray-300" data-cart-id="${item.id}">-</button>
                                            <input type="number" class="item-qty w-12 text-center border-y border-gray-200" value="${item.quantity}" min="1" data-cart-id="${item.id}">
                                            <button class="increase-qty bg-gray-200 px-2 py-1 rounded-r hover:bg-gray-300" data-cart-id="${item.id}">+</button>
                                            <button class="remove-item ml-2 text-red-500 hover:text-red-700" data-cart-id="${item.id}">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                    } else {
                        cartHtml = '<p class="text-gray-500 text-center">Keranjang kosong</p>';
                    }

                    $('.cart-items').html(cartHtml);
                    $('#cartTotal').text('Rp ' + new Intl.NumberFormat('id-ID').format(response.totalHarga || 0));
                    $('.cart-count').text(response.cartCount || 0);
                } else {
                    console.error('Get cart failed:', response);
                }
            },
            error: function(xhr, status, error) {
                console.error('Get cart error:', {xhr, status, error});
            }
        });
    }

    // Toggle cart sidebar
    cartToggle.click(function() {
        cartSidebar.toggleClass('translate-x-full');
        updateCartDisplay();
    });

    closeCart.click(function() {
        cartSidebar.addClass('translate-x-full');
    });

    // Add to cart
    $('.add-to-cart').click(function() {
        const menuId = $(this).data('id');
        const button = $(this);
        
        // Disable button to prevent double submission
        button.prop('disabled', true);
        
        // Check if user is authenticated
        if (!$('meta[name="csrf-token"]').attr('content')) {
            Swal.fire({
                title: 'Error!',
                text: 'Silakan login terlebih dahulu',
                icon: 'error'
            }).then(() => {
                window.location.href = '{{ route("login") }}';
            });
            button.prop('disabled', false);
            return;
        }
        
        $.ajax({
            url: '{{ route("cart.add") }}',
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            data: JSON.stringify({
                menu_id: menuId
            }),
            success: function(response) {
                console.log('Add to cart response:', response);
                
                if (response.status === 'success') {
                    // Show success message
                    Swal.fire({
                        title: 'Berhasil!',
                        text: response.message,
                        icon: 'success',
                        timer: 1500,
                        showConfirmButton: false
                    });
                    
                    // Update cart display
                    updateCartDisplay();
                    cartSidebar.removeClass('translate-x-full');
                } else {
                    console.error('Add to cart failed:', response);
                    Swal.fire({
                        title: 'Gagal!',
                        text: response.message || 'Gagal menambahkan item ke keranjang',
                        icon: 'error'
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('Add to cart error:', {xhr, status, error});
                let errorMessage = 'Gagal menambahkan item ke keranjang';
                
                if (xhr.status === 401) {
                    errorMessage = 'Silakan login terlebih dahulu';
                    window.location.href = '{{ route("login") }}';
                } else if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                }
                
                Swal.fire({
                    title: 'Error!',
                    text: errorMessage,
                    icon: 'error'
                });
            },
            complete: function() {
                // Re-enable button
                button.prop('disabled', false);
            }
        });
    });

    // Update quantity
    $(document).on('click', '.decrease-qty, .increase-qty', function() {
        const cartId = $(this).data('cart-id');
        const qtyInput = $(this).siblings('.item-qty');
        let quantity = parseInt(qtyInput.val());

        if ($(this).hasClass('increase-qty')) {
            quantity++;
        } else {
            quantity = Math.max(1, quantity - 1);
        }

        updateCartQuantity(cartId, quantity);
    });

    // Handle manual input change
    $(document).on('change', '.item-qty', function() {
        const cartId = $(this).data('cart-id');
        const quantity = Math.max(1, parseInt($(this).val()) || 1);
        $(this).val(quantity); // Ensure the display shows valid number
        updateCartQuantity(cartId, quantity);
    });

    function updateCartQuantity(cartId, quantity) {
        $.ajax({
            url: '{{ route("cart.update") }}',
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: {
                cart_id: cartId,
                quantity: quantity
            },
            success: function(response) {
                if (response.status === 'success') {
                    // Update cart display with new data
                    const cartItems = response.cartItems;
                    let cartHtml = '';

                    if (cartItems && cartItems.length > 0) {
                        cartItems.forEach(item => {
                            cartHtml += `
                                <div class="flex items-center mb-4 cart-item" data-id="${item.id}">
                                    <img src="${item.image ? '/storage/' + item.image : '/images/default.jpg'}" class="w-16 h-16 object-cover rounded-lg mr-4">
                                    <div class="flex-1">
                                        <h4 class="font-medium">${item.name}</h4>
                                        <p class="text-[#8B0000]">Rp ${new Intl.NumberFormat('id-ID').format(item.price)}</p>
                                        <div class="flex items-center mt-2">
                                            <button class="decrease-qty bg-gray-200 px-2 py-1 rounded-l hover:bg-gray-300" data-cart-id="${item.id}">-</button>
                                            <input type="number" class="item-qty w-12 text-center border-y border-gray-200" value="${item.quantity}" min="1" data-cart-id="${item.id}">
                                            <button class="increase-qty bg-gray-200 px-2 py-1 rounded-r hover:bg-gray-300" data-cart-id="${item.id}">+</button>
                                            <button class="remove-item ml-2 text-red-500 hover:text-red-700" data-cart-id="${item.id}">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                    } else {
                        cartHtml = '<p class="text-gray-500 text-center">Keranjang kosong</p>';
                    }

                    $('.cart-items').html(cartHtml);
                    $('#cartTotal').text('Rp ' + new Intl.NumberFormat('id-ID').format(response.totalHarga));
                    $('.cart-count').text(response.cartCount || 0);
                }
            },
            error: function(xhr, status, error) {
                console.error('Update Error:', error);
                // Revert the input value on error
                updateCartDisplay();
            }
        });
    }

    // Remove item
    $(document).on('click', '.remove-item', function() {
        const cartId = $(this).data('cart-id');

        $.ajax({
            url: '{{ route("cart.remove") }}',
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: {
                cart_id: cartId
            },
            success: function(response) {
                if (response.status === 'success') {
                    updateCartDisplay();
                }
            }
        });
    });

    // Initial cart display
    updateCartDisplay();
});
</script>
@endpush
@endsection
