<x-tenant-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Create Purchase Requisition') }}
        </h2>
    </x-slot>

    <div class="py-12" x-data="requisitionApp()">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    <form method="POST" action="{{ route('tenant.requisitions.store') }}">
                        @csrf

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                            <!-- Supplier Selection -->
                            <div>
                                <label for="supplier_id" class="block text-sm font-medium text-gray-700">Supplier</label>
                                <div class="flex gap-2">
                                    <select name="supplier_id" id="supplier_id" x-model="selectedSupplier" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50">
                                        <option value="">-- No Supplier (Open Market) --</option>
                                        @foreach($suppliers as $supplier)
                                            <option value="{{ $supplier->id }}">{{ $supplier->name }}</option>
                                        @endforeach
                                    </select>
                                    <button type="button" @click="openSupplierModal = true" class="mt-1 px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700" title="Add Supplier">+</button>
                                </div>
                            </div>

                            <!-- Purpose -->
                            <div>
                                <label for="purpose" class="block text-sm font-medium text-gray-700">Purpose</label>
                                <select name="purpose" id="purpose" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50">
                                    <option value="">-- Select Purpose --</option>
                                    <option value="Low Stock">Low Stock</option>
                                    <option value="Low Price">Low Price Opportunity</option>
                                    <option value="Advance Stock">Advance Stock / Seasonal</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                        </div>

                        <!-- Low Stock Alert -->
                        @if($lowStockProducts->count() > 0)
                            <div class="mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md">
                                <h4 class="text-sm font-bold text-yellow-800 mb-2">Low Stock Alert (<= 10)</h4>
                                <div class="flex flex-wrap gap-2">
                                    @foreach($lowStockProducts as $variant)
                                        <button type="button" 
                                            @click="addItem({{ $variant->id }}, `{{ addslashes($variant->product->name . ($variant->name !== $variant->product->name ? ' - ' . $variant->name : '')) }}`, {{ $variant->cost ?? 0 }})" 
                                            class="text-xs bg-white border border-yellow-300 text-yellow-700 px-2 py-1 rounded hover:bg-yellow-100">
                                            {{ $variant->product->name }} ({{ $variant->stock }})
                                        </button>
                                    @endforeach
                                </div>
                            </div>
                        @endif

                        <!-- Items Table -->
                        <div class="mb-4">
                            <div class="flex justify-between items-center mb-2">
                                <h3 class="text-lg font-medium text-gray-900">Items</h3>
                                <div class="flex gap-2">
                                    <div class="relative" @click.away="showDropdown = false">
                                        <div class="relative">
                                            <input 
                                                type="text" 
                                                x-model="productSearch" 
                                                @focus="showDropdown = true"
                                                placeholder="Search product by Name or SKU..." 
                                                class="text-sm border-gray-300 rounded-md shadow-sm focus:border-green-500 focus:ring-green-500 w-64 pl-8"
                                            >
                                            <div class="absolute inset-y-0 left-0 pl-2 flex items-center pointer-events-none">
                                                <svg class="h-4 w-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                                            </div>
                                        </div>
                                        
                                        <div x-show="showDropdown && (filteredProducts.length > 0 || productSearch.length > 0)" 
                                             class="absolute z-20 w-96 bg-white border border-gray-200 mt-1 rounded-md shadow-xl max-h-60 overflow-y-auto right-0"
                                             style="display: none;">
                                            
                                            <template x-for="product in filteredProducts.slice(0, 50)" :key="product.id">
                                                <div @click="addItem(product.id, product.name, product.cost); showDropdown = false; productSearch = ''" class="px-4 py-2 hover:bg-green-50 cursor-pointer text-sm border-b border-gray-50 last:border-0 transition-colors">
                                                    <div class="flex justify-between">
                                                        <span class="font-medium text-gray-900" x-text="product.name"></span>
                                                        <span class="text-xs font-bold text-green-600" x-text="'$' + parseFloat(product.cost).toFixed(2)"></span>
                                                    </div>
                                                    <div class="text-xs text-gray-500 flex justify-between mt-1">
                                                        <span>SKU: <span x-text="product.sku"></span></span>
                                                        <span>Stock: <span x-text="product.stock"></span></span>
                                                    </div>
                                                </div>
                                            </template>
                                            
                                            <div x-show="filteredProducts.length === 0" class="px-4 py-3 text-sm text-gray-500 text-center">
                                                No products found matching "<span x-text="productSearch"></span>"
                                            </div>
                                        </div>
                                    </div>
                                    <button type="button" @click="openProductModal = true" class="text-sm bg-gray-800 text-white px-3 py-1 rounded hover:bg-gray-700 shadow-sm">
                                        + Add New
                                    </button>
                                </div>
                            </div>
                            
                            <table class="min-w-full divide-y divide-gray-200 border">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Product</th>
                                        <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Cost</th>
                                        <th class="px-4 py-2 text-center text-xs font-medium text-gray-500 uppercase">Qty</th>
                                        <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Total</th>
                                        <th class="px-4 py-2"></th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    <template x-if="items.length === 0">
                                        <tr>
                                            <td colspan="5" class="px-4 py-8 text-center text-gray-500">
                                                No items added. Search products or add from low stock list.
                                            </td>
                                        </tr>
                                    </template>
                                    <template x-for="(item, index) in items" :key="index">
                                        <tr>
                                            <td class="px-4 py-2">
                                                <input type="hidden" :name="'items['+index+'][variant_id]'" :value="item.id">
                                                <span x-text="item.name"></span>
                                            </td>
                                            <td class="px-4 py-2 text-right">
                                                <input type="number" step="0.01" :name="'items['+index+'][cost_price]'" x-model="item.cost" class="w-24 text-right border-gray-300 rounded-md text-sm p-1">
                                            </td>
                                            <td class="px-4 py-2 text-center">
                                                <input type="number" step="1" :name="'items['+index+'][quantity]'" x-model="item.qty" class="w-20 text-center border-gray-300 rounded-md text-sm p-1">
                                            </td>
                                            <td class="px-4 py-2 text-right">
                                                <span x-text="'$' + (item.cost * item.qty).toFixed(2)"></span>
                                            </td>
                                            <td class="px-4 py-2 text-center">
                                                <button type="button" @click="removeItem(index)" class="text-red-600 hover:text-red-900">&times;</button>
                                            </td>
                                        </tr>
                                    </template>
                                </tbody>
                                <tfoot>
                                    <tr class="bg-gray-50 font-bold">
                                        <td colspan="3" class="px-4 py-2 text-right">Total:</td>
                                        <td class="px-4 py-2 text-right" x-text="'$' + totalAmount.toFixed(2)"></td>
                                        <td></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        <div class="mb-4">
                            <label for="note" class="block text-sm font-medium text-gray-700">Note</label>
                            <textarea name="note" id="note" rows="2" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50"></textarea>
                        </div>

                        <div class="flex items-center justify-end">
                            <a href="{{ route('tenant.requisitions.index') }}" class="text-gray-600 hover:text-gray-900 mr-4">Cancel</a>
                            <button type="submit" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded ml-4" :disabled="items.length === 0">
                                Submit Requisition
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Supplier Modal -->
        <div x-show="openSupplierModal" class="fixed inset-0 z-50 overflow-y-auto" style="display: none;">
            <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                <div class="fixed inset-0 transition-opacity" aria-hidden="true" @click="openSupplierModal = false">
                    <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
                </div>
                <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
                <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                    <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                        <h3 class="text-lg leading-6 font-medium text-gray-900">Add New Supplier</h3>
                        <div class="mt-4 space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Name</label>
                                <input type="text" x-model="newSupplier.name" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Contact</label>
                                <input type="text" x-model="newSupplier.contact" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                        <button type="button" @click="saveSupplier" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 sm:ml-3 sm:w-auto sm:text-sm">
                            Save
                        </button>
                        <button type="button" @click="openSupplierModal = false" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                            Cancel
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Product Modal -->
        <div x-show="openProductModal" class="fixed inset-0 z-50 overflow-y-auto" style="display: none;">
            <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                <div class="fixed inset-0 transition-opacity" aria-hidden="true" @click="openProductModal = false">
                    <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
                </div>
                <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
                <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                    <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                        <h3 class="text-lg leading-6 font-medium text-gray-900">Add New Product</h3>
                        <div class="mt-4 space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Product Name</label>
                                <input type="text" x-model="newProduct.name" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                            </div>
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">SKU</label>
                                    <input type="text" x-model="newProduct.sku" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Category</label>
                                    <select x-model="newProduct.category_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                        <option value="">Select Category</option>
                                        @foreach($categories as $category)
                                            <option value="{{ $category->id }}">{{ $category->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Cost Price</label>
                                    <input type="number" step="0.01" x-model="newProduct.cost" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Selling Price</label>
                                    <input type="number" step="0.01" x-model="newProduct.price" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                </div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Unit</label>
                                <select x-model="newProduct.unit_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                                    <option value="">Select Unit</option>
                                    @foreach($units as $unit)
                                        <option value="{{ $unit->id }}">{{ $unit->name }} ({{ $unit->short_name }})</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                        <button type="button" @click="saveProduct" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 sm:ml-3 sm:w-auto sm:text-sm">
                            Add & Select
                        </button>
                        <button type="button" @click="openProductModal = false" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                            Cancel
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

@section('scripts')
    <!-- jQuery CDN -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('requisitionApp', () => ({
                items: [],
                products: @json($products), // Load products from controller
                productSearch: '',
                showDropdown: false,
                selectedSupplier: '',
                openSupplierModal: false,
                openProductModal: false,
                
                newSupplier: { name: '', contact: '' },
                newProduct: { name: '', sku: '', price: '', cost: '', category_id: '', unit_id: '' },

                init() {
                    console.log('Requisition App Initialized');
                    console.log('Loaded Products:', this.products.length);
                },

                get filteredProducts() {
                    if (this.productSearch === '') return this.products;
                    const search = this.productSearch.toLowerCase();
                    return this.products.filter(p => {
                        const nameMatch = p.name && p.name.toLowerCase().includes(search);
                        const skuMatch = p.sku && String(p.sku).toLowerCase().includes(search);
                        return nameMatch || skuMatch;
                    });
                },

                addItem(id, name, cost) {
                    if (!this.items.find(i => i.id === id)) {
                        this.items.push({ id, name, cost: parseFloat(cost) || 0, qty: 1 });
                    }
                },
                removeItem(index) {
                    this.items.splice(index, 1);
                },
                get totalAmount() {
                    return this.items.reduce((sum, item) => sum + (item.cost * item.qty), 0);
                },

                saveSupplier() {
                    if (!this.newSupplier.name) return alert('Name is required');
                    
                    $.ajax({
                        url: '{{ route("tenant.requisitions.store-supplier") }}',
                        method: 'POST',
                        contentType: 'application/json',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        data: JSON.stringify(this.newSupplier),
                        success: (result) => {
                            if (result.success) {
                                // Dynamically add option to select
                                const select = document.getElementById('supplier_id');
                                const option = document.createElement("option");
                                option.text = result.supplier.name;
                                option.value = result.supplier.id;
                                select.add(option);
                                
                                this.selectedSupplier = result.supplier.id;
                                this.openSupplierModal = false;
                                this.newSupplier = { name: '', contact: '' };
                            } else {
                                alert('Error: ' + (result.message || 'Unknown error'));
                            }
                        },
                        error: (xhr) => {
                            console.error(xhr);
                            alert('Error saving supplier');
                        }
                    });
                },

                saveProduct() {
                    if (!this.newProduct.name || !this.newProduct.sku || !this.newProduct.price) return alert('Name, SKU and Price are required');
                    
                    $.ajax({
                        url: '{{ route("tenant.requisitions.store-product") }}',
                        method: 'POST',
                        contentType: 'application/json',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        data: JSON.stringify(this.newProduct),
                        success: (result) => {
                            if (result.success) {
                                // Add to local products list for search
                                this.products.push({
                                    id: result.product.variant_id,
                                    name: result.product.name,
                                    sku: this.newProduct.sku,
                                    stock: 0,
                                    cost: parseFloat(this.newProduct.cost) || 0,
                                    price: parseFloat(this.newProduct.price)
                                });

                                this.addItem(result.product.variant_id, result.product.name, result.product.cost);
                                this.openProductModal = false;
                                this.newProduct = { name: '', sku: '', price: '', cost: '', category_id: '', unit_id: '' };
                            } else {
                                alert('Error: ' + (result.message || 'Unknown error'));
                            }
                        },
                        error: (xhr) => {
                            console.error(xhr);
                            alert('Error saving product');
                        }
                    });
                }
            }));
        });
    </script>
@endsection
</x-tenant-layout>
