@extends('layouts.app')

@section('title', 'Products List')
@section('header', 'Manage Products')
@section('subheader', 'View, search, and manage all products in the system.')

@section('content')
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="bg-gradient-to-r from-primary to-purple-700 px-6 py-4">
            <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                    <h1 class="text-2xl font-bold text-white flex items-center"><i class="fas fa-boxes-stacked mr-3"></i>Stock Management</h1>
                    <p class="text-blue-100 mt-1">Track and manage your product inventory</p>
                </div>
                <div class="mt-4 md:mt-0">
                    <a href="{{ route('admin.scanner.index') }}" class="inline-block px-5 py-2 bg-white text-primary rounded-lg font-semibold hover:bg-gray-100 transition-colors">
                        <i class="fas fa-qrcode mr-2"></i>Scan with Create New Product
                    </a>
                </div>
            </div>
        </div>

        <!-- Statistics Cards -->
        @if(isset($stats))
        <div class="px-6 py-4 bg-gray-50 border-b border-gray-200">
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
                <div class="bg-white rounded-lg shadow p-4 text-center">
                    <p class="text-sm font-medium text-gray-500">Total Products</p>
                    <p class="text-2xl font-bold text-gray-800">{{ $stats['total_products'] ?? 'N/A' }}</p>
                </div>
                <div class="bg-white rounded-lg shadow p-4 text-center">
                    <p class="text-sm font-medium text-gray-500">In Warehouse</p>
                    <p class="text-2xl font-bold text-indigo-600">{{ $stats['in_warehouse'] ?? 'N/A' }}</p>
                </div>
                <div class="bg-white rounded-lg shadow p-4 text-center">
                    <p class="text-sm font-medium text-gray-500">Shipped</p>
                    <p class="text-2xl font-bold text-yellow-600">{{ $stats['shipped'] ?? 'N/A' }}</p>
                </div>
                <div class="bg-white rounded-lg shadow p-4 text-center">
                    <p class="text-sm font-medium text-gray-500">Delivered</p>
                    <p class="text-2xl font-bold text-green-600">{{ $stats['delivered'] ?? 'N/A' }}</p>
                </div>
                <div class="bg-white rounded-lg shadow p-4 text-center">
                    <p class="text-sm font-medium text-gray-500">Sold</p>
                    <p class="text-2xl font-bold text-purple-600">{{ $stats['sold'] ?? 'N/A' }}</p>
                </div>
                <div class="bg-white rounded-lg shadow p-4 text-center">
                    <p class="text-sm font-medium text-gray-500">Returned</p>
                    <p class="text-2xl font-bold text-red-600">{{ $stats['returned'] ?? 'N/A' }}</p>
                </div>
            </div>
        </div>
        @endif


        <!-- Search and Filter Section -->
        <div class="px-6 py-4 bg-gray-50 border-b border-gray-200">
            <form method="GET" action="{{ route('admin.products') }}" class="flex flex-col md:flex-row gap-4">
                <div class="relative flex-grow">
                    <input type="text" name="search" value="{{ $search }}" placeholder="Search products..."
                           class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                </div>
                <div class="flex flex-col sm:flex-row gap-2">
                    <select name="quality" class="bg-white px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">All Qualities</option>
                        <option value="Authentic" {{ $quality == 'Authentic' ? 'selected' : '' }}>Authentic</option>
                        <option value="Premium" {{ $quality == 'Premium' ? 'selected' : '' }}>Premium</option>
                        <option value="Standard" {{ $quality == 'Standard' ? 'selected' : '' }}>Standard</option>
                    </select>
                    <select name="color" class="bg-white px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">All Colors</option>
                        <option value="Black" {{ $color == 'Black' ? 'selected' : '' }}>Black</option>
                        <option value="Blue" {{ $color == 'Blue' ? 'selected' : '' }}>Blue</option>
                        <option value="Blue Ae" {{ $color == 'Blue Ae' ? 'selected' : '' }}>Blue Ae</option>
                        <option value="Cyan" {{ $color == 'Cyan' ? 'selected' : '' }}>Cyan</option>
                        <option value="Gold" {{ $color == 'Gold' ? 'selected' : '' }}>Gold</option>
                        <option value="Gray" {{ $color == 'Gray' ? 'selected' : '' }}>Gray</option>
                        <option value="Green" {{ $color == 'Green' ? 'selected' : '' }}>Green</option>
                        <option value="Red" {{ $color == 'Red' ? 'selected' : '' }}>Red</option>
                        <option value="Silver" {{ $color == 'Silver' ? 'selected' : '' }}>Silver</option>
                        <option value="White" {{ $color == 'White' ? 'selected' : '' }}>White</option>
                        <option value="Yellow" {{ $color == 'Yellow' ? 'selected' : '' }}>Yellow</option>
                    </select>
                    <button type="submit" class="px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"><i class="fas fa-filter mr-2"></i>Filter</button>
                </div>
            </form>
        </div>

        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr class="text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        <th class="px-6 py-3"><i class="fas fa-hashtag mr-1"></i>#</th>
                        <th class="px-6 py-3"><i class="fas fa-barcode mr-1"></i>Serial No</th>
                        <th class="px-6 py-3"><i class="fas fa-box mr-1"></i>Product Name</th>
                        <th class="px-6 py-3"><i class="fas fa-heart-pulse mr-1"></i>Condition</th>
                        <th class="px-6 py-3"><i class="fas fa-truck-fast mr-1"></i>Status</th>
                        <th class="px-6 py-3"><i class="fas fa-star mr-1"></i>Quality</th>
                        <th class="px-6 py-3"><i class="fas fa-mobile-screen-button mr-1"></i>IMEI</th>
                        <th class="px-6 py-3"><i class="fas fa-palette mr-1"></i>Color</th>
                        <th class="px-6 py-3"><i class="fas fa-building mr-1"></i>Distributor</th>
                        <th class="px-6 py-3"><i class="fas fa-store mr-1"></i>Retailer</th>
                        <th class="px-6 py-3"><i class="fas fa-user mr-1"></i>Client</th>
                        <th class="px-6 py-3"><i class="fas fa-cogs mr-1"></i>Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    @foreach($products as $product)
                    <tr class="hover:bg-gray-50 transition-shadow duration-200 hover:shadow-md" data-product-id="{{ $product->id }}">
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ $loop->iteration }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 font-mono">{{ $product->serial_no }}</td>

                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <div class="dropdown">
                                <div id="product_name-btn-{{ $loop->iteration }}" class="dropdown-btn" onclick="toggleDropdown('product_name-dropdown-{{ $loop->iteration }}')">
                                    <span>{{ $product->product_name }}</span>
                                    <i class="fas fa-chevron-down text-xs ml-1"></i>
                                </div>
                                <div id="product_name-dropdown-{{ $loop->iteration }}" class="dropdown-content">
                                    {{-- This should ideally come from your controller --}}
                                    @php $productNames = ['Nokia 105 (2023) +', 'Nokia 105 (2022) +', 'Nokia 210', 'Nokia 5310']; @endphp
                                    @foreach($productNames as $name)
                                        {{-- Use addslashes to escape quotes in product names --}}
                                        <a onclick="updateProductField({{ $product->id }}, 'product_name', '{{ addslashes($name) }}', {{ $loop->parent->iteration }})">{{ $name }}</a>
                                    @endforeach
                                </div>
                            </div>
                        </td>

                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $product->condition }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <div class="dropdown">
                                <div id="status-btn-{{ $loop->iteration }}" class="dropdown-btn" onclick="toggleDropdown('status-dropdown-{{ $loop->iteration }}')">
                                    <span id="status-badge-{{ $loop->iteration }}" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full @switch($product->status) @case('In Warehouse') bg-blue-100 text-blue-800 @break @case('Shipped') bg-yellow-100 text-yellow-800 @break @case('Delivered') bg-green-100 text-green-800 @break @case('Sold') bg-purple-100 text-purple-800 @break @case('Returned') bg-red-100 text-red-800 @break @default bg-gray-100 text-gray-800 @endswitch">
                                        {{ $product->status }}
                                    </span>
                                    <i class="fas fa-chevron-down text-xs ml-1"></i>
                                </div>
                                <div id="status-dropdown-{{ $loop->iteration }}" class="dropdown-content">
                                    <a onclick="updateProductField({{ $product->id }}, 'status', 'In Warehouse', {{ $loop->iteration }})">In Warehouse</a>
                                    <a onclick="updateProductField({{ $product->id }}, 'status', 'Shipped', {{ $loop->iteration }})">Shipped</a>
                                    <a onclick="updateProductField({{ $product->id }}, 'status', 'Delivered', {{ $loop->iteration }})">Delivered</a>
                                    <a onclick="updateProductField({{ $product->id }}, 'status', 'Sold', {{ $loop->iteration }})">Sold</a>
                                    <a onclick="updateProductField({{ $product->id }}, 'status', 'Returned', {{ $loop->iteration }})">Returned</a>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <div class="dropdown">
                                <div id="quality-btn-{{ $loop->iteration }}" class="dropdown-btn" onclick="toggleDropdown('quality-dropdown-{{ $loop->iteration }}')">
                                    <span>{{ $product->quality }}</span>
                                    <i class="fas fa-chevron-down text-xs ml-1"></i>
                                </div>
                                <div id="quality-dropdown-{{ $loop->iteration }}" class="dropdown-content">
                                    <a onclick="updateProductField({{ $product->id }}, 'quality', 'Authentic', {{ $loop->iteration }})">Authentic</a>
                                    <a onclick="updateProductField({{ $product->id }}, 'quality', 'Premium', {{ $loop->iteration }})">Premium</a>
                                    <a onclick="updateProductField({{ $product->id }}, 'quality', 'Standard', {{ $loop->iteration }})">Standard</a>
                                    <a onclick="updateProductField({{ $product->id }}, 'quality', 'Economy', {{ $loop->iteration }})">Economy</a>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 font-mono">{{ $product->imei }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <div class="dropdown">
                                <div id="color-btn-{{ $loop->iteration }}" class="dropdown-btn" onclick="toggleDropdown('color-dropdown-{{ $loop->iteration }}')">
                                    <span>{{ is_array($product->color) ? implode(', ', $product->color) : $product->color }}</span>
                                    <i class="fas fa-chevron-down text-xs ml-1"></i>
                                </div>
                                <div id="color-dropdown-{{ $loop->iteration }}" class="dropdown-content">
                                    <a onclick="updateProductField({{ $product->id }}, 'color', 'Cyan', {{ $loop->iteration }})">Cyan</a>
                                    <a onclick="updateProductField({{ $product->id }}, 'color', 'White', {{ $loop->iteration }})">White</a>
                                    <a onclick="updateProductField({{ $product->id }}, 'color', 'Black', {{ $loop->iteration }})">Black</a>
                                    <a onclick="updateProductField({{ $product->id }}, 'color', 'Red', {{ $loop->iteration }})">Red</a>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $product->distributor_name }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $product->retailer_name }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $product->client_name }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <div class="flex items-center space-x-4">
                                <a href="{{ route('admin.products.edit', $product->id) }}" class="text-indigo-600 hover:text-indigo-900" title="Edit Product">
                                    <i class="fas fa-pencil-alt"></i>
                                </a>
                                <form action="{{ route('admin.products.delete', $product->id) }}" method="POST" onsubmit="return confirm('Are you sure you want to delete this product?');">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="text-red-600 hover:text-red-900" title="Delete Product"><i class="fas fa-trash"></i></button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <div class="bg-gray-50 px-6 py-3 flex items-center justify-between border-t border-gray-200">
            <div class="text-sm text-gray-700">
                Showing <span class="font-medium">{{ $products->firstItem() }}</span> to <span class="font-medium">{{ $products->lastItem() }}</span> of <span class="font-medium">{{ $products->total() }}</span> results
            </div>
            <div class="flex space-x-2">
                @if($products->onFirstPage())
                    <span class="px-4 py-2 text-sm bg-gray-200 text-gray-500 rounded-lg cursor-not-allowed">Previous</span>
                @else
                    <a href="{{ $products->previousPageUrl() . '&' . http_build_query(request()->except('page')) }}" class="px-4 py-2 text-sm bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">Previous</a>
                @endif

                @if($products->hasMorePages())
                    <a href="{{ $products->nextPageUrl() . '&' . http_build_query(request()->except('page')) }}" class="px-4 py-2 text-sm bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">Next</a>
                @else
                    <span class="px-4 py-2 text-sm bg-gray-200 text-gray-500 rounded-lg cursor-not-allowed">Next</span>
                @endif
            </div>
        </div>
    </div>
