

<?php $__env->startSection('title', 'Menu - Chingu Bite'); ?>

<?php $__env->startSection('content'); ?>
<div class="container py-5">
    <!-- Success/Error Messages -->
    <?php if(session('success')): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i><?php echo e(session('success')); ?>

        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <?php if(session('error')): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i><?php echo e(session('error')); ?>

        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <!-- Debug Info -->
    <?php if(config('app.debug')): ?>
    <div class="alert alert-info">
        <strong>Debug Info:</strong> 
        <?php if(auth()->guard()->check()): ?>
            Logged in as: <?php echo e(Auth::user()->name); ?> (<?php echo e(Auth::user()->email); ?>)
        <?php else: ?>
            Not logged in
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <!-- Page Header -->
    <div class="row mb-5">
        <div class="col-md-12 text-center">
            <h1 class="display-4 mb-3">Our Delicious Menu</h1>
            <p class="lead text-muted">Authentic Korean cuisine made with passion and fresh ingredients</p>
        </div>
    </div>

    <!-- Search and Filter Section -->
    <div class="row mb-4">
        <div class="col-md-8">
            <div class="input-group shadow-sm">
                <span class="input-group-text bg-white border-end-0">
                    <i class="fas fa-search text-muted"></i>
                </span>
                <input type="text" id="menu-search" class="form-control border-start-0 py-3" 
                       placeholder="Search for dishes...">
            </div>
        </div>
        <div class="col-md-4">
            <select id="category-filter" class="form-select py-3 shadow-sm">
                <option value="">All Categories</option>
                <?php
                    // FILTER KATEGORI: Hilangkan duplikat berdasarkan nama
                    $uniqueCategories = collect($categories);
                    
                    // Jika $categories adalah array dari API response
                    if (is_array($categories)) {
                        $uniqueCategories = collect($categories)
                            ->unique('name')
                            ->values();
                    } 
                    // Jika $categories adalah Eloquent Collection
                    else if (is_object($categories) && method_exists($categories, 'unique')) {
                        $uniqueCategories = $categories
                            ->unique('name')
                            ->values();
                    }
                ?>
                
                <?php $__currentLoopData = $uniqueCategories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php
                        $categoryId = $category['id'] ?? $category->id ?? '';
                        $categoryName = $category['name'] ?? $category->name ?? 'Unknown';
                    ?>
                    <option value="<?php echo e($categoryId); ?>"><?php echo e($categoryName); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </select>
        </div>
    </div>

    <!-- Categories Navigation -->
    <div class="row mb-5">
        <div class="col-md-12">
            <div class="d-flex flex-wrap gap-2 justify-content-center category-scroll">
                <button class="btn btn-outline-primary active" data-category="">All</button>
                
                <?php
                    // FILTER TOMBOL KATEGORI: Hilangkan duplikat
                    $uniqueCategoryButtons = collect($categories);
                    
                    if (is_array($categories)) {
                        $uniqueCategoryButtons = collect($categories)
                            ->unique('name')
                            ->values();
                    } else if (is_object($categories) && method_exists($categories, 'unique')) {
                        $uniqueCategoryButtons = $categories
                            ->unique('name')
                            ->values();
                    }
                ?>
                
                <?php $__currentLoopData = $uniqueCategoryButtons; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php
                        $categoryId = $category['id'] ?? $category->id ?? '';
                        $categoryName = $category['name'] ?? $category->name ?? 'Unknown';
                    ?>
                    <button class="btn btn-outline-primary" data-category="<?php echo e($categoryId); ?>">
                        <?php echo e($categoryName); ?>

                    </button>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                
                <!-- Special Categories -->
                <button class="btn btn-outline-warning" data-category="special">
                    <i class="fas fa-star me-1"></i> Special
                </button>
                <button class="btn btn-outline-danger" data-category="best-seller">
                    <i class="fas fa-fire me-1"></i> Best Seller
                </button>
            </div>
        </div>
    </div>

    <!-- Menu Grid -->
    <div class="row g-4" id="menu-container">
        <?php
            // FILTER MENU UTAMA: Hilangkan duplikat berdasarkan multiple criteria
            $uniqueMenus = collect();
            
            if (is_array($menus)) {
                // Jika $menus adalah array dari API response
                $uniqueMenus = collect($menus)
                    ->unique(function($item) {
                        // Gunakan kombinasi nama + kategori ID untuk deteksi duplikat
                        $name = $item['name'] ?? $item->name ?? '';
                        $categoryId = $item['category_id'] ?? $item->category_id ?? '';
                        $price = $item['price'] ?? $item->price ?? 0;
                        
                        // Hash unik berdasarkan nama, kategori, dan harga
                        return md5(strtolower($name) . '_' . $categoryId . '_' . $price);
                    })
                    ->values();
                    
            } else if (is_object($menus) && method_exists($menus, 'unique')) {
                // Jika $menus adalah Eloquent Collection
                $uniqueMenus = $menus
                    ->unique(function($item) {
                        // Gunakan kombinasi nama + kategori ID untuk deteksi duplikat
                        $name = $item->name ?? '';
                        $categoryId = $item->category_id ?? '';
                        $price = $item->price ?? 0;
                        
                        // Hash unik berdasarkan nama, kategori, dan harga
                        return md5(strtolower($name) . '_' . $categoryId . '_' . $price);
                    })
                    ->values();
            }
            
            // Debug log untuk melihat jumlah sebelum dan sesudah filter
            $originalCount = is_array($menus) ? count($menus) : ($menus ? $menus->count() : 0);
            $filteredCount = $uniqueMenus->count();
        ?>
        
        
        <?php if(config('app.debug')): ?>
            <div class="col-12 mb-3">
                <div class="alert alert-info small py-2">
                    <i class="fas fa-info-circle me-1"></i>
                    Menu items: <?php echo e($originalCount); ?> original, <?php echo e($filteredCount); ?> after duplicate removal
                </div>
            </div>
        <?php endif; ?>
        
        <?php $__empty_1 = true; $__currentLoopData = $uniqueMenus; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $menu): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
            <?php
                // Standardize data format untuk menghindari error
                $menuData = is_array($menu) ? $menu : $menu->toArray();
                
                $menuId = $menuData['id'] ?? $menu->id ?? '';
                $menuName = $menuData['name'] ?? $menu->name ?? 'Unknown Item';
                $menuDescription = $menuData['description'] ?? $menu->description ?? '';
                $menuPrice = $menuData['price'] ?? $menu->price ?? 0;
                $menuImage = $menuData['image'] ?? $menu->image ?? $menuData['image_url'] ?? $menu->image_url ?? '/images/default-food.jpg';
                $menuAvailable = $menuData['is_available'] ?? $menu->is_available ?? false;
                $menuRating = $menuData['rating'] ?? $menuData['average_rating'] ?? $menu->average_rating ?? 0;
                
                // Handle category data
                $menuCategoryName = '';
                $menuCategoryId = '';
                
                if (isset($menuData['category'])) {
                    $menuCategoryName = $menuData['category']['name'] ?? '';
                    $menuCategoryId = $menuData['category']['id'] ?? '';
                } else if (isset($menu->category)) {
                    $menuCategoryName = $menu->category->name ?? '';
                    $menuCategoryId = $menu->category->id ?? '';
                } else {
                    $menuCategoryName = $menuData['category_name'] ?? '';
                    $menuCategoryId = $menuData['category_id'] ?? '';
                }
                
                $menuOriginalPrice = $menuData['original_price'] ?? null;
                
                // Clean up data
                $menuName = htmlspecialchars($menuName, ENT_QUOTES, 'UTF-8');
                $menuDescription = htmlspecialchars($menuDescription, ENT_QUOTES, 'UTF-8');
                
                // Generate unique key untuk card
                $menuUniqueKey = md5($menuName . '_' . $menuCategoryId . '_' . $menuPrice);
            ?>
            
            <div class="col-xl-3 col-lg-4 col-md-6 col-sm-6 mb-4" data-menu-key="<?php echo e($menuUniqueKey); ?>">
                <div class="card menu-card h-100 shadow-sm border-0 hover-lift">
                    <!-- Menu Image -->
                    <div class="position-relative">
                        <img src="<?php echo e($menuImage); ?>" 
                             alt="<?php echo e($menuName); ?>" 
                             class="card-img-top menu-image" 
                             style="height: 200px; object-fit: cover;"
                             loading="lazy"
                             onerror="this.src='/images/default-food.jpg'">
                        
                        <!-- Availability Badge -->
                        <div class="position-absolute top-0 end-0 m-2">
                            <span class="badge <?php echo e($menuAvailable ? 'bg-success' : 'bg-danger'); ?>">
                                <?php echo e($menuAvailable ? 'Available' : 'Out of Stock'); ?>

                            </span>
                        </div>

                        <!-- Category Badge -->
                        <?php if(!empty($menuCategoryName)): ?>
                            <div class="position-absolute top-0 start-0 m-2">
                                <span class="badge bg-primary"><?php echo e($menuCategoryName); ?></span>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Menu Content -->
                    <div class="card-body d-flex flex-column">
                        <h5 class="card-title fw-bold text-dark mb-2"><?php echo e($menuName); ?></h5>
                        <p class="card-text text-muted small mb-3 flex-grow-1">
                            <?php echo e(Str::limit($menuDescription, 100)); ?>

                        </p>
                        
                        <!-- Rating -->
                        <?php if($menuRating > 0): ?>
                            <div class="mb-3">
                                <div class="d-flex align-items-center">
                                    <div class="text-warning">
                                        <?php for($i = 1; $i <= 5; $i++): ?>
                                            <?php if($i <= floor($menuRating)): ?>
                                                <i class="fas fa-star"></i>
                                            <?php elseif($i - 0.5 <= $menuRating): ?>
                                                <i class="fas fa-star-half-alt"></i>
                                            <?php else: ?>
                                                <i class="far fa-star"></i>
                                            <?php endif; ?>
                                        <?php endfor; ?>
                                    </div>
                                    <small class="text-muted ms-2">(<?php echo e(number_format($menuRating, 1)); ?>)</small>
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Price and Action -->
                        <div class="d-flex justify-content-between align-items-center mt-auto">
                            <div>
                                <h4 class="text-primary fw-bold mb-0">
                                    Rp <?php echo e(number_format($menuPrice, 0, ',', '.')); ?>

                                </h4>
                                <?php if($menuOriginalPrice && $menuOriginalPrice > $menuPrice): ?>
                                    <small class="text-muted text-decoration-line-through">
                                        Rp <?php echo e(number_format($menuOriginalPrice, 0, ',', '.')); ?>

                                    </small>
                                <?php endif; ?>
                            </div>
                            
                            <?php if($menuAvailable): ?>
                                <?php if(auth()->guard()->check()): ?>
                                    <form action="<?php echo e(route('customer.cart.store')); ?>" method="POST" class="d-inline">
                                        <?php echo csrf_field(); ?>
                                        <input type="hidden" name="menu_id" value="<?php echo e($menuId); ?>">
                                        <input type="hidden" name="quantity" value="1">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-plus me-1"></i> Add
                                        </button>
                                    </form>
                                <?php else: ?>
                                    <a href="<?php echo e(route('login')); ?>" class="btn btn-primary">
                                        <i class="fas fa-sign-in-alt me-1"></i> Login to Add
                                    </a>
                                <?php endif; ?>
                            <?php else: ?>
                                <button class="btn btn-outline-secondary" disabled>
                                    <i class="fas fa-ban me-1"></i> Unavailable
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="card-footer bg-transparent border-top-0 pt-0">
                        <div class="d-flex justify-content-between">
                            <a href="javascript:void(0)" class="text-decoration-none text-primary btn-view-details" 
                               data-menu-id="<?php echo e($menuId); ?>">
                                <i class="fas fa-info-circle me-1"></i> Details
                            </a>
                            <a href="javascript:void(0)" class="text-decoration-none text-warning btn-similar" 
                               data-category-id="<?php echo e($menuCategoryId); ?>"
                               data-category-name="<?php echo e($menuCategoryName); ?>">
                                <i class="fas fa-utensils me-1"></i> Similar
                            </a>
                            <?php if(auth()->guard()->check()): ?>
                                <a href="javascript:void(0)" class="text-decoration-none text-muted btn-favorite"
                                   data-menu-id="<?php echo e($menuId); ?>">
                                    <i class="far fa-heart"></i>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
            <div class="col-md-12 text-center py-5">
                <div class="empty-state">
                    <i class="fas fa-utensils fa-4x text-muted mb-4"></i>
                    <h3>No Menu Items Available</h3>
                    <p class="text-muted">We're currently updating our menu. Please check back later.</p>
                    <a href="<?php echo e(url('/')); ?>" class="btn btn-primary mt-3">
                        <i class="fas fa-home me-1"></i> Back to Home
                    </a>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Load More Button -->
    <?php if($filteredCount > 12): ?>
        <div class="row mt-4">
            <div class="col-md-12 text-center">
                <button id="load-more" class="btn btn-outline-primary px-5 py-2">
                    <i class="fas fa-spinner fa-spin d-none" id="loading-spinner"></i>
                    <span id="load-more-text">Load More</span>
                </button>
            </div>
        </div>
    <?php endif; ?>

    <!-- Loading Indicator -->
    <div id="loading-indicator" class="text-center py-4 d-none">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <p class="mt-2 text-muted">Loading menu items...</p>
    </div>

    <!-- No Results Message -->
    <div id="no-results" class="text-center py-5 d-none">
        <i class="fas fa-search fa-3x text-muted mb-3"></i>
        <h4>No Menu Items Found</h4>
        <p class="text-muted">Try adjusting your search or filter to find what you're looking for.</p>
    </div>
