@extends('layouts.admin')

@section('title', 'Penjualan')

@section('content')

    <!-- Breadcrumb -->
    @php
    $breadcrumbs = [
        ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
        ['label' => 'Transaksi', 'url' => '#'],
        ['label' => 'Penjualan', 'url' => route('admin.transaksi.sales.index')]
    ];
    @endphp
    <x-breadcrumb :items="$breadcrumbs" />

    <!-- Notifikasi Modern -->
    <x-admin-notification />

    <!-- Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800 dark:text-white">Daftar Penjualan</h1>
    </div>

    <!-- Filter Section -->
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 mb-4">
        <form method="GET" action="{{ route('admin.transaksi.sales.index') }}" id="filterForm" class="space-y-4">
            <!-- Search Bar -->
            <div class="relative flex-1">
                <input type="text" name="search" id="searchInput" value="{{ request('search') }}" placeholder="Cari produk atau pembeli..."
                    class="form-input-search" />
                <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none"></i>
                @if (request('search'))
                    <button type="button" onclick="clearFilter('search')"
                        class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300">
                        <i class="fas fa-times"></i>
                    </button>
                @endif
            </div>

            <!-- Filter Row -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <!-- Status Filter -->
                <div class="relative">
                    <select name="status" id="statusFilter" onchange="submitFilter()" class="form-select">
                        <option value="">Semua Status</option>
                        <option value="selesai" {{ request('status') === 'selesai' ? 'selected' : '' }}>Selesai</option>
                        <option value="dibatalkan" {{ request('status') === 'dibatalkan' ? 'selected' : '' }}>Dibatalkan</option>
                    </select>
                    <i class="fas fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none text-xs"></i>
                </div>

                <!-- Payment Method Filter -->
                <div class="relative">
                    <select name="payment_method" id="paymentMethodFilter" onchange="submitFilter()" class="form-select">
                        <option value="">Semua Metode</option>
                        <option value="transfer" {{ request('payment_method') === 'transfer' ? 'selected' : '' }}>Transfer</option>
                        <option value="cod" {{ request('payment_method') === 'cod' ? 'selected' : '' }}>COD</option>
                        <option value="dp" {{ request('payment_method') === 'dp' ? 'selected' : '' }}>DP</option>
                        <option value="qris" {{ request('payment_method') === 'qris' ? 'selected' : '' }}>QRIS</option>
                    </select>
                    <i class="fas fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none text-xs"></i>
                </div>

                <!-- Date From -->
                <div class="relative">
                    <input type="date" name="date_from" id="dateFromInput" value="{{ request('date_from') }}" onchange="submitFilter()"
                        class="w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors duration-200 text-sm"
                        placeholder="Dari Tanggal">
                    <i class="fas fa-calendar-alt absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none"></i>
                </div>

                <!-- Date To -->
                <div class="relative">
                    <input type="date" name="date_to" id="dateToInput" value="{{ request('date_to') }}" onchange="submitFilter()"
                        class="w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors duration-200 text-sm"
                        placeholder="Sampai Tanggal">
                    <i class="fas fa-calendar-alt absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none"></i>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="flex flex-col sm:flex-row items-center gap-2 justify-end">
                @if (request('search') || request('status') || request('payment_method') || request('date_from') || request('date_to'))
                    <button type="button" onclick="clearAllFilters()"
                        class="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2 text-sm font-medium rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors duration-200">
                        <i class="fas fa-times mr-2"></i>
                        Reset Filter
                    </button>
                @endif
            </div>
        </form>
    </div>

    <!-- Active Filters Info -->
    @if (request('search') || request('status') || request('payment_method') || request('date_from') || request('date_to'))
        <div class="mb-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg p-4">
            <div class="flex flex-wrap items-center gap-2">
                <span class="text-sm font-medium text-blue-800 dark:text-blue-200">Filter Aktif:</span>
                
                @if (request('search'))
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-800 dark:text-blue-200">
                        <i class="fas fa-search mr-1"></i>
                        Pencarian: "{{ request('search') }}"
                        <button onclick="clearFilter('search')" class="ml-2 hover:text-blue-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif
                
                @if (request('status'))
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-200">
                        <i class="fas fa-check-circle mr-1"></i>
                        Status: {{ ucfirst(request('status')) }}
                        <button onclick="clearFilter('status')" class="ml-2 hover:text-green-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif
                
                @if (request('payment_method'))
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-800 dark:text-purple-200">
                        <i class="fas fa-credit-card mr-1"></i>
                        Metode: {{ strtoupper(request('payment_method')) }}
                        <button onclick="clearFilter('payment_method')" class="ml-2 hover:text-purple-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif
                
                @if (request('date_from') || request('date_to'))
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800 dark:bg-orange-800 dark:text-orange-200">
                        <i class="fas fa-calendar-alt mr-1"></i>
                        Periode: {{ request('date_from') ? date('d M Y', strtotime(request('date_from'))) : 'Awal' }} - {{ request('date_to') ? date('d M Y', strtotime(request('date_to'))) : 'Akhir' }}
                        <button onclick="clearDateFilter()" class="ml-2 hover:text-orange-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif
                
                <button onclick="clearAllFilters()" 
                    class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-200 hover:bg-red-200 dark:hover:bg-red-700 transition-colors">
                    <i class="fas fa-times-circle mr-1"></i>
                    Hapus Semua Filter
                </button>
            </div>
        </div>
    @endif

    <!-- Table Container -->
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden transition-colors duration-300">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-600">
                    <tr>
                        <th class="w-16 px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">No</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300" style="width: 100px;">Gambar</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Produk</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Pembeli</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Jumlah</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Harga Satuan</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Total</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Metode</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Tanggal</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Status</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Aksi</th>
                    </tr>
                </thead>

                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                    @forelse ($sales as $sale)
                        <tr class="hover:bg-blue-50/50 dark:hover:bg-gray-700/80 transition-colors duration-200 cursor-pointer">
                            <!-- No -->
                            <td class="px-4 py-4 text-sm text-gray-900 dark:text-gray-100 text-center align-middle">
                                {{ $loop->iteration + $sales->firstItem() - 1 }}
                            </td>

                            <!-- Gambar Produk -->
                            <td class="px-4 py-4 text-center align-middle">
                                <div class="flex justify-center">
                                    @if ($sale->product && $sale->product->product_image)
                                        <img src="{{ asset('uploads/products/' . $sale->product->product_image) }}"
                                            alt="{{ $sale->product->product_title }}"
                                            class="h-16 w-16 object-contain"
                                            style="background: transparent;"
                                            onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                        <!-- Fallback jika gambar gagal dimuat -->
                                        <div class="h-16 w-16 bg-gray-100 dark:bg-gray-600 rounded flex items-center justify-center" style="display: none;">
                                            <i class="fas fa-image text-gray-400 dark:text-gray-500 text-lg"></i>
                                        </div>
                                    @elseif ($sale->product && $sale->product->images && $sale->product->images->count() > 0)
                                        <img src="{{ asset('uploads/products/' . $sale->product->images->first()->image_path) }}"
                                            alt="{{ $sale->product->product_title }}"
                                            class="h-16 w-16 object-contain"
                                            style="background: transparent;"
                                            onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                        <!-- Fallback jika gambar gagal dimuat -->
                                        <div class="h-16 w-16 bg-gray-100 dark:bg-gray-600 rounded flex items-center justify-center" style="display: none;">
                                            <i class="fas fa-image text-gray-400 dark:text-gray-500 text-lg"></i>
                                        </div>
                                    @else
                                        <div class="h-16 w-16 bg-gray-100 dark:bg-gray-600 rounded flex items-center justify-center">
                                            <i class="fas fa-image text-gray-400 dark:text-gray-500 text-lg"></i>
                                        </div>
                                    @endif
                                </div>
                            </td>

                            <!-- Produk -->
                            <td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100 font-medium align-middle">
                                {{ $sale->product->product_title ?? '-' }}
                            </td>

                            <!-- Pembeli -->
                            <td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100 font-medium align-middle">
                                {{ $sale->order->customer_name ?? '-' }}
                            </td>

                            <!-- Jumlah -->
                            <td class="px-4 py-4 text-center text-sm text-gray-900 dark:text-gray-100 align-middle">
                                {{ $sale->quantity }}
                            </td>

                            <!-- Harga Satuan -->
                            <td class="px-4 py-4 text-sm text-gray-900 dark:text-gray-100 font-semibold align-middle text-right">
                                Rp {{ number_format($sale->unit_price, 0, ',', '.') }}
                            </td>

                            <!-- Total -->
                            <td class="px-4 py-4 text-sm font-semibold text-green-600 dark:text-green-400 align-middle text-right">
                                Rp {{ number_format($sale->total_price, 0, ',', '.') }}
                            </td>

                            <!-- Metode -->
                            <td class="px-4 py-4 text-center align-middle">
                                @php
                                    $paymentMethodColors = [
                                        'transfer' => 'bg-blue-100 dark:bg-blue-900/40 text-blue-800 dark:text-blue-300',
                                        'qris' => 'bg-green-100 dark:bg-green-900/40 text-green-800 dark:text-green-300',
                                        'dp' => 'bg-purple-100 dark:bg-purple-900/40 text-purple-800 dark:text-purple-300',
                                        'cod' => 'bg-orange-100 dark:bg-orange-900/40 text-orange-800 dark:text-orange-300',
                                    ];
                                    $methodClass = $paymentMethodColors[strtolower($sale->payment_method ?? '')] ?? 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300';
                                @endphp
                                <span class="inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md {{ $methodClass }}">
                                    {{ strtoupper($sale->payment_method ?? '-') }}
                                </span>
                            </td>

                            <!-- Tanggal -->
                            <td class="px-4 py-4 text-sm text-gray-700 dark:text-gray-300 align-middle text-center">
                                {{ $sale->sale_date ? $sale->sale_date->format('d M Y') : '-' }}
                            </td>

                            <!-- Status -->
                            <td class="px-4 py-4 text-center align-middle">
                                @php
                                    $statusConfig = [
                                        'selesai' => [
                                            'bg' => 'bg-green-100 dark:bg-green-900/40',
                                            'text' => 'text-green-700 dark:text-green-300',
                                            'icon' => 'fa-check-circle'
                                        ],
                                        'dibatalkan' => [
                                            'bg' => 'bg-red-100 dark:bg-red-900/40',
                                            'text' => 'text-red-700 dark:text-red-300',
                                            'icon' => 'fa-times-circle'
                                        ],
                                    ];
                                    $config = $statusConfig[$sale->status] ?? [
                                        'bg' => 'bg-yellow-100 dark:bg-yellow-900/40',
                                        'text' => 'text-yellow-700 dark:text-yellow-300',
                                        'icon' => 'fa-clock'
                                    ];
                                @endphp
                                <span class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md {{ $config['bg'] }} {{ $config['text'] }}">
                                    <i class="fas {{ $config['icon'] }} text-xs"></i>
                                    <span>{{ ucfirst($sale->status) }}</span>
                                </span>
                            </td>

                            <!-- Aksi -->
                            <td class="px-4 py-4 text-center align-middle">
                                <div class="flex items-center justify-center space-x-2">
                                    <a href="{{ route('admin.transaksi.sales.show', $sale->id) }}"
                                        class="inline-flex items-center justify-center w-9 h-9 text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 rounded transition-colors duration-200"
                                        title="Detail">
                                        <i class="fas fa-eye text-base"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="11" class="px-6 py-16 text-center">
                                <div class="flex flex-col items-center">
                                    <div class="w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mb-4">
                                        <i class="fas fa-chart-line text-2xl text-gray-400 dark:text-gray-500"></i>
                                    </div>
                                    @if (request('search') || request('status') || request('payment_method') || request('date_from') || request('date_to'))
                                        <p class="text-gray-500 dark:text-gray-400 text-lg font-medium">Tidak ada hasil pencarian</p>
                                        <p class="text-gray-400 dark:text-gray-500 text-sm mt-1">Coba kata kunci lain atau <a href="{{ route('admin.transaksi.sales.index') }}" class="text-blue-600 dark:text-blue-400 hover:underline">reset pencarian</a></p>
                                    @else
                                        <p class="text-gray-500 dark:text-gray-400 text-lg font-medium">Belum ada data penjualan</p>
                                        <p class="text-gray-400 dark:text-gray-500 text-sm mt-1">Data penjualan dibuat otomatis dari pesanan yang sudah selesai pembayaran dan produksi</p>
                                    @endif
                                </div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <!-- Pagination -->
    @if ($sales->hasPages())
        <div class="mt-6 flex justify-center">
            {{ $sales->onEachSide(1)->links() }}
        </div>
    @endif

    <script>
        // Submit filter dengan parameter yang bersih
        function submitFilter() {
            const params = new URLSearchParams();
            
            // Ambil nilai dari setiap input/select
            const search = document.getElementById('searchInput')?.value?.trim() || '';
            const status = document.getElementById('statusFilter')?.value || '';
            const paymentMethod = document.getElementById('paymentMethodFilter')?.value || '';
            const dateFrom = document.getElementById('dateFromInput')?.value || '';
            const dateTo = document.getElementById('dateToInput')?.value || '';
            
            // Hanya tambahkan parameter yang memiliki nilai
            if (search) {
                params.append('search', search);
            }
            if (status) {
                params.append('status', status);
            }
            if (paymentMethod) {
                params.append('payment_method', paymentMethod);
            }
            if (dateFrom) {
                params.append('date_from', dateFrom);
            }
            if (dateTo) {
                params.append('date_to', dateTo);
            }
            
            // Redirect dengan parameter yang bersih
            const url = '{{ route("admin.transaksi.sales.index") }}' + (params.toString() ? '?' + params.toString() : '');
            window.location.href = url;
        }

        // Clear individual filter
        function clearFilter(filterName) {
            const url = new URL(window.location);
            url.searchParams.delete(filterName);
            window.location.href = url.toString();
        }

        // Clear date filter
        function clearDateFilter() {
            const url = new URL(window.location);
            url.searchParams.delete('date_from');
            url.searchParams.delete('date_to');
            window.location.href = url.toString();
        }

        // Clear all filters
        function clearAllFilters() {
            window.location.href = '{{ route("admin.transaksi.sales.index") }}';
        }

        // Submit form search dengan Enter
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('searchInput');
            if (searchInput) {
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        submitFilter();
                    }
                });
            }
        });
    </script>

    <style>
        /* Custom scrollbar untuk tabel */
        .overflow-x-auto::-webkit-scrollbar {
            height: 8px;
        }
        
        .overflow-x-auto::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 4px;
        }
        
        .overflow-x-auto::-webkit-scrollbar-thumb {
            background: #cbd5e0;
            border-radius: 4px;
        }
        
        .overflow-x-auto::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }
        
        /* Dark mode scrollbar */
        .dark .overflow-x-auto::-webkit-scrollbar-track {
            background: #374151;
        }
        
        .dark .overflow-x-auto::-webkit-scrollbar-thumb {
            background: #6b7280;
        }
        
        .dark .overflow-x-auto::-webkit-scrollbar-thumb:hover {
            background: #9ca3af;
        }

        /* Konsisten Style untuk semua Index Pages */
        .form-input-search,
        .form-select {
            height: 40px !important;
            min-height: 40px !important;
            max-height: 40px !important;
            box-sizing: border-box !important;
            line-height: 1.5 !important;
            padding: 0 2.5rem 0 2.5rem !important;
            margin: 0 !important;
        }
        
        .form-input-search {
            width: 100%;
            padding-left: 2.5rem !important;
            padding-right: 2.5rem !important;
            border: 1px solid rgb(209 213 219);
            border-radius: 0.5rem;
            background-color: white;
            color: rgb(17 24 39);
            font-size: 0.875rem;
            transition: all 0.2s;
        }
        
        .dark .form-input-search {
            border-color: rgb(75 85 99);
            background-color: rgb(55 65 81);
            color: white;
        }
        
        .form-input-search:focus {
            outline: none;
            ring: 2px;
            ring-color: rgb(59 130 246);
        }
        
        .form-select {
            width: 100%;
            padding-left: 1rem !important;
            padding-right: 2.5rem !important;
            border: 1px solid rgb(209 213 219);
            border-radius: 0.5rem;
            background-color: white;
            color: rgb(17 24 39);
            font-size: 0.875rem;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            transition: all 0.2s;
        }
        
        .dark .form-select {
            border-color: rgb(75 85 99);
            background-color: rgb(55 65 81);
            color: white;
        }
        
        .form-select:focus {
            outline: none;
            ring: 2px;
            ring-color: rgb(59 130 246);
        }
    </style>
@endsection