</div>

@endsection



@push('scripts')
    {{-- This script contains the logic for dropdowns and inline updates --}}
    <script>
        // Define a global URL template for the update route, making it robust
        window.productUpdateUrl = "{{ route('admin.products.update', ['product' => 'PRODUCT_ID_PLACEHOLDER']) }}";
    </script>
    <script src="{{ asset('admin/assets/js/products.js') }}"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Define the showToast function globally for this page
            window.showToast = function(message, type = 'info') {
                const toast = document.createElement('div');
                const iconClass = type === 'success' ? 'fa-check-circle' : (type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle');
                const bgColor = type === 'success' ? 'bg-green-500' : (type === 'error' ? 'bg-red-500' : 'bg-blue-500');

                toast.className = `toast-notification fixed top-5 right-5 p-4 rounded-lg shadow-lg z-[1000] flex items-center text-white ${bgColor}`;
                toast.innerHTML = `
                    <i class="fas ${iconClass} mr-3"></i>
                    <span>${message}</span>
                    <button onclick="this.parentElement.remove()" class="ml-4 text-white hover:text-gray-200">
                        <i class="fas fa-times"></i>
                    </button>
                `;

                document.body.appendChild(toast);

                setTimeout(() => {
                    if (toast.parentElement) {
                        toast.remove();
                    }
                }, 5000);
            };

            // Check for session flash messages and show toast
            @if (session('success'))
                showToast('{{ session('success') }}', 'success');
            @endif
            @if (session('error'))
                showToast('{{ session('error') }}', 'error');
            @endif
        });
    </script>
@endpush