</div>

<!-- Menu Details Modal -->
<div class="modal fade" id="menuDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="menuModalTitle"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <img id="menuModalImage" src="" class="img-fluid rounded" alt=""
                             onerror="this.src='/images/default-food.jpg'">
                    </div>
                    <div class="col-md-6">
                        <h4 id="menuModalName" class="mb-3"></h4>
                        <p id="menuModalDescription" class="text-muted mb-4"></p>
                        
                        <div class="row mb-4">
                            <div class="col-6">
                                <h5 class="text-primary" id="menuModalPrice"></h5>
                                <small class="text-muted text-decoration-line-through d-none" id="menuModalOriginalPrice"></small>
                            </div>
                            <div class="col-6">
                                <div id="menuModalRating"></div>
                            </div>
                        </div>

                        <!-- Add to Cart Form -->
                        <div class="mb-4">
                            <label class="form-label">Quantity</label>
                            <div class="input-group" style="max-width: 200px;">
                                <button class="btn btn-outline-secondary" type="button" onclick="adjustQuantity(-1)">-</button>
                                <input type="number" id="menuQuantity" class="form-control text-center" value="1" min="1" max="10">
                                <button class="btn btn-outline-secondary" type="button" onclick="adjustQuantity(1)">+</button>
                            </div>
                        </div>

                        <!-- Special Instructions -->
                        <div class="mb-4">
                            <label class="form-label">Special Instructions (Optional)</label>
                            <textarea id="menuInstructions" class="form-control" rows="2" 
                                      placeholder="Any special requests?"></textarea>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="addToCartModalBtn">
                    <i class="fas fa-cart-plus me-2"></i> Add to Cart
                </button>
            </div>
        </div>
    </div>
