@extends('layouts.app')

@section('title', 'Add Product')

@section('content')
<div class="max-w-3xl 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">Add New Product</h1>
        <a href="{{ route('products.index') }}" class="text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200">
            ← Back to Products
        </a>
    </div>

    <form method="POST" action="{{ route('products.store') }}" class="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
        @csrf

        <div class="space-y-6">
            <!-- Product Name -->
            <div>
                <label class="block text-sm font-medium mb-2">Product Name <span class="text-red-500">*</span></label>
                <input type="text" name="name" required
                       class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                       value="{{ old('name') }}"
                       placeholder="e.g., Blue T-Shirt (L)">
                @error('name')
                    <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                @enderror
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- SKU -->
                <div>
                    <label class="block text-sm font-medium mb-2">SKU / Product Code</label>
                    <input type="text" name="sku"
                           class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                           value="{{ old('sku') }}"
                           placeholder="e.g., TS-BLU-L">
                    @error('sku')
                        <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                    <p class="text-xs text-gray-500 mt-1">Optional - for easier searching</p>
                </div>

                <!-- Product Type -->
                <div>
                    <label class="block text-sm font-medium mb-2">Product Type <span class="text-red-500">*</span></label>
                    <select name="product_type" id="product_type" required
                            class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700">
                        <option value="single" {{ old('product_type', 'single') == 'single' ? 'selected' : '' }}>Single Product</option>
                        <option value="bundle" {{ old('product_type') == 'bundle' ? 'selected' : '' }}>Bundle / Package</option>
                    </select>
                    @error('product_type')
                        <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <!-- Bundle Items (shown only for bundles) -->
            <div id="bundle_section" class="hidden">
                <label class="block text-sm font-medium mb-2">Bundle Items</label>
                <div class="space-y-2 mb-2" id="bundle_items">
                    <!-- Bundle items will be added here dynamically -->
                </div>
                <button type="button" onclick="addBundleItem()"
                        class="text-sm text-blue-600 hover:text-blue-800">
                    + Add Item to Bundle
                </button>
                <p class="text-xs text-gray-500 mt-1">Select products and quantities that make up this bundle</p>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Price -->
                <div>
                    <label class="block text-sm font-medium mb-2">Price (RM) <span class="text-red-500">*</span></label>
                    <input type="number" name="price" required min="0" step="0.01"
                           class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                           value="{{ old('price') }}"
                           placeholder="0.00">
                    @error('price')
                        <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>

            <!-- Stock -->
            <div>
                <label class="block text-sm font-medium mb-2">Stock Quantity</label>
                <input type="number" name="stock" min="0"
                       class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                       value="{{ old('stock') }}"
                       placeholder="Leave empty if not tracking stock">
                @error('stock')
                    <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                @enderror
                <p class="text-xs text-gray-500 mt-1">Optional - for inventory tracking</p>
            </div>

            <!-- Description -->
            <div>
                <label class="block text-sm font-medium mb-2">Description</label>
                <textarea name="description" rows="3"
                          class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700"
                          placeholder="Optional product description or notes">{{ old('description') }}</textarea>
                @error('description')
                    <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                @enderror
            </div>

            <!-- Active Status -->
            <div class="flex items-center">
                <input type="checkbox" name="is_active" id="is_active" value="1" checked
                       class="rounded border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-blue-600 focus:ring-blue-500">
                <label for="is_active" class="ml-2 text-sm font-medium">
                    Active (available for checkout)
                </label>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="mt-8 flex items-center justify-end gap-3">
            <a href="{{ route('products.index') }}"
               class="px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                Cancel
            </a>
            <button type="submit"
                    class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg shadow hover:shadow-lg transition-all">
                Add Product
            </button>
        </div>
    </form>
</div>

<script>
let bundleItemIndex = 0;

// Toggle bundle section visibility
document.getElementById('product_type').addEventListener('change', function() {
    const bundleSection = document.getElementById('bundle_section');
    if (this.value === 'bundle') {
        bundleSection.classList.remove('hidden');
        if (document.getElementById('bundle_items').children.length === 0) {
            addBundleItem(); // Add first item automatically
        }
    } else {
        bundleSection.classList.add('hidden');
    }
});

async function addBundleItem() {
    const container = document.getElementById('bundle_items');

    // Fetch products if not already fetched
    if (!window.allProducts) {
        try {
            const response = await fetch('{{ route("products.search.api") }}?q=');
            window.allProducts = await response.json();
        } catch (error) {
            console.error('Error fetching products:', error);
            window.allProducts = [];
        }
    }

    const itemDiv = document.createElement('div');
    itemDiv.className = 'flex gap-2 items-center';

    // Create product select options
    const productOptions = window.allProducts
        .filter(p => !p.is_bundle) // Only show single products, not bundles
        .map(p => `<option value="${p.id}" data-sku="${p.sku}" data-name="${p.name}">${p.display_name || p.name} ${p.sku ? '('+p.sku+')' : ''}</option>`)
        .join('');

    itemDiv.innerHTML = `
        <select name="bundle_items[${bundleItemIndex}][product_id]" required
                onchange="updateBundleItemData(this, ${bundleItemIndex})"
                class="flex-1 rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm">
            <option value="">Select Product</option>
            ${productOptions}
        </select>
        <input type="hidden" name="bundle_items[${bundleItemIndex}][sku]" id="sku_${bundleItemIndex}">
        <input type="hidden" name="bundle_items[${bundleItemIndex}][name]" id="name_${bundleItemIndex}">
        <input type="number" name="bundle_items[${bundleItemIndex}][quantity]"
               placeholder="Qty" min="1" value="1" required
               class="w-24 rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm">
        <button type="button" onclick="removeBundleItem(this)"
                class="text-red-600 hover:text-red-800 text-sm font-medium">
            Remove
        </button>
    `;
    container.appendChild(itemDiv);
    bundleItemIndex++;
}

function updateBundleItemData(selectElement, index) {
    const selectedOption = selectElement.options[selectElement.selectedIndex];
    const sku = selectedOption.dataset.sku || '';
    const name = selectedOption.dataset.name || '';

    document.getElementById(`sku_${index}`).value = sku;
    document.getElementById(`name_${index}`).value = name;
}

function removeBundleItem(button) {
    button.parentElement.remove();
}

// Initialize on page load if bundle type is selected
if (document.getElementById('product_type').value === 'bundle') {
    document.getElementById('bundle_section').classList.remove('hidden');
}
</script>
@endsection
