<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Voucher Management - Ryll Store</title>
    <link rel="icon" type="image/webp" href="{{ 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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&display=swap" rel="stylesheet">
    
    <style>
        .font-orbitron { font-family: 'Orbitron', sans-serif; }
        
        [x-cloak] { display: none !important; }
        
        body { background: linear-gradient(135deg, #0a0e27 0%, #1a1f3a 100%); }
        
        .glow-border { 
            box-shadow: 0 0 20px rgba(6, 182, 212, 0.3); 
            border: 1px solid rgba(6, 182, 212, 0.5); 
        }
        
        .card-stat { 
            background: linear-gradient(135deg, rgba(6, 182, 212, 0.1) 0%, rgba(147, 51, 234, 0.1) 100%); 
            backdrop-filter: blur(10px); 
        }

        /* Progress bar animation */
        @keyframes progress-animation {
            0% { width: 0%; }
        }

        .progress-bar {
            animation: progress-animation 1s ease-out;
        }

        /* Mobile responsive */
        @media (max-width: 768px) {
            .desktop-table { display: none; }
            .mobile-cards { display: block; }
        }
        
        @media (min-width: 769px) {
            .desktop-table { display: table; }
            .mobile-cards { display: none; }
        }
    </style>
</head>
<body class="min-h-screen text-white" x-data="voucherManager()">

<!-- Navbar -->
@include('components.admin-navbar')

<div class="max-w-7xl mx-auto px-4 py-8">
    
    <!-- Header -->
    <div class="mb-8">
        <h1 class="text-2xl md:text-3xl font-bold font-orbitron mb-2">
            <i class="fas fa-ticket text-purple-400 mr-3"></i>VOUCHER MANAGEMENT
        </h1>
        <p class="text-sm md:text-base text-gray-400">Create and manage discount vouchers</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-6 mb-8">
        <div class="card-stat glow-border rounded-xl md:rounded-2xl p-4 md:p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm uppercase mb-1 md:mb-2">TOTAL</p>
                    <p class="text-2xl md:text-3xl font-bold">{{ $stats['total'] }}</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-purple-500/20 rounded-lg md:rounded-xl flex items-center justify-center">
                    <i class="fas fa-ticket text-lg md:text-2xl text-purple-400"></i>
                </div>
            </div>
        </div>
        
        <div class="card-stat glow-border rounded-xl md:rounded-2xl p-4 md:p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm uppercase mb-1 md:mb-2">ACTIVE</p>
                    <p class="text-2xl md:text-3xl font-bold text-green-400">{{ $stats['active'] }}</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-green-500/20 rounded-lg md:rounded-xl flex items-center justify-center">
                    <i class="fas fa-check-circle text-lg md:text-2xl text-green-400"></i>
                </div>
            </div>
        </div>
        
        <div class="card-stat glow-border rounded-xl md:rounded-2xl p-4 md:p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm uppercase mb-1 md:mb-2">EXPIRED</p>
                    <p class="text-2xl md:text-3xl font-bold text-red-400">{{ $stats['expired'] }}</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-red-500/20 rounded-lg md:rounded-xl flex items-center justify-center">
                    <i class="fas fa-clock text-lg md:text-2xl text-red-400"></i>
                </div>
            </div>
        </div>
        
        <div class="card-stat glow-border rounded-xl md:rounded-2xl p-4 md:p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm uppercase mb-1 md:mb-2">USED TODAY</p>
                    <p class="text-2xl md:text-3xl font-bold text-cyan-400">{{ $stats['used_today'] }}</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-cyan-500/20 rounded-lg md:rounded-xl flex items-center justify-center">
                    <i class="fas fa-chart-line text-lg md:text-2xl text-cyan-400"></i>
                </div>
            </div>
        </div>

        <!-- ✅ NEW: Total Discount Given -->
        <div class="card-stat glow-border rounded-xl md:rounded-2xl p-4 md:p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm uppercase mb-1 md:mb-2">DISCOUNT</p>
                    @php
                        $totalDiscount = DB::table('voucher_usage')->sum('discount_amount');
                    @endphp
                    <p class="text-lg md:text-2xl font-bold text-yellow-400">{{ number_format($totalDiscount / 1000, 0) }}K</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-yellow-500/20 rounded-lg md:rounded-xl flex items-center justify-center">
                    <i class="fas fa-coins text-lg md:text-2xl text-yellow-400"></i>
                </div>
            </div>
        </div>

        <!-- ✅ NEW: Most Used Voucher -->
        <div class="card-stat glow-border rounded-xl md:rounded-2xl p-4 md:p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm uppercase mb-1 md:mb-2">TOP CODE</p>
                    @php
                        $topVoucher = DB::table('vouchers')->orderBy('used_count', 'desc')->first();
                    @endphp
                    <p class="text-xs md:text-sm font-bold text-purple-400 font-mono">
                        {{ $topVoucher ? Str::limit($topVoucher->code, 8) : 'N/A' }}
                    </p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-purple-500/20 rounded-lg md:rounded-xl flex items-center justify-center">
                    <i class="fas fa-trophy text-lg md:text-2xl text-purple-400"></i>
                </div>
            </div>
        </div>
    </div>
    
    <!-- ✅ SEARCH & FILTER BAR -->
    <div class="bg-gray-900/50 glow-border rounded-xl md:rounded-2xl p-4 md:p-6 mb-6">
        <div class="flex flex-col md:flex-row gap-3 mb-4">
            <!-- 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" 
                       x-model="searchQuery"
                       @input.debounce.300ms="filterVouchers()"
                       placeholder="Search by code or description..."
                       class="w-full pl-12 pr-4 py-2 md:py-3 bg-gray-800 border border-cyan-500/30 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
            </div>

            <!-- Type Filter -->
            <select x-model="typeFilter" 
                    @change="filterVouchers()"
                    class="px-4 py-2 md:py-3 bg-gray-800 border border-cyan-500/30 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none">
                <option value="all">All Types</option>
                <option value="percentage">Percentage</option>
                <option value="fixed">Fixed Amount</option>
            </select>

            <!-- Status Filter -->
            <select x-model="statusFilter" 
                    @change="filterVouchers()"
                    class="px-4 py-2 md:py-3 bg-gray-800 border border-cyan-500/30 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none">
                <option value="all">All Status</option>
                <option value="active">Active Only</option>
                <option value="expired">Expired</option>
                <option value="full">Full Usage</option>
            </select>
        </div>

        <!-- Quick Actions -->
        <div class="flex flex-wrap items-center gap-2">
            <button @click="showCreateModal = true" 
                    class="px-4 py-2 bg-gradient-to-r from-cyan-500 to-blue-600 rounded-lg font-bold hover:scale-105 transition text-sm">
                <i class="fas fa-plus mr-2"></i>CREATE NEW VOUCHER
            </button>

            <button @click="resetFilters()"
                    x-show="searchQuery || typeFilter !== 'all' || statusFilter !== 'all'"
                    class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm">
                <i class="fas fa-redo mr-2"></i>Clear Filters
            </button>

            <span class="ml-auto text-sm text-gray-400" x-text="`Showing ${filteredVouchers.length} of ${allVouchers.length}`"></span>
        </div>
    </div>

    <!-- ✅ BULK ACTIONS BAR -->
    <div x-show="selectedVouchers.length > 0" 
         x-cloak
         class="bg-purple-500/10 border border-purple-500/30 rounded-xl p-4 mb-6 flex flex-wrap items-center gap-3">
        <span class="text-sm font-bold text-purple-400">
            <i class="fas fa-check-square mr-2"></i>
            <span x-text="selectedVouchers.length"></span> selected
        </span>
        
        <button @click="bulkActivate()" class="px-4 py-2 bg-green-500/20 text-green-400 rounded-lg hover:bg-green-500 hover:text-white transition text-sm font-bold">
            <i class="fas fa-play mr-2"></i>Bulk Activate
        </button>
        
        <button @click="bulkDeactivate()" class="px-4 py-2 bg-yellow-500/20 text-yellow-400 rounded-lg hover:bg-yellow-500 hover:text-white transition text-sm font-bold">
            <i class="fas fa-pause mr-2"></i>Bulk Deactivate
        </button>
        
        <button @click="bulkDelete()" class="px-4 py-2 bg-red-500/20 text-red-400 rounded-lg hover:bg-red-500 hover:text-white transition text-sm font-bold">
            <i class="fas fa-trash mr-2"></i>Bulk Delete
        </button>

        <button @click="selectedVouchers = []" class="ml-auto px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm">
            Clear Selection
        </button>
    </div>
    
    <!-- Success Message -->
    @if(session('success'))
    <div class="bg-green-500/20 border border-green-500 rounded-lg p-4 mb-6">
        <i class="fas fa-check-circle text-green-400 mr-2"></i>
        <span class="text-green-400">{{ session('success') }}</span>
    </div>
    @endif
    
    <!-- Vouchers List -->
    <div class="bg-gray-900/50 glow-border rounded-xl md:rounded-2xl p-4 md:p-6">
        <h3 class="text-base md:text-lg font-bold mb-6 flex items-center gap-2">
            <i class="fas fa-list text-cyan-400"></i>
            Vouchers List
        </h3>
        
        <!-- ✅ DESKTOP TABLE -->
        <div class="overflow-x-auto" x-show="filteredVouchers.length > 0">
            <table class="w-full desktop-table">
                <thead>
                    <tr class="border-b border-gray-700">
                        <th class="text-left py-4 px-4">
                            <input type="checkbox" 
                                   @change="toggleSelectAll($event)"
                                   :checked="selectedVouchers.length === filteredVouchers.length && filteredVouchers.length > 0"
                                   class="w-4 h-4 rounded bg-gray-700 border-gray-600 text-purple-500">
                        </th>
                        <th class="text-left py-4 px-4 text-xs md:text-sm text-gray-400 font-semibold">CODE</th>
                        <th class="text-left py-4 px-4 text-xs md:text-sm text-gray-400 font-semibold">TYPE</th>
                        <th class="text-left py-4 px-4 text-xs md:text-sm text-gray-400 font-semibold">VALUE</th>
                        <th class="text-left py-4 px-4 text-xs md:text-sm text-gray-400 font-semibold">MIN PURCHASE</th>
                        <th class="text-left py-4 px-4 text-xs md:text-sm text-gray-400 font-semibold">USAGE</th>
                        <th class="text-left py-4 px-4 text-xs md:text-sm text-gray-400 font-semibold">VALID UNTIL</th>
                        <th class="text-left py-4 px-4 text-xs md:text-sm text-gray-400 font-semibold">STATUS</th>
                        <th class="text-left py-4 px-4 text-xs md:text-sm text-gray-400 font-semibold">ACTIONS</th>
                    </tr>
                </thead>
                <tbody>
                    <template x-for="voucher in filteredVouchers" :key="voucher.id">
                        <tr class="border-b border-gray-800 hover:bg-gray-800/50 transition">
                            <td class="py-4 px-4">
                                <input type="checkbox" 
                                       :value="voucher.id"
                                       @change="toggleSelect(voucher.id)"
                                       :checked="selectedVouchers.includes(voucher.id)"
                                       class="w-4 h-4 rounded bg-gray-700 border-gray-600 text-purple-500">
                            </td>
                            <td class="py-4 px-4">
                                <div class="flex items-center gap-2">
                                    <span class="font-bold text-cyan-400 font-mono text-sm md:text-lg" x-text="voucher.code"></span>
                                    <button @click="copyCode(voucher.code)" 
                                            class="text-gray-500 hover:text-cyan-400 transition text-xs"
                                            title="Copy code">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                            </td>
                            <td class="py-4 px-4">
                                <span class="px-2 md:px-3 py-1 rounded-full text-xs md:text-sm"
                                      :class="voucher.type === 'percentage' ? 'bg-purple-500/20 text-purple-400' : 'bg-blue-500/20 text-blue-400'">
                                    <i :class="voucher.type === 'percentage' ? 'fas fa-percent' : 'fas fa-dollar-sign'"></i>
                                    <span x-text="voucher.type === 'percentage' ? ' Percentage' : ' Fixed'" class="hidden md:inline"></span>
                                </span>
                            </td>
                            <td class="py-4 px-4">
                                <template x-if="voucher.type === 'percentage'">
                                    <div>
                                        <span class="text-base md:text-lg font-bold text-yellow-400" x-text="voucher.value + '%'"></span>
                                        <template x-if="voucher.max_discount">
                                            <p class="text-xs text-gray-500">Max: Rp <span x-text="formatNumber(voucher.max_discount)"></span></p>
                                        </template>
                                    </div>
                                </template>
                                <template x-if="voucher.type === 'fixed'">
                                    <span class="text-base md:text-lg font-bold text-green-400">Rp <span x-text="formatNumber(voucher.value)"></span></span>
                                </template>
                            </td>
                            <td class="py-4 px-4">
                                <span class="text-xs md:text-sm">Rp <span x-text="formatNumber(voucher.min_purchase)"></span></span>
                            </td>
                            <td class="py-4 px-4">
                                <div>
                                    <div class="flex items-center gap-2 mb-1">
                                        <span class="text-cyan-400 font-bold text-sm" x-text="voucher.used_count"></span>
                                        <span class="text-gray-500 text-sm">/</span>
                                        <span class="text-gray-500 text-sm" x-text="voucher.max_usage > 0 ? voucher.max_usage : '∞'"></span>
                                    </div>
                                    <!-- ✅ USAGE PROGRESS BAR -->
                                    <template x-if="voucher.max_usage > 0">
                                        <div class="w-24 bg-gray-700 rounded-full h-2 overflow-hidden">
                                            <div class="progress-bar h-full rounded-full transition-all duration-500"
                                                 :class="(voucher.used_count / voucher.max_usage * 100) >= 80 ? 'bg-red-500' : 'bg-cyan-500'"
                                                 :style="`width: ${Math.min((voucher.used_count / voucher.max_usage * 100), 100)}%`"></div>
                                        </div>
                                    </template>
                                </div>
                            </td>
                            <td class="py-4 px-4">
                                <template x-if="voucher.valid_until">
                                    <div>
                                        <span class="text-xs md:text-sm" x-text="formatDate(voucher.valid_until)"></span>
                                        <template x-if="isExpiringSoon(voucher.valid_until)">
                                            <p class="text-xs text-orange-400 mt-1">
                                                <i class="fas fa-exclamation-triangle"></i> Expiring soon
                                            </p>
                                        </template>
                                    </div>
                                </template>
                                <template x-if="!voucher.valid_until">
                                    <span class="text-gray-500 text-sm">No expiry</span>
                                </template>
                            </td>
                            <td class="py-4 px-4">
                                <span class="px-2 md:px-3 py-1 rounded-full text-xs md:text-sm"
                                      :class="voucher.is_active ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400'">
                                    <i :class="voucher.is_active ? 'fas fa-check-circle' : 'fas fa-times-circle'"></i>
                                    <span x-text="voucher.is_active ? ' Active' : ' Inactive'" class="hidden md:inline"></span>
                                </span>
                            </td>
                            <td class="py-4 px-4">
                                <div class="flex gap-2">
                                    <form method="POST" :action="`/account/vouchers/${voucher.id}/toggle`">
                                        @csrf
                                        <button type="submit" 
                                                class="px-2 md:px-3 py-2 rounded-lg hover:opacity-80 transition text-xs md:text-sm"
                                                :class="voucher.is_active ? 'bg-yellow-500/20 text-yellow-400' : 'bg-green-500/20 text-green-400'"
                                                :title="voucher.is_active ? 'Deactivate' : 'Activate'">
                                            <i :class="voucher.is_active ? 'fas fa-pause' : 'fas fa-play'"></i>
                                        </button>
                                    </form>
                                    
                                    <a :href="`/account/vouchers/${voucher.id}/usage`" 
                                       class="px-2 md:px-3 py-2 bg-blue-500/20 text-blue-400 rounded-lg hover:opacity-80 transition text-xs md:text-sm" 
                                       title="View Usage">
                                        <i class="fas fa-chart-bar"></i>
                                    </a>
                                    
                                    <form method="POST" :action="`/account/vouchers/${voucher.id}`" 
                                          onsubmit="return confirm('Delete this voucher?')">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" 
                                                class="px-2 md:px-3 py-2 bg-red-500/20 text-red-400 rounded-lg hover:opacity-80 transition text-xs md:text-sm" 
                                                title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>

        <!-- ✅ MOBILE CARDS -->
        <div class="mobile-cards space-y-4" x-show="filteredVouchers.length > 0">
            <template x-for="voucher in filteredVouchers" :key="voucher.id">
                <div class="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
                    <!-- Header -->
                    <div class="flex items-start gap-3 mb-3">
                        <input type="checkbox" 
                               :value="voucher.id"
                               @change="toggleSelect(voucher.id)"
                               :checked="selectedVouchers.includes(voucher.id)"
                               class="mt-1 w-4 h-4 rounded bg-gray-700 border-gray-600 text-purple-500">
                        
                        <div class="flex-1">
                            <div class="flex items-center gap-2 mb-2">
                                <span class="font-bold text-cyan-400 font-mono text-lg" x-text="voucher.code"></span>
                                <button @click="copyCode(voucher.code)" 
                                        class="text-gray-500 hover:text-cyan-400 transition text-xs">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                            
                            <!-- Type & Value -->
                            <div class="flex gap-2 mb-2">
                                <span class="px-2 py-1 rounded-full text-xs"
                                      :class="voucher.type === 'percentage' ? 'bg-purple-500/20 text-purple-400' : 'bg-blue-500/20 text-blue-400'">
                                    <i :class="voucher.type === 'percentage' ? 'fas fa-percent' : 'fas fa-dollar-sign'"></i>
                                    <span x-text="voucher.type === 'percentage' ? ' Percentage' : ' Fixed'"></span>
                                </span>
                                
                                <span class="px-2 py-1 rounded-full text-xs"
                                      :class="voucher.is_active ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400'">
                                    <i :class="voucher.is_active ? 'fas fa-check-circle' : 'fas fa-times-circle'"></i>
                                    <span x-text="voucher.is_active ? ' Active' : ' Inactive'"></span>
                                </span>
                            </div>
                        </div>
                    </div>

                    <!-- Value Info -->
                    <div class="bg-gray-900/50 rounded-lg p-3 mb-3 space-y-2">
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-400">Value:</span>
                            <template x-if="voucher.type === 'percentage'">
                                <span class="font-bold text-yellow-400" x-text="voucher.value + '%'"></span>
                            </template>
                            <template x-if="voucher.type === 'fixed'">
                                <span class="font-bold text-green-400">Rp <span x-text="formatNumber(voucher.value)"></span></span>
                            </template>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-400">Min Purchase:</span>
                            <span class="font-bold">Rp <span x-text="formatNumber(voucher.min_purchase)"></span></span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-400">Usage:</span>
                            <span class="font-bold text-cyan-400">
                                <span x-text="voucher.used_count"></span> / <span x-text="voucher.max_usage > 0 ? voucher.max_usage : '∞'"></span>
                            </span>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="flex gap-2">
                        <form method="POST" :action="`/account/vouchers/${voucher.id}/toggle`" class="flex-1">
                            @csrf
                            <button type="submit" 
                                    class="w-full px-3 py-2 rounded-lg hover:opacity-80 transition text-xs font-bold"
                                    :class="voucher.is_active ? 'bg-yellow-500/20 text-yellow-400' : 'bg-green-500/20 text-green-400'">
                                <i :class="voucher.is_active ? 'fas fa-pause' : 'fas fa-play'"></i>
                                <span x-text="voucher.is_active ? ' Pause' : ' Activate'"></span>
                            </button>
                        </form>
                        
                        <a :href="`/account/vouchers/${voucher.id}/usage`" 
                           class="px-3 py-2 bg-blue-500/20 text-blue-400 rounded-lg hover:opacity-80 transition text-xs">
                            <i class="fas fa-chart-bar"></i>
                        </a>
                        
                        <form method="POST" :action="`/account/vouchers/${voucher.id}`" 
                              onsubmit="return confirm('Delete this voucher?')">
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="px-3 py-2 bg-red-500/20 text-red-400 rounded-lg hover:opacity-80 transition text-xs">
                                <i class="fas fa-trash"></i>
                            </button>
                        </form>
                    </div>
                </div>
            </template>
        </div>

        <!-- ✅ NO RESULTS STATE -->
        <div x-show="filteredVouchers.length === 0" class="text-center py-12">
            <i class="fas fa-ticket text-5xl md:text-6xl text-gray-600 mb-4"></i>
            <p class="text-gray-400 mb-4">No vouchers found</p>
            <button @click="resetFilters()" 
                    x-show="searchQuery || typeFilter !== 'all' || statusFilter !== 'all'"
                    class="px-6 py-3 bg-cyan-500 hover:bg-cyan-600 rounded-lg transition">
                <i class="fas fa-redo mr-2"></i>Clear Filters
            </button>
            <button @click="showCreateModal = true"
                    x-show="!searchQuery && typeFilter === 'all' && statusFilter === 'all'"
                    class="px-6 py-3 bg-cyan-500 hover:bg-cyan-600 rounded-lg transition">
                <i class="fas fa-plus mr-2"></i>Create First Voucher
            </button>
        </div>
    </div>
    
</div>

<!-- ✅ CREATE MODAL -->
<div x-show="showCreateModal" 
     x-cloak
     class="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4"
     @click.self="showCreateModal = false">
    <div class="bg-gray-900 glow-border rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto"
         @click.stop
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0 scale-90"
         x-transition:enter-end="opacity-100 scale-100">
        <div class="p-6">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-xl md:text-2xl font-bold font-orbitron">
                    <i class="fas fa-plus-circle text-cyan-400 mr-2"></i>CREATE NEW VOUCHER
                </h3>
                <button @click="showCreateModal = false" class="text-gray-400 hover:text-white transition">
                    <i class="fas fa-times text-xl md:text-2xl"></i>
                </button>
            </div>
            
            <form method="POST" action="{{ route('account.vouchers.store') }}" class="space-y-4">
                @csrf
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Voucher Code *</label>
                        <input type="text" name="code" required placeholder="RYLLJANUARI" 
                               class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white uppercase focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                    </div>
                    
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Type *</label>
                        <select name="type" required class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                            <option value="percentage">Percentage (%)</option>
                            <option value="fixed">Fixed Amount (Rp)</option>
                        </select>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Value *</label>
                        <input type="number" name="value" required step="0.01" min="0" placeholder="10" 
                               class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                    </div>
                    
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Max Discount (Optional)</label>
                        <input type="number" name="max_discount" step="1" min="0" placeholder="50000" 
                               class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Min Purchase *</label>
                        <input type="number" name="min_purchase" required step="1" min="0" placeholder="10000" 
                               class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                    </div>
                    
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Max Usage (0 = Unlimited)</label>
                        <input type="number" name="max_usage" value="0" step="1" min="0" placeholder="100" 
                               class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Valid From</label>
                        <input type="datetime-local" name="valid_from" value="{{ now()->format('Y-m-d\TH:i') }}"
                               class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                        <p class="text-xs text-gray-500 mt-1">Default: Now</p>
                    </div>
                    
                    <div>
                        <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Valid Until</label>
                        <input type="datetime-local" name="valid_until" 
                               class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                    </div>
                </div>
                
                <div>
                    <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">Description</label>
                    <textarea name="description" rows="3" placeholder="Grand Opening Promo - 10% off for all purchases" 
                              class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 resize-none"></textarea>
                </div>
                
                <button type="submit" class="w-full px-6 py-3 md:py-4 bg-gradient-to-r from-cyan-500 to-blue-600 rounded-xl font-bold hover:scale-105 transition text-sm md:text-base">
                    <i class="fas fa-save mr-2"></i>CREATE VOUCHER
                </button>
            </form>
        </div>
    </div>
</div>

<script>
    function voucherManager() {
        return {
            showCreateModal: false,
            searchQuery: '',
            typeFilter: 'all',
            statusFilter: 'all',
            selectedVouchers: [],
            allVouchers: @json($vouchers->items()),

            get filteredVouchers() {
                let filtered = [...this.allVouchers];

                // Search filter
                if (this.searchQuery.trim()) {
                    const query = this.searchQuery.toLowerCase();
                    filtered = filtered.filter(v => 
                        v.code.toLowerCase().includes(query) ||
                        (v.description && v.description.toLowerCase().includes(query))
                    );
                }

                // Type filter
                if (this.typeFilter !== 'all') {
                    filtered = filtered.filter(v => v.type === this.typeFilter);
                }

                // Status filter
                if (this.statusFilter === 'active') {
                    filtered = filtered.filter(v => v.is_active);
                } else if (this.statusFilter === 'expired') {
                    filtered = filtered.filter(v => 
                        v.valid_until && new Date(v.valid_until) < new Date()
                    );
                } else if (this.statusFilter === 'full') {
                    filtered = filtered.filter(v => 
                        v.max_usage > 0 && v.used_count >= v.max_usage
                    );
                }

                return filtered;
            },

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

            toggleSelectAll(event) {
                if (event.target.checked) {
                    this.selectedVouchers = this.filteredVouchers.map(v => v.id);
                } else {
                    this.selectedVouchers = [];
                }
            },

            resetFilters() {
                this.searchQuery = '';
                this.typeFilter = 'all';
                this.statusFilter = 'all';
            },

            filterVouchers() {
                // Trigger reactivity
                this.filteredVouchers;
            },

            copyCode(code) {
                navigator.clipboard.writeText(code).then(() => {
                    alert(`✅ Copied: ${code}`);
                });
            },

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

            formatDate(date) {
                return new Date(date).toLocaleDateString('id-ID', {
                    day: '2-digit',
                    month: 'short',
                    year: 'numeric'
                });
            },

            isExpiringSoon(date) {
                const expiry = new Date(date);
                const now = new Date();
                const diff = expiry - now;
                const days = diff / (1000 * 60 * 60 * 24);
                return days > 0 && days <= 7;
            },

            async bulkActivate() {
                if (this.selectedVouchers.length === 0) return;
                
                if (!confirm(`Activate ${this.selectedVouchers.length} vouchers?`)) return;

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

                    const data = await response.json();
                    if (data.success) {
                        alert('✅ ' + data.message);
                        window.location.reload();
                    }
                } catch (error) {
                    alert('❌ Failed to activate vouchers');
                }
            },

            async bulkDeactivate() {
                if (this.selectedVouchers.length === 0) return;
                
                if (!confirm(`Deactivate ${this.selectedVouchers.length} vouchers?`)) return;

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

                    const data = await response.json();
                    if (data.success) {
                        alert('✅ ' + data.message);
                        window.location.reload();
                    }
                } catch (error) {
                    alert('❌ Failed to deactivate vouchers');
                }
            },

            async bulkDelete() {
                if (this.selectedVouchers.length === 0) return;
                
                if (!confirm(`Delete ${this.selectedVouchers.length} vouchers? This cannot be undone!`)) return;

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

                    const data = await response.json();
                    if (data.success) {
                        alert('✅ ' + data.message);
                        window.location.reload();
                    }
                } catch (error) {
                    alert('❌ Failed to delete vouchers');
                }
            }
        }
    }
</script>

</body>
</html>