</div>

<style>
.menu-card {
    transition: all 0.3s ease;
    border-radius: 15px;
    overflow: hidden;
    position: relative;
}

.menu-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 30px rgba(0,0,0,0.1) !important;
}

/* Prevent duplicate display */
#menu-container .col-xl-3[data-menu-key=""] {
    display: none !important;
}

#menu-container .col-xl-3:empty {
    display: none !important;
}

/* Duplicate warning badge */
.duplicate-warning {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(255, 193, 7, 0.9);
    color: #333;
    font-size: 0.7rem;
    padding: 2px 6px;
    border-radius: 4px;
    z-index: 10;
}

/* Category filter improvement */
.category-scroll {
    display: flex;
    overflow-x: auto;
    white-space: nowrap;
    -webkit-overflow-scrolling: touch;
    padding-bottom: 10px;
    scrollbar-width: thin;
    scrollbar-color: #e63946 #f8f9fa;
}

.category-scroll::-webkit-scrollbar {
    height: 6px;
}

.category-scroll::-webkit-scrollbar-track {
    background: #f8f9fa;
    border-radius: 3px;
}

.category-scroll::-webkit-scrollbar-thumb {
    background: #e63946;
    border-radius: 3px;
}

.category-scroll .btn {
    flex-shrink: 0;
    transition: all 0.2s;
}

