@extends('layouts.app')

@section('title', 'Products')

@section('content')
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="mb-6 flex items-center justify-between">
        <h1 class="text-2xl font-bold">Product Catalog</h1>
        <a href="{{ route('products.create') }}"
           class="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg shadow hover:shadow-lg transition-all font-medium">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
            </svg>
            Add Product
        </a>
    </div>

    <!-- Filters -->
    <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow mb-6">
        <form method="GET" action="{{ route('products.index') }}">
            <div class="flex flex-wrap items-end gap-3">
                <!-- Search -->
                <div class="flex-1 min-w-[200px]">
                    <label class="block text-xs font-medium mb-1">Search</label>
                    <input type="text" name="search" value="{{ request('search') }}"
                           placeholder="Product name or SKU"
                           class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm py-1.5">
                </div>

                <!-- Status -->
                <div class="w-36">
                    <label class="block text-xs font-medium mb-1">Status</label>
                    <select name="status" class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm py-1.5">
                        <option value="">All</option>
                        <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>Active</option>
                        <option value="inactive" {{ request('status') == 'inactive' ? 'selected' : '' }}>Inactive</option>
                    </select>
                </div>

                <!-- Type (Own vs Global) -->
                <div class="w-36">
                    <label class="block text-xs font-medium mb-1">Type</label>
                    <select name="type" class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm py-1.5">
                        <option value="">All Products</option>
                        <option value="own" {{ request('type') == 'own' ? 'selected' : '' }}>My Products</option>
                        <option value="global" {{ request('type') == 'global' ? 'selected' : '' }}>Global Products</option>
                    </select>
                </div>

                <!-- Buttons -->
                <div class="flex gap-2">
                    <button type="submit" class="inline-flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 shadow-sm hover:shadow-md transition-all text-sm font-medium">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"/>
                        </svg>
                        Filter
                    </button>
                    <a href="{{ route('products.index') }}" class="inline-flex items-center gap-1.5 px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-400 dark:hover:bg-gray-700 shadow-sm hover:shadow-md transition-all text-sm font-medium">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                        </svg>
                        Reset
                    </a>
                </div>
            </div>
        </form>
    </div>

    <!-- Products Table -->
    <div class="bg-white dark:bg-gray-800 shadow rounded-lg overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
            <thead class="bg-gray-50 dark:bg-gray-700">
                <tr>
                    <th class="px-4 py-3 text-center text-xs font-medium uppercase tracking-wider">
                        <span class="flex items-center justify-center gap-1">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                            </svg>
                            Sell
                        </span>
                    </th>
                    <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">SKU</th>
                    <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">Product Name</th>
                    <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">Type</th>
                    <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">Price</th>
                    <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">Stock</th>
                    <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">Status</th>
                    <th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider">Actions</th>
                </tr>
            </thead>
            <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                @forelse($products as $product)
                @php
                    // Safely check if product is enabled for this user
                    $userProduct = auth()->user()->products->where('id', $product->id)->first();
                    $isChecked = $userProduct && $userProduct->pivot && $userProduct->pivot->is_enabled;
                @endphp
                <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">
                    <td class="px-4 py-3 text-center">
                        <input type="checkbox"
                               data-product-id="{{ $product->id }}"
                               {{ $isChecked ? 'checked' : '' }}
                               onchange="toggleProduct(this, {{ $product->id }})"
                               class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600">
                    </td>
                    <td class="px-4 py-3 text-sm font-mono text-gray-600 dark:text-gray-400">
                        {{ $product->sku ?: '-' }}
                    </td>
                    <td class="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">
                        <div class="flex items-center gap-2">
                            <span>{{ $product->name }}</span>
                            @if($product->isAdminProduct())
                                <span class="px-2 py-0.5 inline-flex text-xs font-medium rounded bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                                    Global
                                </span>
                            @endif
                        </div>
                        @if($product->description)
                            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ Str::limit($product->description, 50) }}</p>
                        @endif
                    </td>
                    <td class="px-4 py-3 text-sm">
                        @if($product->isBundle())
                            <span class="px-2 py-1 inline-flex text-xs font-medium rounded bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200">
                                Bundle
                            </span>
                            @if($product->bundle_items)
                                <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                    <div class="font-semibold">{{ count($product->bundle_items) }} items:</div>
                                    @foreach($product->bundle_items as $bundleItem)
                                        <div class="ml-2">
                                            • {{ $bundleItem['name'] ?? $bundleItem['sku'] ?? 'N/A' }} x{{ $bundleItem['quantity'] }}
                                        </div>
                                    @endforeach
                                </div>
                            @endif
                        @else
                            <span class="px-2 py-1 inline-flex text-xs font-medium rounded bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300">
                                Single
                            </span>
                        @endif
                    </td>
                    <td class="px-4 py-3 text-sm font-semibold text-gray-900 dark:text-white">
                        RM {{ number_format($product->price, 2) }}
                    </td>
                    <td class="px-4 py-3 text-sm text-gray-600 dark:text-gray-400">
                        {{ $product->stock ?? '-' }}
                    </td>
                    <td class="px-4 py-3 text-sm">
                        @if($product->is_active)
                            <span class="px-2 py-1 inline-flex text-xs font-medium rounded bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">
                                Active
                            </span>
                        @else
                            <span class="px-2 py-1 inline-flex text-xs font-medium rounded bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300">
                                Inactive
                            </span>
                        @endif
                    </td>
                    <td class="px-4 py-3 text-sm">
                        @if($product->user_id === auth()->id())
                            <!-- User owns this product - can edit and delete -->
                            <div class="flex items-center gap-2">
                                <a href="{{ route('products.edit', $product) }}"
                                   class="text-indigo-600 dark:text-indigo-400 hover:text-indigo-900 dark:hover:text-indigo-300 font-medium">
                                    Edit
                                </a>
                                <form action="{{ route('products.destroy', $product) }}" method="POST" class="inline"
                                      onsubmit="return confirm('Are you sure you want to delete this product?');">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300 font-medium">
                                        Delete
                                    </button>
                                </form>
                            </div>
                        @else
                            <!-- Global product - read-only -->
                            <span class="text-gray-400 dark:text-gray-500 text-xs italic">Read-only</span>
                        @endif
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="8" class="px-6 py-8 text-center text-gray-500 dark:text-gray-400">
                        No products found.
                        <a href="{{ route('products.create') }}" class="text-blue-600 hover:text-blue-800">Add your first product</a>
                    </td>
                </tr>
                @endforelse
            </tbody>
        </table>

        <!-- Pagination -->
        @if($products->hasPages())
        <div class="px-4 py-3 border-t border-gray-200 dark:border-gray-700">
            {{ $products->links() }}
        </div>
        @endif
    </div>
</div>
@endsection

@push('scripts')
<script>
function toggleProduct(checkbox, productId) {
    const isEnabled = checkbox.checked;

    fetch(`/products/${productId}/toggle`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
        },
        body: JSON.stringify({
            is_enabled: isEnabled
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log(`Product ${productId} ${isEnabled ? 'enabled' : 'disabled'} for checkout`);
        } else {
            console.error('Failed to toggle product');
            // Revert checkbox state on error
            checkbox.checked = !isEnabled;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        // Revert checkbox state on error
        checkbox.checked = !isEnabled;
    });
}
</script>
@endpush
