<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <title>Product Management - Ryll Store</title>
    <link rel="icon" type="image/webp" href="<?php echo e(asset('images/ryll.webp')); ?>">

    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        .font-orbitron {
            font-family: 'Orbitron', sans-serif;
        }

        [x-cloak] {
            display: none !important;
        }
        
        /* Mobile card view */
        @media (max-width: 768px) {
            .table-desktop { display: none; }
            .cards-mobile { display: block; }
        }
        
        @media (min-width: 769px) {
            .table-desktop { display: table; }
            .cards-mobile { display: none; }
        }

        /* Sortable column hover */
        .sortable-header {
            cursor: pointer;
            user-select: none;
        }
        
        .sortable-header:hover {
            background-color: rgba(6, 182, 212, 0.1);
        }
    </style>
</head>

<body class="bg-gray-950 text-white" x-data="productManager()">

    <!-- Header with Sync Button -->
    <div class="bg-gray-900 border-b border-cyan-500/20 p-4 md:p-6">
        <div class="max-w-7xl mx-auto">
            <!-- NAVBAR -->
            <?php echo $__env->make('components.admin-navbar', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
            <br>

            <!-- Header -->
            <div class="mb-4 md:mb-6">
                <h1 class="text-2xl md:text-3xl font-bold text-cyan-400 font-orbitron mb-2">📦 PRODUCT MANAGEMENT</h1>
                <p class="text-sm md:text-base text-gray-400">Sync produk tina VIP RESELLER API jeung atur harga jual</p>
            </div>

            <!-- ✅ ENHANCED STATS (4 → 6 cards) -->
            <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 md:gap-4 mb-6">
                <div class="bg-gradient-to-br from-cyan-500/10 to-blue-500/10 border border-cyan-500/30 rounded-xl p-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-cyan-500/20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-box text-cyan-400"></i>
                        </div>
                        <div>
                            <p class="text-2xl font-black text-white"><?php echo e($totalProducts); ?></p>
                            <p class="text-xs text-gray-400">Total</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-green-500/10 to-emerald-500/10 border border-green-500/30 rounded-xl p-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-green-500/20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-check-circle text-green-400"></i>
                        </div>
                        <div>
                            <p class="text-2xl font-black text-white"><?php echo e($activeProducts); ?></p>
                            <p class="text-xs text-gray-400">Active</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-red-500/10 to-orange-500/10 border border-red-500/30 rounded-xl p-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-red-500/20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-times-circle text-red-400"></i>
                        </div>
                        <div>
                            <p class="text-2xl font-black text-white"><?php echo e($totalProducts - $activeProducts); ?></p>
                            <p class="text-xs text-gray-400">Inactive</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-yellow-500/10 to-orange-500/10 border border-yellow-500/30 rounded-xl p-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-yellow-500/20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-percentage text-yellow-400"></i>
                        </div>
                        <div>
                            <?php
                                $avgMarkup = DB::table('products')
                                    ->whereNotNull('selling_price')
                                    ->where('price', '>', 0)
                                    ->selectRaw('AVG((selling_price - price) / price * 100) as avg_markup')
                                    ->value('avg_markup');
                            ?>
                            <p class="text-2xl font-black text-white"><?php echo e(number_format($avgMarkup ?? 0, 1)); ?>%</p>
                            <p class="text-xs text-gray-400">Avg Markup</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-purple-500/10 to-pink-500/10 border border-purple-500/30 rounded-xl p-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-coins text-purple-400"></i>
                        </div>
                        <div>
                            <?php
                                $totalValue = DB::table('products')->sum('selling_price');
                            ?>
                            <p class="text-lg font-black text-white"><?php echo e(number_format($totalValue / 1000, 0)); ?>K</p>
                            <p class="text-xs text-gray-400">Total Value</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-blue-500/10 to-indigo-500/10 border border-blue-500/30 rounded-xl p-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-blue-500/20 rounded-lg flex items-center justify-center">
                            <i class="fas fa-clock text-blue-400"></i>
                        </div>
                        <div>
                            <p class="text-xs font-bold text-white">
                                <?php if($lastSync): ?>
                                <?php echo e(\Carbon\Carbon::parse($lastSync)->diffForHumans()); ?>

                                <?php else: ?>
                                Never
                                <?php endif; ?>
                            </p>
                            <p class="text-xs text-gray-400">Last Sync</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Edit Banner Section (Keep as is) -->
            <div x-data="bannerManager()">
                <form action="<?php echo e(route('account.categories.update-banner')); ?>" method="POST" enctype="multipart/form-data" class="mb-8">
                    <?php echo csrf_field(); ?>
                    <div class="bg-gray-900/50 p-6 rounded-2xl border border-cyan-500/20">
                        <label class="block text-xs font-bold text-cyan-400 mb-4 font-orbitron uppercase tracking-widest">
                            <i class="fas fa-plus-circle mr-2"></i>Tambah Banner Utama Baru
                        </label>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div class="w-full h-44 bg-gray-950 rounded-xl border border-gray-800 flex items-center justify-center overflow-hidden shadow-inner">
                                <template x-if="newBannerPreview">
                                    <img :src="newBannerPreview" class="w-full h-full object-cover">
                                </template>
                                <template x-if="!newBannerPreview">
                                    <div class="text-center">
                                        <i class="fas fa-cloud-upload-alt text-gray-700 text-3xl mb-2"></i>
                                        <p class="text-gray-600 text-[10px] italic">Preview banner baru akan muncul di sini</p>
                                    </div>
                                </template>
                            </div>

                            <div class="flex flex-col justify-center space-y-4">
                                <div>
                                    <label class="block text-[10px] text-gray-500 mb-2 font-orbitron uppercase tracking-widest">Pilih File Gambar (Rasio 21:9 atau 16:9)</label>
                                    <input type="file" name="banner" @change="previewNewBanner($event)" required
                                           class="w-full text-xs text-gray-400 file:mr-3 file:py-2 file:px-4 file:rounded file:border-0 file:text-xs file:font-bold file:bg-cyan-500 file:text-white hover:file:bg-cyan-600 cursor-pointer transition-all">
                                </div>

                                <div class="pt-2">
                                    <button type="submit" class="w-full py-3 bg-gradient-to-r from-cyan-600 to-blue-600 rounded-lg font-bold text-xs font-orbitron tracking-widest hover:scale-[1.02] transition shadow-lg shadow-cyan-500/20 uppercase">
                                        Upload ke Slider
                                    </button>
                                </div>
                                <p class="text-[9px] text-gray-500 italic">*Setiap upload akan menambah slide baru di halaman depan.</p>
                            </div>
                        </div>
                    </div>
                </form>

                <div class="bg-gray-900/30 p-6 rounded-2xl border border-gray-800 mb-6">
                    <label class="block text-xs font-bold text-gray-400 mb-6 font-orbitron uppercase tracking-widest">
                        <i class="fas fa-images mr-2 text-cyan-500"></i>Banner Terpasang (Slider Utama)
                    </label>

                    <?php $activeSliders = DB::table('sliders')->orderBy('id', 'desc')->get(); ?>

                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php $__empty_1 = true; $__currentLoopData = $activeSliders; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $slide): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                            <div class="relative group bg-gray-950 rounded-xl overflow-hidden border border-gray-800 hover:border-cyan-500/50 transition-all duration-300 shadow-lg">
                                <img src="<?php echo e(asset($slide->image)); ?>?v=<?php echo e(time()); ?>" class="w-full aspect-video object-cover opacity-80 group-hover:opacity-100 transition-opacity">
                                
                                <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-end justify-between p-3">
                                    <span class="text-[10px] text-gray-400 font-mono tracking-tighter truncate max-w-[150px]">
                                        <?php echo e(basename($slide->image)); ?>

                                    </span>
                                    
                                    <div class="flex gap-2">
                                        <form action="<?php echo e(route('account.categories.delete-banner', $slide->id)); ?>" method="POST" onsubmit="return confirm('Hapus banner ini dari slider?')">
                                            <?php echo csrf_field(); ?>
                                            <?php echo method_field('DELETE'); ?>
                                            <button type="submit" class="w-8 h-8 bg-red-500/20 hover:bg-red-500 text-red-500 hover:text-white rounded-lg flex items-center justify-center transition-all shadow-lg">
                                                <i class="fas fa-trash-alt text-xs"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                            <div class="col-span-full py-12 flex flex-col items-center justify-center border-2 border-dashed border-gray-800 rounded-2xl">
                                <i class="fas fa-folder-open text-gray-800 text-4xl mb-3"></i>
                                <p class="text-gray-600 font-orbitron text-[10px] uppercase">Tidak ada banner yang aktif di slider</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Sync Buttons -->
            <div class="grid grid-cols-1 sm:grid-cols-3 gap-2 md:gap-3">
                <!-- Sync VIP Reseller Games -->
                <button @click="syncVipResellerGames()" :disabled="syncingGames"
                    class="group relative px-4 py-4 bg-gradient-to-r from-cyan-500 to-blue-600 rounded-xl font-bold hover:scale-105 transition-all shadow-lg shadow-cyan-500/20 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100">
                    <div class="flex items-center justify-center gap-3">
                        <i class="fas text-lg" :class="syncingGames ? 'fa-spinner fa-spin' : 'fa-gamepad'"></i>
                        <div class="text-left">
                            <div class="text-sm font-bold" x-text="syncingGames ? 'Syncing...' : 'Sync Games'"></div>
                            <div class="text-xs opacity-80">VIP Reseller Games</div>
                        </div>
                    </div>
                    <div class="absolute inset-0 rounded-xl bg-gradient-to-r from-cyan-500/20 to-blue-600/20 blur-xl opacity-0 group-hover:opacity-100 transition-opacity -z-10"></div>
                </button>

                <!-- Sync VIP Reseller PPOB -->
                <button @click="syncVipResellerPpob()" :disabled="syncingPpob"
                    class="group relative px-4 py-4 bg-gradient-to-r from-purple-500 to-pink-600 rounded-xl font-bold hover:scale-105 transition-all shadow-lg shadow-purple-500/20 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100">
                    <div class="flex items-center justify-center gap-3">
                        <i class="fas text-lg" :class="syncingPpob ? 'fa-spinner fa-spin' : 'fa-mobile-alt'"></i>
                        <div class="text-left">
                            <div class="text-sm font-bold" x-text="syncingPpob ? 'Syncing...' : 'Sync PPOB'"></div>
                            <div class="text-xs opacity-80">Pulsa, E-Wallet, etc</div>
                        </div>
                    </div>
                    <div class="absolute inset-0 rounded-xl bg-gradient-to-r from-purple-500/20 to-pink-600/20 blur-xl opacity-0 group-hover:opacity-100 transition-opacity -z-10"></div>
                </button>
                
                <!-- Fix Categories Button -->
                <button @click="fixCategories()" :disabled="fixingCategories"
                    class="group relative px-4 py-4 bg-gradient-to-r from-green-500 to-emerald-600 rounded-xl font-bold hover:scale-105 transition-all shadow-lg shadow-green-500/20 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100">
                    <div class="flex items-center justify-center gap-3">
                        <i class="fas text-lg" :class="fixingCategories ? 'fa-spinner fa-spin' : 'fa-tools'"></i>
                        <div class="text-left">
                            <div class="text-sm font-bold" x-text="fixingCategories ? 'Fixing...' : 'Fix Categories'"></div>
                            <div class="text-xs opacity-80">Auto-correct assignments</div>
                        </div>
                    </div>
                    <div class="absolute inset-0 rounded-xl bg-gradient-to-r from-green-500/20 to-emerald-600/20 blur-xl opacity-0 group-hover:opacity-100 transition-opacity -z-10"></div>
                </button>
            </div>
        </div>
    </div>

    <!-- ✅ ENHANCED FILTERS & SEARCH -->
    <div class="max-w-7xl mx-auto px-4 md:px-6 py-4 md:py-6">
        
        <!-- ✅ FILTER PRESETS -->
        <div class="flex flex-wrap gap-2 mb-4">
            <button @click="applyPreset('all')" 
                :class="activePreset === 'all' ? 'bg-cyan-500 text-white' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'"
                class="px-4 py-2 rounded-lg font-bold text-sm transition">
                <i class="fas fa-th mr-2"></i>All
            </button>
            <button @click="applyPreset('games')" 
                :class="activePreset === 'games' ? 'bg-cyan-500 text-white' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'"
                class="px-4 py-2 rounded-lg font-bold text-sm transition">
                🎮 Games
            </button>
            <button @click="applyPreset('vouchers')" 
                :class="activePreset === 'vouchers' ? 'bg-cyan-500 text-white' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'"
                class="px-4 py-2 rounded-lg font-bold text-sm transition">
                🎫 Vouchers
            </button>
            <button @click="applyPreset('high-margin')" 
                :class="activePreset === 'high-margin' ? 'bg-cyan-500 text-white' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'"
                class="px-4 py-2 rounded-lg font-bold text-sm transition">
                💰 High Margin (>15%)
            </button>
        </div>

        <!-- Search & Filters Row -->
        <div class="flex flex-col md:flex-row gap-3 md:gap-4 mb-4">
            <!-- ✅ ADVANCED SEARCH -->
            <div class="flex-1 relative">
                <i class="fas fa-search absolute left-4 top-1/2 -translate-y-1/2 text-gray-500"></i>
                <input type="text" placeholder="Search by name, SKU, brand, category..."
                    class="w-full pl-12 pr-4 py-2 md:py-3 bg-gray-900 border border-gray-800 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50"
                    x-model="search" @input.debounce.300ms="filterProducts()">
            </div>

            <!-- Category Filter -->
            <select
                class="px-4 py-2 md:py-3 bg-gray-900 border border-gray-800 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none"
                x-model="categoryFilter" @change="filterProducts()">
                <option value="">All Categories</option>
                <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cat): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <option value="<?php echo e($cat->id); ?>"><?php echo e($cat->name); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </select>

            <!-- Status Filter -->
            <select
                class="px-4 py-2 md:py-3 bg-gray-900 border border-gray-800 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none"
                x-model="statusFilter" @change="filterProducts()">
                <option value="">All Status</option>
                <option value="1">Active</option>
                <option value="0">Inactive</option>
            </select>

            <!-- ✅ SORT DROPDOWN -->
            <select
                class="px-4 py-2 md:py-3 bg-gray-900 border border-gray-800 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none"
                x-model="sortBy" @change="filterProducts()">
                <option value="">Sort By...</option>
                <option value="name_asc">Name (A-Z)</option>
                <option value="name_desc">Name (Z-A)</option>
                <option value="price_asc">Price (Low-High)</option>
                <option value="price_desc">Price (High-Low)</option>
                <option value="profit_desc">Profit (High-Low)</option>
                <option value="stock_desc">Stock (High-Low)</option>
            </select>
        </div>

        <!-- ✅ RESULTS COUNTER & RESET -->
        <div class="flex items-center justify-between text-sm mb-4">
            <p class="text-gray-400">
                Showing <?php echo e($products->count()); ?> of <?php echo e($products->total()); ?> products
            </p>
            <button @click="resetFilters()" 
                x-show="search || categoryFilter || statusFilter || sortBy || activePreset !== 'all'"
                class="text-cyan-400 hover:text-cyan-300 transition font-bold">
                <i class="fas fa-redo mr-1"></i> Reset All Filters
            </button>
        </div>

        <!-- Bulk Actions -->
        <div class="flex flex-wrap gap-2 items-center mb-4 bg-gray-900/50 p-3 rounded-lg border border-gray-800" x-show="selectedProducts.length > 0" x-cloak>
            <span class="text-xs md:text-sm text-cyan-400 font-bold" x-text="`${selectedProducts.length} selected`"></span>
            <button @click="openBulkMarkupModal()"
                class="px-3 py-2 bg-blue-500/20 text-blue-400 rounded-lg hover:bg-blue-500 hover:text-white transition text-xs font-bold">
                <i class="fas fa-tag mr-1"></i>Bulk Markup
            </button>
            <button @click="bulkToggleStatus(true)"
                class="px-3 py-2 bg-green-500/20 text-green-400 rounded-lg hover:bg-green-500 hover:text-white transition text-xs font-bold">
                <i class="fas fa-check mr-1"></i>Activate
            </button>
            <button @click="bulkToggleStatus(false)"
                class="px-3 py-2 bg-red-500/20 text-red-400 rounded-lg hover:bg-red-500 hover:text-white transition text-xs font-bold">
                <i class="fas fa-times mr-1"></i>Deactivate
            </button>
            <button @click="selectedProducts = []"
                class="ml-auto px-3 py-2 bg-gray-800 text-gray-400 rounded-lg hover:bg-gray-700 transition text-xs">
                Clear Selection
            </button>
        </div>
    </div>

    <!-- Products Content -->
    <div class="max-w-7xl mx-auto px-4 md:px-6 pb-20">
        
        <!-- DESKTOP TABLE VIEW -->
        <div class="bg-gray-900 rounded-lg border border-gray-800 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full table-desktop">
                    <thead class="bg-gray-800 border-b border-gray-700">
                        <tr>
                            <th class="px-4 py-4 text-left">
                                <input type="checkbox" @change="toggleSelectAll($event)"
                                    :checked="selectedProducts.length === products.length && products.length > 0"
                                    class="w-4 h-4 rounded bg-gray-700 border-gray-600 text-cyan-500">
                            </th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-cyan-400 uppercase sortable-header">
                                Product Info
                            </th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-cyan-400 uppercase sortable-header">
                                Pricing
                            </th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-cyan-400 uppercase sortable-header">
                                Stock
                            </th>
                            <th class="px-6 py-4 text-center text-xs font-bold text-cyan-400 uppercase">
                                Status
                            </th>
                            <th class="px-6 py-4 text-center text-xs font-bold text-cyan-400 uppercase">
                                Actions
                            </th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-800">
                        <?php $__empty_1 = true; $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <tr class="hover:bg-gray-800/50 transition">
                            <td class="px-4 py-4">
                                <input type="checkbox" value="<?php echo e($product->id); ?>" 
                                    @change="toggleSelect(<?php echo e($product->id); ?>)"
                                    :checked="selectedProducts.includes(<?php echo e($product->id); ?>)"
                                    class="w-4 h-4 rounded bg-gray-700 border-gray-600 text-cyan-500">
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex items-center gap-4">
                                    <div class="w-16 h-16 bg-gray-800 rounded-lg overflow-hidden flex-shrink-0 cursor-pointer hover:ring-2 hover:ring-cyan-500 transition"
                                         @click="previewImage('<?php echo e($product->image ? asset('storage/' . $product->image) : ''); ?>', '<?php echo e($product->name); ?>')">
                                        <?php if($product->image): ?>
                                        <img src="<?php echo e(asset('storage/' . $product->image)); ?>" alt="<?php echo e($product->name); ?>"
                                            class="w-full h-full object-cover">
                                        <?php else: ?>
                                        <div class="w-full h-full flex items-center justify-center text-gray-600">
                                            <i class="fas fa-image text-2xl"></i>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <div>
                                        <h3 class="font-bold text-white text-sm"><?php echo e($product->name); ?></h3>
                                        <p class="text-xs text-gray-400"><?php echo e($product->category_name); ?></p>
                                        <p class="text-xs text-gray-500 mt-1">SKU: <?php echo e($product->buyer_sku_code); ?></p>
                                        <span class="inline-block mt-1 px-2 py-1 bg-blue-500/20 text-blue-400 rounded text-xs"><?php echo e($product->brand); ?></span>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <div class="space-y-1">
                                    <p class="text-xs text-gray-400">Base: <span class="text-yellow-500 font-bold">Rp <?php echo e(number_format($product->price, 0, ',', '.')); ?></span></p>
                                    <p class="text-xs text-gray-400">Selling: <span class="text-green-500 font-bold">Rp <?php echo e(number_format($product->selling_price, 0, ',', '.')); ?></span></p>
                                    <p class="text-xs text-cyan-400">
                                        Profit: Rp <?php echo e(number_format($product->selling_price - $product->price, 0, ',', '.')); ?>

                                        (<?php echo e($product->price > 0 ? number_format((($product->selling_price - $product->price) / $product->price) * 100, 1) : 0); ?>%)
                                    </p>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-sm <?php echo e($product->unlimited_stock ? 'text-green-400' : ($product->stock > 0 ? 'text-blue-400' : 'text-red-400')); ?>">
                                    <?php echo e($product->unlimited_stock ? 'Unlimited' : $product->stock); ?>

                                </span>
                            </td>
                            <td class="px-6 py-4 text-center">
                                <button @click="toggleStatus(<?php echo e($product->id); ?>)"
                                    class="px-3 py-1 rounded-full text-xs font-bold transition"
                                    :class="products.find(p => p.id === <?php echo e($product->id); ?>)?.status ? 'bg-green-500/20 text-green-500' : 'bg-red-500/20 text-red-500'">
                                    <span x-text="products.find(p => p.id === <?php echo e($product->id); ?>)?.status ? 'Active' : 'Inactive'">
                                        <?php echo e($product->seller_product_status ? 'Active' : 'Inactive'); ?>

                                    </span>
                                </button>
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex items-center justify-center gap-2">
                                    <button
                                        @click="openEditModal(<?php echo e($product->id); ?>, '<?php echo e(addslashes($product->name)); ?>', <?php echo e($product->price); ?>, <?php echo e($product->selling_price); ?>)"
                                        class="px-3 py-2 bg-blue-500/20 text-blue-500 rounded-lg hover:bg-blue-500 hover:text-white transition text-xs"
                                        title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button
                                        @click="openMarkupModal(<?php echo e($product->id); ?>, '<?php echo e(addslashes($product->name)); ?>', <?php echo e($product->price); ?>)"
                                        class="px-3 py-2 bg-purple-500/20 text-purple-500 rounded-lg hover:bg-purple-500 hover:text-white transition text-xs"
                                        title="Markup">
                                        <i class="fas fa-percent"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <tr>
                            <td colspan="6" class="px-6 py-12 text-center text-gray-500">
                                <i class="fas fa-box-open text-5xl mb-4 opacity-20"></i>
                                <p class="mb-2">Tosan aya produk. Klik "Sync dari VIP RESELLER" heula!</p>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- MOBILE CARDS VIEW (Keep as is) -->
            <div class="cards-mobile space-y-4 p-4">
                <?php $__empty_1 = true; $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <div class="bg-gray-800/50 rounded-lg p-4 border border-gray-700">
                    <!-- Product Header -->
                    <div class="flex items-start gap-3 mb-3">
                        <input type="checkbox" value="<?php echo e($product->id); ?>" 
                            @change="toggleSelect(<?php echo e($product->id); ?>)"
                            :checked="selectedProducts.includes(<?php echo e($product->id); ?>)"
                            class="mt-1 w-4 h-4 rounded bg-gray-700 border-gray-600 text-cyan-500">
                        
                        <div class="w-16 h-16 bg-gray-900 rounded-lg overflow-hidden flex-shrink-0">
                            <?php if($product->image): ?>
                            <img src="<?php echo e(asset('storage/' . $product->image)); ?>" alt="<?php echo e($product->name); ?>"
                                class="w-full h-full object-cover">
                            <?php else: ?>
                            <div class="w-full h-full flex items-center justify-center text-gray-600">
                                <i class="fas fa-image text-xl"></i>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="flex-1 min-w-0">
                            <h3 class="font-bold text-white text-sm mb-1 truncate"><?php echo e($product->name); ?></h3>
                            <p class="text-xs text-gray-400 mb-1"><?php echo e($product->category_name); ?></p>
                            <span class="inline-block px-2 py-1 bg-blue-500/20 text-blue-400 rounded text-xs"><?php echo e($product->brand); ?></span>
                        </div>
                    </div>
                    
                    <!-- Pricing Info -->
                    <div class="bg-gray-900/50 rounded-lg p-3 mb-3 space-y-1">
                        <div class="flex justify-between text-xs">
                            <span class="text-gray-400">Base:</span>
                            <span class="text-yellow-500 font-bold">Rp <?php echo e(number_format($product->price, 0, ',', '.')); ?></span>
                        </div>
                        <div class="flex justify-between text-xs">
                            <span class="text-gray-400">Selling:</span>
                            <span class="text-green-500 font-bold">Rp <?php echo e(number_format($product->selling_price, 0, ',', '.')); ?></span>
                        </div>
                        <div class="flex justify-between text-xs">
                            <span class="text-gray-400">Profit:</span>
                            <span class="text-cyan-400 font-bold">
                                Rp <?php echo e(number_format($product->selling_price - $product->price, 0, ',', '.')); ?>

                                (<?php echo e($product->price > 0 ? number_format((($product->selling_price - $product->price) / $product->price) * 100, 1) : 0); ?>%)
                            </span>
                        </div>
                    </div>
                    
                    <!-- Stock & Status -->
                    <div class="flex items-center justify-between gap-2 mb-3">
                        <div class="text-xs">
                            <span class="text-gray-400">Stock: </span>
                            <span class="<?php echo e($product->unlimited_stock ? 'text-green-400' : ($product->stock > 0 ? 'text-blue-400' : 'text-red-400')); ?>">
                                <?php echo e($product->unlimited_stock ? 'Unlimited' : $product->stock); ?>

                            </span>
                        </div>
                        
                        <button @click="toggleStatus(<?php echo e($product->id); ?>)"
                            class="px-3 py-1 rounded-full text-xs font-bold transition"
                            :class="products.find(p => p.id === <?php echo e($product->id); ?>)?.status ? 'bg-green-500/20 text-green-500' : 'bg-red-500/20 text-red-500'">
                            <span x-text="products.find(p => p.id === <?php echo e($product->id); ?>)?.status ? 'Active' : 'Inactive'">
                                <?php echo e($product->seller_product_status ? 'Active' : 'Inactive'); ?>

                            </span>
                        </button>
                    </div>
                    
                    <!-- Actions -->
                    <div class="flex gap-2">
                        <button
                            @click="openEditModal(<?php echo e($product->id); ?>, '<?php echo e(addslashes($product->name)); ?>', <?php echo e($product->price); ?>, <?php echo e($product->selling_price); ?>)"
                            class="flex-1 px-3 py-2 bg-blue-500/20 text-blue-500 rounded-lg hover:bg-blue-500 hover:text-white transition text-xs font-bold">
                            <i class="fas fa-edit mr-1"></i>Edit
                        </button>
                        <button
                            @click="openMarkupModal(<?php echo e($product->id); ?>, '<?php echo e(addslashes($product->name)); ?>', <?php echo e($product->price); ?>)"
                            class="flex-1 px-3 py-2 bg-purple-500/20 text-purple-500 rounded-lg hover:bg-purple-500 hover:text-white transition text-xs font-bold">
                            <i class="fas fa-percent mr-1"></i>Markup
                        </button>
                    </div>
                    
                    <p class="text-[10px] text-gray-600 mt-2">SKU: <?php echo e($product->buyer_sku_code); ?></p>
                </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <div class="text-center py-12 text-gray-500">
                    <i class="fas fa-box-open text-5xl mb-4 opacity-20"></i>
                    <p>Tosan aya produk. Klik "Sync dari VIP RESELLER" heula!</p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Pagination -->
        <?php if($products->hasPages()): ?>
        <div class="mt-6">
            <?php echo e($products->links()); ?>

        </div>
        <?php endif; ?>
    </div>

    <!-- Edit Modal (Keep as is) -->
    <div x-show="showEditModal" x-cloak
        class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
        @click.self="closeEditModal()">
        <div class="bg-gray-900 rounded-2xl border border-cyan-500/20 w-full max-w-lg max-h-[90vh] overflow-y-auto" @click.stop>
            <div class="p-4 md:p-6 border-b border-gray-800">
                <h2 class="text-xl md:text-2xl font-bold text-cyan-400">Edit Product</h2>
                <p class="text-xs md:text-sm text-gray-400 mt-1" x-text="editForm.name"></p>
            </div>

            <form @submit.prevent="submitEdit()" class="p-4 md:p-6 space-y-4">
                <div>
                    <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Base Price (from API)</label>
                    <input type="text" :value="'Rp ' + formatNumber(editForm.base_price)" disabled
                        class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-gray-500 text-sm">
                </div>

                <div>
                    <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Selling Price *</label>
                    <input type="number" x-model="editForm.selling_price" required min="0" step="0.01"
                        class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none"
                        placeholder="12000">
                </div>

                <div>
                    <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Product Image</label>
                    <input type="file" @change="editForm.image = $event.target.files[0]" accept="image/*"
                        class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:bg-cyan-500 file:text-white file:cursor-pointer hover:file:bg-cyan-600 file:text-xs">
                    <p class="text-xs text-gray-500 mt-1">Max 2MB (JPG, PNG, WEBP)</p>
                </div>

                <div class="flex gap-3 pt-4">
                    <button type="button" @click="closeEditModal()"
                        class="flex-1 px-4 py-2 md:py-3 bg-gray-800 text-gray-400 rounded-lg font-bold hover:bg-gray-700 transition text-sm">
                        Cancel
                    </button>
                    <button type="submit"
                        class="flex-1 px-4 py-2 md:py-3 bg-gradient-to-r from-cyan-500 to-blue-600 rounded-lg font-bold hover:scale-105 transition shadow-lg shadow-cyan-500/20 text-sm"
                        :disabled="loading">
                        <span x-show="!loading">Update</span>
                        <span x-show="loading">Updating...</span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Markup Modal (Keep as is) -->
    <div x-show="showMarkupModal" x-cloak
        class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
        @click.self="closeMarkupModal()">
        <div class="bg-gray-900 rounded-2xl border border-cyan-500/20 w-full max-w-md" @click.stop>
            <div class="p-4 md:p-6 border-b border-gray-800">
                <h2 class="text-xl md:text-2xl font-bold text-cyan-400">Apply Markup</h2>
                <p class="text-xs md:text-sm text-gray-400 mt-1 truncate" x-text="markupForm.name"></p>
            </div>

            <form @submit.prevent="submitMarkup()" class="p-4 md:p-6 space-y-4">
                <div>
                    <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Base Price</label>
                    <p class="text-xl md:text-2xl font-bold text-yellow-500" x-text="'Rp ' + formatNumber(markupForm.base_price)"></p>
                </div>

                <div>
                    <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Markup Percentage *</label>
                    <div class="flex gap-2">
                        <input type="number" x-model="markupForm.percentage" required min="0" max="100" step="0.1"
                            class="flex-1 px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none"
                            placeholder="10">
                        <span class="px-4 py-2 md:py-3 bg-gray-800 rounded-lg text-gray-400 text-sm">%</span>
                    </div>
                </div>

                <div class="bg-gray-800 rounded-lg p-4">
                    <p class="text-xs md:text-sm text-gray-400 mb-1">Selling Price:</p>
                    <p class="text-xl md:text-2xl font-bold text-green-500" x-text="'Rp ' + formatNumber(calculateSellingPrice())"></p>
                    <p class="text-xs text-cyan-400 mt-2" x-text="'Profit: Rp ' + formatNumber(calculateProfit())"></p>
                </div>

                <div class="flex gap-3 pt-4">
                    <button type="button" @click="closeMarkupModal()"
                        class="flex-1 px-4 py-2 md:py-3 bg-gray-800 text-gray-400 rounded-lg font-bold hover:bg-gray-700 transition text-sm">
                        Cancel
                    </button>
                    <button type="submit"
                        class="flex-1 px-4 py-2 md:py-3 bg-gradient-to-r from-purple-500 to-pink-600 rounded-lg font-bold hover:scale-105 transition shadow-lg text-sm"
                        :disabled="loading">
                        <span x-show="!loading">Apply</span>
                        <span x-show="loading">Applying...</span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ✅ NEW: BULK MARKUP MODAL -->
    <div x-show="showBulkMarkupModal" x-cloak
        class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
        @click.self="closeBulkMarkupModal()">
        <div class="bg-gray-900 rounded-2xl border border-cyan-500/20 w-full max-w-md" @click.stop>
            <div class="p-4 md:p-6 border-b border-gray-800">
                <h2 class="text-xl md:text-2xl font-bold text-cyan-400">Bulk Apply Markup</h2>
                <p class="text-xs md:text-sm text-gray-400 mt-1">
                    <span x-text="selectedProducts.length"></span> products selected
                </p>
            </div>

            <form @submit.prevent="submitBulkMarkup()" class="p-4 md:p-6 space-y-4">
                <div>
                    <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Markup Percentage *</label>
                    <div class="flex gap-2">
                        <input type="number" x-model="bulkMarkupPercentage" required min="0" max="100" step="0.1"
                            class="flex-1 px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none"
                            placeholder="10">
                        <span class="px-4 py-2 md:py-3 bg-gray-800 rounded-lg text-gray-400 text-sm">%</span>
                    </div>
                    <p class="text-xs text-gray-500 mt-2">
                        This markup will be applied to all <span x-text="selectedProducts.length"></span> selected products
                    </p>
                </div>

                <div class="bg-cyan-500/10 border border-cyan-500/30 rounded-lg p-4">
                    <p class="text-xs text-cyan-400 flex items-center gap-2">
                        <i class="fas fa-info-circle"></i>
                        <span>Each product's selling price will be calculated as: Base Price × (1 + Markup%)</span>
                    </p>
                </div>

                <div class="flex gap-3 pt-4">
                    <button type="button" @click="closeBulkMarkupModal()"
                        class="flex-1 px-4 py-2 md:py-3 bg-gray-800 text-gray-400 rounded-lg font-bold hover:bg-gray-700 transition text-sm">
                        Cancel
                    </button>
                    <button type="submit"
                        class="flex-1 px-4 py-2 md:py-3 bg-gradient-to-r from-purple-500 to-pink-600 rounded-lg font-bold hover:scale-105 transition shadow-lg text-sm"
                        :disabled="loading">
                        <span x-show="!loading">Apply to All</span>
                        <span x-show="loading">Processing...</span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ✅ NEW: IMAGE PREVIEW MODAL -->
    <div x-show="showImagePreview" x-cloak
        class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/90 backdrop-blur-sm"
        @click="showImagePreview = false">
        <div class="relative max-w-4xl max-h-[90vh]" @click.stop>
            <button @click="showImagePreview = false"
                class="absolute -top-12 right-0 w-10 h-10 bg-white/10 hover:bg-white/20 rounded-full flex items-center justify-center transition">
                <i class="fas fa-times text-white"></i>
            </button>
            <img :src="previewImageSrc" :alt="previewImageAlt"
                class="max-w-full max-h-[90vh] rounded-lg shadow-2xl">
        </div>
    </div>

    <script>
        function productManager() {
            return {
                syncingGames: false,
                syncingPpob: false,
                fixingCategories: false,
                loading: false,
                search: '<?php echo e($search ?? ''); ?>',
                categoryFilter: '<?php echo e($categoryFilter ?? ''); ?>',
                statusFilter: '<?php echo e($statusFilter ?? ''); ?>',
                sortBy: '',
                activePreset: 'all',
                products: <?php echo json_encode($products->items(), 15, 512) ?>.map(function(p) {
                    return Object.assign({}, p, {
                        status: p.seller_product_status
                    });
                }),
                selectedProducts: [],
                showEditModal: false,
                showMarkupModal: false,
                showBulkMarkupModal: false,
                showImagePreview: false,
                previewImageSrc: '',
                previewImageAlt: '',
                bulkMarkupPercentage: 10,
                editForm: {
                    id: null,
                    name: '',
                    base_price: 0,
                    selling_price: 0,
                    image: null
                },
                markupForm: {
                    id: null,
                    name: '',
                    base_price: 0,
                    percentage: 10
                },

                // ✅ PRESET FILTERS
                applyPreset: function(preset) {
                    this.activePreset = preset;
                    
                    switch(preset) {
                        case 'all':
                            this.categoryFilter = '';
                            this.statusFilter = '';
                            this.sortBy = '';
                            break;
                        case 'games':
                            // Find game category IDs
                            this.categoryFilter = ''; // Set to game category ID if available
                            this.statusFilter = '1';
                            break;
                        case 'vouchers':
                            this.categoryFilter = ''; // Set to voucher category ID if available
                            this.statusFilter = '1';
                            break;
                        case 'high-margin':
                            this.statusFilter = '1';
                            this.sortBy = 'profit_desc';
                            break;
                    }
                    
                    this.filterProducts();
                },

                // ✅ RESET ALL FILTERS
                resetFilters: function() {
                    this.search = '';
                    this.categoryFilter = '';
                    this.statusFilter = '';
                    this.sortBy = '';
                    this.activePreset = 'all';
                    this.filterProducts();
                },

                // ✅ IMAGE PREVIEW
                previewImage: function(src, alt) {
                    if (src) {
                        this.previewImageSrc = src;
                        this.previewImageAlt = alt;
                        this.showImagePreview = true;
                    }
                },

                // ✅ BULK MARKUP MODAL
                openBulkMarkupModal: function() {
                    if (this.selectedProducts.length === 0) {
                        alert('Pilih produk heula!');
                        return;
                    }
                    this.bulkMarkupPercentage = 10;
                    this.showBulkMarkupModal = true;
                },

                closeBulkMarkupModal: function() {
                    this.showBulkMarkupModal = false;
                },

                submitBulkMarkup: async function() {
                    if (this.selectedProducts.length === 0) {
                        alert('No products selected!');
                        return;
                    }

                    if (!confirm(`Apply ${this.bulkMarkupPercentage}% markup to ${this.selectedProducts.length} products?`)) {
                        return;
                    }

                    this.loading = true;
                    var self = this;

                    try {
                        const response = await fetch('/account/products/bulk-markup', {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                product_ids: this.selectedProducts,
                                markup_percentage: this.bulkMarkupPercentage
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            alert('✅ ' + data.message);
                            window.location.reload();
                        } else {
                            alert('❌ Error: ' + data.message);
                        }
                    } catch (error) {
                        alert('❌ Error applying bulk markup');
                        console.error(error);
                    } finally {
                        self.loading = false;
                    }
                },

                syncVipResellerGames: function() {
                    if (this.syncingGames) return;
                    
                    this.syncingGames = true;
                    var self = this;

                    fetch('/account/products/sync-vipreseller-games', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                        }
                    })
                    .then(function(response) {
                        return response.json();
                    })
                    .then(function(data) {
                        if (data.success) {
                            alert('✅ Games synced successfully!');
                            location.reload();
                        } else {
                            alert('❌ Error: ' + data.message);
                        }
                    })
                    .catch(function(error) {
                        alert('❌ Failed to sync: ' + error);
                    })
                    .finally(function() {
                        self.syncingGames = false;
                    });
                },

                syncVipResellerPpob: function() {
                    if (this.syncingPpob) return;
                    
                    this.syncingPpob = true;
                    var self = this;

                    fetch('/account/products/sync-vipreseller-ppob', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                        }
                    })
                    .then(function(response) {
                        return response.json();
                    })
                    .then(function(data) {
                        if (data.success) {
                            alert('✅ PPOB synced successfully!');
                            location.reload();
                        } else {
                            alert('❌ Error: ' + data.message);
                        }
                    })
                    .catch(function(error) {
                        alert('❌ Failed to sync: ' + error);
                    })
                    .finally(function() {
                        self.syncingPpob = false;
                    });
                },

                fixCategories: function() {
                    if (!confirm('Fix miscategorized products?\n\nThis will correct category assignments for:\n• Subscription apps\n• Streaming services\n• Vouchers')) {
                        return;
                    }
                    
                    if (this.fixingCategories) return;
                    
                    this.fixingCategories = true;
                    var self = this;

                    fetch('/account/products/fix-categories', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                        }
                    })
                    .then(function(response) {
                        return response.json();
                    })
                    .then(function(data) {
                        if (data.success) {
                            alert('✅ ' + data.message);
                            setTimeout(function() {
                                location.reload();
                            }, 1500);
                        } else {
                            alert('❌ Error: ' + data.message);
                        }
                    })
                    .catch(function(error) {
                        alert('❌ Failed to fix categories: ' + error);
                    })
                    .finally(function() {
                        self.fixingCategories = false;
                    });
                },

                toggleStatus: async function(id) {
                    var self = this;
                    try {
                        const response = await fetch('/account/products/' + id + '/toggle-status', {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Content-Type': 'application/json'
                            }
                        });

                        const data = await response.json();

                        if (data.success) {
                            const product = self.products.find(function(p) {
                                return p.id === id;
                            });
                            if (product) {
                                product.status = data.status;
                            }
                        }
                    } catch (error) {
                        alert('Error updating status');
                    }
                },

                toggleSelect: function(id) {
                    const index = this.selectedProducts.indexOf(id);
                    if (index > -1) {
                        this.selectedProducts.splice(index, 1);
                    } else {
                        this.selectedProducts.push(id);
                    }
                },

                toggleSelectAll: function(event) {
                    if (event.target.checked) {
                        this.selectedProducts = this.products.map(function(p) { return p.id; });
                    } else {
                        this.selectedProducts = [];
                    }
                },

                openEditModal: function(id, name, basePrice, sellingPrice) {
                    this.editForm = {
                        id: id,
                        name: name,
                        base_price: basePrice,
                        selling_price: sellingPrice,
                        image: null
                    };
                    this.showEditModal = true;
                },

                closeEditModal: function() {
                    this.showEditModal = false;
                },

                submitEdit: async function() {
                    this.loading = true;
                    var self = this;

                    const formData = new FormData();
                    formData.append('selling_price', this.editForm.selling_price);
                    if (this.editForm.image) {
                        formData.append('image', this.editForm.image);
                    }
                    formData.append('_method', 'PUT');

                    try {
                        const response = await fetch('/account/products/' + this.editForm.id, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                            },
                            body: formData
                        });

                        const data = await response.json();

                        if (data.success) {
                            alert(data.message);
                            window.location.reload();
                        } else {
                            alert('Error: ' + data.message);
                        }
                    } catch (error) {
                        alert('Error submitting form');
                    } finally {
                        self.loading = false;
                    }
                },

                openMarkupModal: function(id, name, basePrice) {
                    this.markupForm = {
                        id: id,
                        name: name,
                        base_price: basePrice,
                        percentage: 10
                    };
                    this.showMarkupModal = true;
                },

                closeMarkupModal: function() {
                    this.showMarkupModal = false;
                },

                submitMarkup: async function() {
                    this.loading = true;
                    var self = this;

                    try {
                        const response = await fetch('/account/products/' + this.markupForm.id + '/apply-markup', {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                markup_percentage: this.markupForm.percentage
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            alert(data.message);
                            window.location.reload();
                        } else {
                            alert('Error: ' + data.message);
                        }
                    } catch (error) {
                        alert('Error applying markup');
                    } finally {
                        self.loading = false;
                    }
                },

                bulkToggleStatus: async function(status) {
                    if (this.selectedProducts.length === 0) {
                        alert('Pilih produk heula!');
                        return;
                    }

                    try {
                        const response = await fetch('/account/products/bulk-toggle', {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                product_ids: this.selectedProducts,
                                status: status
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            alert(data.message);
                            window.location.reload();
                        }
                    } catch (error) {
                        alert('Error updating products');
                    }
                },

                calculateSellingPrice: function() {
                    return this.markupForm.base_price + (this.markupForm.base_price * this.markupForm.percentage / 100);
                },

                calculateProfit: function() {
                    return this.calculateSellingPrice() - this.markupForm.base_price;
                },

                formatNumber: function(num) {
                    return new Intl.NumberFormat('id-ID').format(num);
                },

                filterProducts: function() {
                    const params = new URLSearchParams();
                    if (this.search) params.append('search', this.search);
                    if (this.categoryFilter) params.append('category', this.categoryFilter);
                    if (this.statusFilter !== '') params.append('status', this.statusFilter);
                    if (this.sortBy) params.append('sort', this.sortBy);

                    window.location.href = '/account/products?' + params.toString();
                }
            }
        }
        
        function bannerManager() {
            return {
                newBannerPreview: null,
                previewNewBanner(event) {
                    const file = event.target.files[0];
                    if (file) {
                        this.newBannerPreview = URL.createObjectURL(file);
                    }
                }
            }
        }
    </script>
</body>

</html><?php /**PATH /home/instinct/Documents/belajar/php/ryll-topup/resources/views/account/products/index.blade.php ENDPATH**/ ?>