.category-scroll .btn:hover {
    transform: translateY(-2px);
}

/* Loading states */
#loading-indicator {
    min-height: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

/* Toast styling */
.toast-container {
    z-index: 9999;
}

/* Cart update animation */
@keyframes cartBounce {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.2); }
}

.cart-updated {
    animation: cartBounce 0.3s ease;
}

/* Menu image fallback */
.menu-image {
    background-color: #f8f9fa;
    transition: transform 0.3s ease;
}

.menu-card:hover .menu-image {
    transform: scale(1.05);
}

/* Empty state */
.empty-state {
    padding: 3rem 1.5rem;
    background: linear-gradient(135deg, rgba(248, 249, 250, 0.8), rgba(255, 255, 255, 0.9));
    border-radius: 15px;
    border: 2px dashed #dee2e6;
}

.empty-state i {
    color: #adb5bd;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .menu-card {
        margin-bottom: 1rem;
    }
    
    .col-xl-3, .col-lg-4, .col-md-6, .col-sm-6 {
        padding-left: 8px;
        padding-right: 8px;
    }
    
    .category-scroll .btn {
        padding: 0.375rem 0.75rem;
        font-size: 0.875rem;
    }
}

/* Price styling */
.text-primary {
    color: #e63946 !important;
}

.bg-primary {
    background-color: #e63946 !important;
}

.btn-primary {
    background-color: #e63946;
    border-color: #e63946;
}

.btn-primary:hover {
    background-color: #c1121f;
    border-color: #c1121f;
}

.btn-outline-primary {
    color: #e63946;
    border-color: #e63946;
}

.btn-outline-primary:hover,
.btn-outline-primary.active {
    background-color: #e63946;
    border-color: #e63946;
    color: white;
}

/* Badge styling */
.badge {
    font-weight: 600;
    letter-spacing: 0.3px;
}

.bg-success {
    background-color: #2a9d8f !important;
}

.bg-danger {
    background-color: #e63946 !important;
}
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Global variables
    let currentPage = 1;
    let isLoading = false;
    let hasMore = false;
    let currentCategory = '';
    let currentSearch = '';
    let loadedMenuIds = new Set(); // Untuk tracking menu yang sudah dimuat berdasarkan ID
    let loadedMenuKeys = new Set(); // Untuk tracking menu yang sudah dimuat berdasarkan unique key

    // API Configuration
    const API_CONFIG = {
        baseUrl: '<?php echo e(config("app.api_url", "http://localhost:8000/api")); ?>',
        token: '<?php echo e(session("api_token")); ?>',
        isAuthenticated: <?php echo e(auth()->check() ? 'true' : 'false'); ?>

    };

    // Initialize
    initEventListeners();
    setupToastContainer();
    
    // Attach event listeners to existing menu items (rendered by server)
    attachMenuEventListeners();
    
    // DON'T auto-fetch on page load - menu already rendered by server
    // fetchMenus only triggered by user actions (search, filter, load more)

    // Fungsi untuk generate unique key untuk menu
    function generateMenuKey(menu) {
        const name = (menu.name || '').toLowerCase().trim();
        const categoryId = menu.category_id || menu.category?.id || '';
        const price = menu.price || 0;
        return md5(`${name}_${categoryId}_${price}`);
    }

    // MD5 hash function (simple version untuk unique key)
    function md5(str) {
        let hash = 0;
        if (str.length === 0) return hash.toString(16);
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash;
        }
        return Math.abs(hash).toString(16);
    }

    // Fungsi untuk filter menu duplikat di client side dengan multiple checks
    function filterDuplicateMenus(menus) {
        const uniqueMenus = [];
        const seenIds = new Set();
        const seenNames = new Set();
        const seenKeys = new Set();
        
        menus.forEach(menu => {
            const menuId = menu.id || menu.menu_id;
            const menuName = (menu.name || '').toLowerCase().trim();
            const menuKey = generateMenuKey(menu);
            
            // Cek berdasarkan 3 criteria: ID, Nama, dan Unique Key
            if (!seenIds.has(menuId) && !seenNames.has(menuName) && !seenKeys.has(menuKey)) {
                seenIds.add(menuId);
                seenNames.add(menuName);
                seenKeys.add(menuKey);
                uniqueMenus.push(menu);
            } else {
                console.log('Duplicate filtered:', {
                    id: menuId,
                    name: menuName,
                    key: menuKey
                });
            }
        });
        
        console.log(`Filtered: ${menus.length} -> ${uniqueMenus.length} unique menus`);
        return uniqueMenus;
    }

    // Fetch menus from API
    async function fetchMenus(append = false) {
        if (isLoading) return;
        
        isLoading = true;
        showLoading(!append);
        if (append) showLoadMoreLoading(true);
        hideNoResults();

        try {
            // Build query params
            const params = new URLSearchParams();
            params.append('page', currentPage);
            params.append('limit', 12);
            params.append('unique', 'true');
            
            if (currentSearch) params.append('search', currentSearch);
            if (currentCategory && !['special', 'best-seller'].includes(currentCategory)) {
                params.append('category_id', currentCategory);
            }

            // Determine endpoint
            let endpoint = '/customer/menu';
            if (currentCategory === 'special') {
                endpoint = '/customer/menu/special';
            }
            if (currentCategory === 'best-seller') {
                endpoint = '/customer/menu/best-seller';
            }

            const url = `${API_CONFIG.baseUrl}${endpoint}?${params}`;
            
            // Prepare headers
            const headers = {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            };
            
            // Add auth token if available
            if (API_CONFIG.token) {
                headers['Authorization'] = `Bearer ${API_CONFIG.token}`;
            }

            const response = await fetch(url, { headers });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }

            const result = await response.json();
            
            // Handle API response structure
            let menus = [];
            let pagination = null;
            
            if (result.success) {
                const data = result.data || {};
                menus = data.menus || data.data || result.data || [];
                pagination = data.pagination || data.meta || result.meta || null;
            } else {
                menus = result.data || result;
            }

            // Filter duplikat
            menus = filterDuplicateMenus(menus);

            // Filter menu yang sudah dimuat sebelumnya
            if (append) {
                menus = menus.filter(menu => {
                    const menuId = menu.id || menu.menu_id;
                    const menuKey = generateMenuKey(menu);
                    return !loadedMenuIds.has(menuId) && !loadedMenuKeys.has(menuKey);
                });
            }

            // Simpan ID dan key menu yang baru dimuat
            menus.forEach(menu => {
                const menuId = menu.id || menu.menu_id;
                const menuKey = generateMenuKey(menu);
                loadedMenuIds.add(menuId);
                loadedMenuKeys.add(menuKey);
            });

            // Render menus
            if (append) {
                appendMenus(menus);
            } else {
                renderMenus(menus);
            }

            // Update pagination
            hasMore = pagination ? (pagination.current_page < pagination.last_page) : false;
            updateLoadMoreButton();

            // Show/hide no results
            if (menus.length === 0 && currentPage === 1) {
                showNoResults();
            }

        } catch (error) {
            console.error('Error fetching menus:', error);
            showError('Failed to load menu. Please try again.');
            
        } finally {
            isLoading = false;
            showLoading(false);
            showLoadMoreLoading(false);
        }
    }

    // Render menus
    function renderMenus(menus) {
        const menuContainer = document.getElementById('menu-container');
        if (!menuContainer) return;
        
        if (!menus || menus.length === 0) {
            menuContainer.innerHTML = getNoResultsHTML();
            return;
        }

        // Clear previous content
        menuContainer.innerHTML = '';
        
        // Create document fragment for better performance
        const fragment = document.createDocumentFragment();
        
        menus.forEach(menu => {
            const menuKey = generateMenuKey(menu);
            const col = document.createElement('div');
            col.className = 'col-xl-3 col-lg-4 col-md-6 col-sm-6 mb-4';
            col.setAttribute('data-menu-key', menuKey);
            col.innerHTML = getMenuCardHTML(menu);
            fragment.appendChild(col);
        });
        
        menuContainer.appendChild(fragment);
        attachMenuEventListeners();
    }

    // Append menus for load more
    function appendMenus(menus) {
        const menuContainer = document.getElementById('menu-container');
        if (!menuContainer || !menus || menus.length === 0) return;
        
        const fragment = document.createDocumentFragment();
        menus.forEach(menu => {
            const menuKey = generateMenuKey(menu);
            const col = document.createElement('div');
            col.className = 'col-xl-3 col-lg-4 col-md-6 col-sm-6 mb-4';
            col.setAttribute('data-menu-key', menuKey);
            col.innerHTML = getMenuCardHTML(menu);
            fragment.appendChild(col);
        });
        
        menuContainer.appendChild(fragment);
        attachMenuEventListeners();
    }

    // Get menu card HTML
    function getMenuCardHTML(menu) {
        const imageUrl = menu.image_url || menu.image || '/images/default-food.jpg';
        const description = menu.description ? 
            (menu.description.length > 100 ? menu.description.substring(0, 100) + '...' : menu.description) : 
            'No description available';
        
        const rating = menu.rating || 0;
        const categoryName = menu.category?.name || menu.category_name || '';
        const isAvailable = menu.is_available !== false;
        const hasDiscount = menu.original_price && menu.original_price > menu.price;
        const menuKey = generateMenuKey(menu);
        
        return `
            <div class="card menu-card h-100 shadow-sm border-0 hover-lift" data-menu-id="${menu.id}" data-menu-key="${menuKey}">
                <div class="position-relative">
                    <img src="${imageUrl}" 
                         alt="${menu.name}" 
                         class="card-img-top menu-image" 
                         style="height: 200px; object-fit: cover;"
                         onerror="this.src='/images/default-food.jpg'">
                    
                    <div class="position-absolute top-0 end-0 m-2">
                        <span class="badge ${isAvailable ? 'bg-success' : 'bg-danger'}">
                            ${isAvailable ? 'Available' : 'Out of Stock'}
                        </span>
                    </div>

                    ${categoryName ? `
                        <div class="position-absolute top-0 start-0 m-2">
                            <span class="badge bg-primary">${categoryName}</span>
                        </div>
                    ` : ''}
                </div>

                <div class="card-body d-flex flex-column">
                    <h5 class="card-title fw-bold text-dark mb-2">${menu.name}</h5>
                    <p class="card-text text-muted small mb-3 flex-grow-1">
                        ${description}
                    </p>
                    
                    ${rating > 0 ? `
                        <div class="mb-3">
                            <div class="d-flex align-items-center">
                                <div class="text-warning">
                                    ${generateStarRating(rating)}
                                </div>
                                <small class="text-muted ms-2">(${rating.toFixed(1)})</small>
                            </div>
                        </div>
                    ` : ''}

                    <div class="d-flex justify-content-between align-items-center mt-auto">
                        <div>
                            <h4 class="text-primary fw-bold mb-0">
                                Rp ${formatPrice(menu.price)}
                            </h4>
                            ${hasDiscount ? `
                                <small class="text-muted text-decoration-line-through">
                                    Rp ${formatPrice(menu.original_price)}
                                </small>
                            ` : ''}
                        </div>
                        
                        ${isAvailable ? `
                            <button class="btn btn-primary btn-add-cart" 
                                    data-menu-id="${menu.id}"
                                    data-menu-name="${menu.name}"
                                    data-menu-price="${menu.price}">
                                <i class="fas fa-plus me-1"></i> Add
                            </button>
                        ` : `
                            <button class="btn btn-outline-secondary" disabled>
                                <i class="fas fa-ban me-1"></i> Unavailable
                            </button>
                        `}
                    </div>
                </div>

                <div class="card-footer bg-transparent border-top-0 pt-0">
                    <div class="d-flex justify-content-between">
                        <a href="#" class="text-decoration-none text-primary btn-view-details" 
                           data-menu-id="${menu.id}">
                            <i class="fas fa-info-circle me-1"></i> Details
                        </a>
                        <a href="#" class="text-decoration-none text-warning btn-similar" 
                           data-category-id="${menu.category_id || ''}"
                           data-category-name="${categoryName}">
                            <i class="fas fa-utensils me-1"></i> Similar
                        </a>
                        <?php if(auth()->guard()->check()): ?>
                            <a href="#" class="text-decoration-none text-muted btn-favorite"
                               data-menu-id="${menu.id}">
                                <i class="far fa-heart"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        `;
    }

    // Attach event listeners to menu cards
    function attachMenuEventListeners() {
        console.log('Attaching event listeners to menu cards...');
        
        // Add to cart buttons
        const addButtons = document.querySelectorAll('.btn-add-cart');
        console.log(`Found ${addButtons.length} add-to-cart buttons`);
        
        addButtons.forEach(button => {
            button.addEventListener('click', async function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                console.log('=== ADD TO CART BUTTON CLICKED ===');
                alert('Button clicked! Check console for details.');
                
                const menuId = this.dataset.menuId;
                const menuName = this.dataset.menuName || 'item';
                
                console.log('Menu ID:', menuId, 'Menu Name:', menuName);
                
                await addToCart(menuId, 1, '', menuName);
            });
        });
        
        // View details buttons
        document.querySelectorAll('.btn-view-details').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const menuId = this.dataset.menuId;
                showMenuDetails(menuId);
            });
        });

        // Similar items buttons
        document.querySelectorAll('.btn-similar').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const categoryId = this.dataset.categoryId;
                const categoryName = this.dataset.categoryName || 'Similar Items';
                if (categoryId) {
                    document.getElementById('category-filter').value = categoryId;
                    document.querySelectorAll('[data-category]').forEach(btn => {
                        btn.classList.remove('active');
                        if (btn.dataset.category === categoryId) {
                            btn.classList.add('active');
                        }
                    });
                    currentCategory = categoryId;
                    resetAndFetch();
                    showToast(`Showing ${categoryName}`, 'info');
                }
            });
        });
    }

    // Event Listeners untuk filter
    function initEventListeners() {
        // Category buttons
        document.querySelectorAll('[data-category]').forEach(button => {
            button.addEventListener('click', function() {
                document.querySelectorAll('[data-category]').forEach(btn => btn.classList.remove('active'));
                this.classList.add('active');
                currentCategory = this.dataset.category || '';
                document.getElementById('category-filter').value = 
                    (currentCategory && !['special', 'best-seller'].includes(currentCategory)) ? currentCategory : '';
                resetAndFetch();
            });
        });

        // Search with debounce
        let searchTimeout;
        document.getElementById('menu-search').addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                currentSearch = this.value.trim();
                resetAndFetch();
            }, 500);
        });

        // Category filter select
        document.getElementById('category-filter').addEventListener('change', function() {
            currentCategory = this.value;
            document.querySelectorAll('[data-category]').forEach(btn => {
                btn.classList.toggle('active', 
                    btn.dataset.category === currentCategory || 
                    (!currentCategory && btn.dataset.category === ''));
            });
            resetAndFetch();
        });

        // Load more button
        const loadMoreBtn = document.getElementById('load-more');
        if (loadMoreBtn) {
            loadMoreBtn.addEventListener('click', loadMore);
        }
    }

    function resetAndFetch() {
        currentPage = 1;
        hasMore = false;
        loadedMenuIds.clear();
        loadedMenuKeys.clear();
        fetchMenus();
    }

    function loadMore() {
        if (!isLoading && hasMore) {
            currentPage++;
            fetchMenus(true);
        }
    }

    // Helper functions
    function generateStarRating(rating) {
        let stars = '';
        for (let i = 1; i <= 5; i++) {
            if (i <= Math.floor(rating)) {
                stars += '<i class="fas fa-star"></i>';
            } else if (i - 0.5 <= rating) {
                stars += '<i class="fas fa-star-half-alt"></i>';
            } else {
                stars += '<i class="far fa-star"></i>';
            }
        }
        return stars;
    }
    
    function formatPrice(price) {
        if (!price) return '0';
        return parseFloat(price).toLocaleString('id-ID', {
            minimumFractionDigits: 0,
            maximumFractionDigits: 0
        });
    }
    
    function getNoResultsHTML() {
        return `
            <div class="col-md-12 text-center py-5">
                <div class="empty-state">
                    <i class="fas fa-search fa-4x text-muted mb-4"></i>
                    <h3>No Menu Items Found</h3>
                    <p class="text-muted">Try adjusting your search or filter to find what you're looking for.</p>
                    <button class="btn btn-outline-primary mt-3" onclick="resetFilters()">
                        <i class="fas fa-redo me-1"></i> Reset Filters
                    </button>
                </div>
            </div>
        `;
    }

    // UI Control functions
    function showLoading(show) {
        const loadingIndicator = document.getElementById('loading-indicator');
        const loadMoreBtn = document.getElementById('load-more');
        
        if (show) {
            loadingIndicator?.classList.remove('d-none');
            loadMoreBtn?.classList.add('d-none');
        } else {
            loadingIndicator?.classList.add('d-none');
        }
    }
    
    function showLoadMoreLoading(show) {
        const spinner = document.getElementById('loading-spinner');
        const text = document.getElementById('load-more-text');
        const loadMoreBtn = document.getElementById('load-more');
        
        if (spinner && text && loadMoreBtn) {
            if (show) {
                spinner.classList.remove('d-none');
                text.textContent = 'Loading...';
                loadMoreBtn.disabled = true;
            } else {
                spinner.classList.add('d-none');
                text.textContent = 'Load More';
                loadMoreBtn.disabled = false;
            }
        }
    }
    
    function updateLoadMoreButton() {
        const loadMoreBtn = document.getElementById('load-more');
        if (loadMoreBtn) {
            loadMoreBtn.style.display = hasMore ? 'block' : 'none';
        }
    }
    
    function showNoResults() {
        const noResults = document.getElementById('no-results');
        noResults?.classList.remove('d-none');
    }
    
    function hideNoResults() {
        const noResults = document.getElementById('no-results');
        noResults?.classList.add('d-none');
    }

    // Toast notification system
    function setupToastContainer() {
        if (!document.getElementById('toast-container')) {
            const container = document.createElement('div');
            container.id = 'toast-container';
            container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
            container.style.zIndex = '1050';
            document.body.appendChild(container);
        }
    }
    
    function showToast(message, type = 'success') {
        const container = document.getElementById('toast-container');
        if (!container) return;
        
        const toastId = 'toast-' + Date.now();
        const icon = type === 'success' ? 'check-circle' : 
                    type === 'error' ? 'exclamation-triangle' :
                    type === 'warning' ? 'exclamation-circle' : 'info-circle';
        
        const toast = document.createElement('div');
        toast.id = toastId;
        toast.className = `toast align-items-center text-bg-${type} border-0`;
        toast.setAttribute('role', 'alert');
        toast.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">
                    <i class="fas fa-${icon} me-2"></i>
                    ${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        `;
        
        container.appendChild(toast);
        const bsToast = new bootstrap.Toast(toast, { delay: 3000 });
        bsToast.show();
        
        toast.addEventListener('hidden.bs.toast', () => toast.remove());
    }
    
    function showError(message) {
        showToast(message, 'error');
    }

    // Global function untuk reset filters
    window.resetFilters = function() {
        document.getElementById('menu-search').value = '';
        document.getElementById('category-filter').value = '';
        document.querySelectorAll('[data-category]').forEach(btn => {
            btn.classList.remove('active');
            if (btn.dataset.category === '') {
                btn.classList.add('active');
            }
        });
        currentCategory = '';
        currentSearch = '';
        resetAndFetch();
    };

    // Initial cart count jika authenticated
    if (API_CONFIG.isAuthenticated && API_CONFIG.token) {
        // updateCartCount(); // Uncomment jika diperlukan
    }

    // Add to cart function - using AJAX POST without page refresh
    async function addToCart(menuId, quantity, instructions, menuName) {
        console.log('addToCart called:', {menuId, quantity, instructions, menuName});
        
        <?php if(auth()->guard()->guest()): ?>
        console.log('User not authenticated, redirecting to login');
        alert('Please login to add items to cart');
        window.location.href = '<?php echo e(route("login")); ?>';
        return;
        <?php endif; ?>
        
        try {
            console.log('User is authenticated, proceeding...');
            
            // Show loading state
            const buttons = document.querySelectorAll(`[data-menu-id="${menuId}"]`);
            console.log('Found buttons:', buttons.length);
            
            buttons.forEach(btn => {
                btn.disabled = true;
                btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Adding...';
            });

            const formData = new FormData();
            formData.append('menu_id', menuId);
            formData.append('quantity', quantity);
            if (instructions) {
                formData.append('notes', instructions);
            }
            
            console.log('Sending POST to:', '<?php echo e(route("customer.cart.store")); ?>');
            console.log('FormData:', {
                menu_id: menuId,
                quantity: quantity,
                notes: instructions
            });

            const response = await fetch('<?php echo e(route("customer.cart.store")); ?>', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                    'Accept': 'application/json',
                },
                body: formData
            });

            console.log('Response status:', response.status);
            console.log('Response ok:', response.ok);
            
            let data;
            try {
                data = await response.json();
                console.log('Response data:', data);
            } catch (jsonError) {
                console.error('Failed to parse JSON:', jsonError);
                const text = await response.text();
                console.error('Response text:', text);
                throw new Error('Invalid JSON response from server');
            }

            // Reset buttons
            buttons.forEach(btn => {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-plus me-1"></i> Add';
            });

            if (response.ok && data.success) {
                console.log('✓ Item added to cart successfully');
                showToast(`${menuName} added to cart!`, 'success');
            } else {
                console.error('✗ Failed to add to cart:', data.message);
                showToast(data.message || 'Failed to add to cart', 'error');
            }
        } catch (error) {
            console.error('Add to cart error:', error);
            showToast('Failed to add to cart: ' + error.message, 'error');
            
            // Reset buttons on error
            const buttons = document.querySelectorAll(`[data-menu-id="${menuId}"]`);
            buttons.forEach(btn => {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-plus me-1"></i> Add';
            });
        }
    }

    // Quantity adjustment for modal
    window.adjustQuantity = function(change) {
        const quantityInput = document.getElementById('menuQuantity');
        let currentValue = parseInt(quantityInput.value) || 1;
        currentValue += change;
        if (currentValue < 1) currentValue = 1;
        if (currentValue > 10) currentValue = 10;
        quantityInput.value = currentValue;
    };

    // Show menu details
    window.showMenuDetails = async function(menuId) {
        try {
            const response = await fetch(`${API_CONFIG.baseUrl}/customer/menu/${menuId}`, {
                headers: {
                    'Authorization': API_CONFIG.token ? `Bearer ${API_CONFIG.token}` : '',
                    'Accept': 'application/json'
                }
            });
            
            if (!response.ok) throw new Error('Failed to fetch menu details');
            
            const result = await response.json();
            const menu = result.data?.menu || result.data || result;
            
            // Populate modal
            document.getElementById('menuModalTitle').textContent = menu.name;
            document.getElementById('menuModalName').textContent = menu.name;
            document.getElementById('menuModalDescription').textContent = menu.description || 'No description available';
            document.getElementById('menuModalPrice').textContent = `Rp ${formatPrice(menu.price)}`;
            document.getElementById('menuModalImage').src = menu.image_url || menu.image || '/images/default-food.jpg';
            
            // Handle rating
            const ratingElement = document.getElementById('menuModalRating');
            const rating = menu.rating || menu.average_rating || 0;
            if (rating > 0) {
                ratingElement.innerHTML = `
                    <div class="text-warning">
                        ${generateStarRating(rating)}
                    </div>
                    <small class="text-muted">(${rating.toFixed(1)})</small>
                `;
            } else {
                ratingElement.innerHTML = '<small class="text-muted">No ratings yet</small>';
            }
            
            // Handle discount
            const originalPriceElement = document.getElementById('menuModalOriginalPrice');
            if (menu.original_price && menu.original_price > menu.price) {
                originalPriceElement.textContent = `Rp ${formatPrice(menu.original_price)}`;
                originalPriceElement.classList.remove('d-none');
            } else {
                originalPriceElement.classList.add('d-none');
            }
            
            // Set up add to cart button in modal
            const addToCartBtn = document.getElementById('addToCartModalBtn');
            addToCartBtn.onclick = function() {
                const quantity = parseInt(document.getElementById('menuQuantity').value) || 1;
                const instructions = document.getElementById('menuInstructions').value;
                addToCart(menuId, quantity, instructions, menu.name);
                
                // Close modal
                const modal = bootstrap.Modal.getInstance(document.getElementById('menuDetailsModal'));
                if (modal) modal.hide();
            };
            
            // Show modal
            const modal = new bootstrap.Modal(document.getElementById('menuDetailsModal'));
            modal.show();
            
        } catch (error) {
            console.error('Menu details error:', error);
            showToast('Failed to load menu details', 'error');
        }
    };
});
</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\PABW\Chingu-Bite-fix\resources\views\customer\menu\index.blade.php ENDPATH**/ ?>