<x-tenant-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ $requisition ? __('Process MRR from Requisition') . ' (' . $requisition->requisition_no . ')' : __('Create Direct MRR') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <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.stock.mrr.store') }}" id="mrr-form">
                        @csrf
                        @if($requisition)
                            <input type="hidden" name="purchase_requisition_id" value="{{ $requisition->id }}">
                            <input type="hidden" name="supplier_id" value="{{ $requisition->supplier_id }}">
                        @endif

                        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                            <div>
                                <x-input-label for="mrr_no" :value="__('MRR Number')" />
                                <x-text-input id="mrr_no" name="mrr_no" type="text" class="mt-1 block w-full" :value="old('mrr_no', 'MRR-' . date('YmdHis'))" required />
                                <x-input-error class="mt-2" :messages="$errors->get('mrr_no')" />
                            </div>

                            <div>
                                <x-input-label for="challan_no" :value="__('Challan Number')" />
                                <x-text-input id="challan_no" name="challan_no" type="text" class="mt-1 block w-full" :value="old('challan_no')" required />
                                <x-input-error class="mt-2" :messages="$errors->get('challan_no')" />
                            </div>

                            <div>
                                <x-input-label for="supplier_id_display" :value="__('Supplier')" />
                                @if($requisition)
                                    <div class="mt-2 text-sm font-semibold text-gray-900">{{ $requisition->supplier->name }}</div>
                                @else
                                    <select name="supplier_id" id="supplier_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm select2" required>
                                        <option value="">Select Supplier</option>
                                        @foreach($suppliers as $supplier)
                                            <option value="{{ $supplier->id }}" {{ old('supplier_id') == $supplier->id ? 'selected' : '' }}>
                                                {{ $supplier->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    <x-input-error class="mt-2" :messages="$errors->get('supplier_id')" />
                                @endif
                            </div>
                        </div>

                        <div class="mb-6">
                            <h3 class="text-lg font-bold text-gray-900 mb-2">Product List</h3>
                            <div class="overflow-x-auto">
                                <table class="min-w-full divide-y divide-gray-200 border" id="items-table">
                                    <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">Unit Cost</th>
                                            <th class="px-4 py-2 text-center text-xs font-medium text-gray-500 uppercase">Actual 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 text-center text-xs font-medium text-gray-500 uppercase">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-gray-200" id="items-body">
                                        @if($requisition)
                                            @foreach($requisition->items as $index => $item)
                                                <tr class="item-row">
                                                    <td class="px-4 py-2 text-sm text-gray-900">
                                                        <input type="hidden" name="items[{{ $index }}][variant_id]" value="{{ $item->product_variant_id }}">
                                                        {{ $item->variant->product->name }} 
                                                        @if($item->variant->name !== $item->variant->product->name)
                                                            - {{ $item->variant->name }}
                                                        @endif
                                                    </td>
                                                    <td class="px-4 py-2 text-right">
                                                        <input type="number" step="0.01" name="items[{{ $index }}][unit_cost]" value="{{ $item->cost_price }}" class="w-24 text-right border-gray-300 rounded-md text-sm p-1 unit-cost" required>
                                                    </td>
                                                    <td class="px-4 py-2 text-center">
                                                        <input type="number" step="0.01" name="items[{{ $index }}][quantity]" value="{{ $item->quantity }}" class="w-24 text-center border-gray-300 rounded-md text-sm p-1 quantity" required>
                                                    </td>
                                                    <td class="px-4 py-2 text-right text-sm font-medium row-total">
                                                        {{ number_format($item->total, 2) }}
                                                    </td>
                                                    <td class="px-4 py-2 text-center">
                                                        <button type="button" class="text-red-600 hover:text-red-900 remove-row">Remove</button>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        @else
                                            <tr class="item-row">
                                                <td class="px-4 py-2">
                                                    <select name="items[0][variant_id]" class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm select2-product" required>
                                                        <option value="">Select Product</option>
                                                        @foreach($products as $variant)
                                                            <option value="{{ $variant->id }}" data-cost="{{ $variant->cost }}">
                                                                {{ $variant->product->name }} - {{ $variant->name }} ({{ $variant->sku }})
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </td>
                                                <td class="px-4 py-2 text-right">
                                                    <input type="number" step="0.01" name="items[0][unit_cost]" value="0" class="w-24 text-right border-gray-300 rounded-md text-sm p-1 unit-cost" required>
                                                </td>
                                                <td class="px-4 py-2 text-center">
                                                    <input type="number" step="0.01" name="items[0][quantity]" value="1" class="w-24 text-center border-gray-300 rounded-md text-sm p-1 quantity" required>
                                                </td>
                                                <td class="px-4 py-2 text-right text-sm font-medium row-total">
                                                    0.00
                                                </td>
                                                <td class="px-4 py-2 text-center">
                                                    <button type="button" class="text-red-600 hover:text-red-900 remove-row">Remove</button>
                                                </td>
                                            </tr>
                                        @endif
                                    </tbody>
                                    <tfoot>
                                        <tr class="bg-gray-50">
                                            <td colspan="3" class="px-4 py-2 text-right font-bold">Grand Total:</td>
                                            <td class="px-4 py-2 text-right font-bold" id="grand-total">0.00</td>
                                            <td></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                            @if(!$requisition)
                                <div class="mt-4">
                                    <button type="button" id="add-item-btn" class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:ring ring-gray-300 disabled:opacity-25 transition ease-in-out duration-150">
                                        Add Another Product
                                    </button>
                                </div>
                            @endif
                        </div>

                        <div class="mb-6">
                            <x-input-label for="notes" :value="__('Notes (Optional)')" />
                            <textarea id="notes" name="notes" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" rows="3">{{ old('notes') }}</textarea>
                            <x-input-error class="mt-2" :messages="$errors->get('notes')" />
                        </div>

                        <div class="flex items-center justify-end">
                            <a href="{{ route('tenant.stock.mrr.index') }}" class="text-gray-600 hover:text-gray-900 mr-4">Cancel</a>
                            <x-primary-button>
                                {{ __('Complete MRR & Update Stock') }}
                            </x-primary-button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        $(document).ready(function() {
            let itemIndex = {{ $requisition ? $requisition->items->count() : 1 }};

            function initSelect2(element) {
                $(element).select2({
                    width: '100%'
                });
            }

            initSelect2('.select2');
            initSelect2('.select2-product');

            function calculateTotals() {
                let grandTotal = 0;
                $('.item-row').each(function() {
                    const cost = parseFloat($(this).find('.unit-cost').val()) || 0;
                    const qty = parseFloat($(this).find('.quantity').val()) || 0;
                    const total = cost * qty;
                    $(this).find('.row-total').text(total.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
                    grandTotal += total;
                });
                $('#grand-total').text(grandTotal.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
            }

            $(document).on('input', '.unit-cost, .quantity', function() {
                calculateTotals();
            });

            $(document).on('change', '.select2-product', function() {
                const cost = $(this).find(':selected').data('cost') || 0;
                $(this).closest('tr').find('.unit-cost').val(cost);
                calculateTotals();
            });

            $('#add-item-btn').click(function() {
                const newRow = `
                    <tr class="item-row">
                        <td class="px-4 py-2">
                            <select name="items[${itemIndex}][variant_id]" class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm select2-product" required>
                                <option value="">Select Product</option>
                                @foreach($products as $variant)
                                    <option value="{{ $variant->id }}" data-cost="{{ $variant->cost }}">
                                        {{ $variant->product->name }} - {{ $variant->name }} ({{ $variant->sku }})
                                    </option>
                                @endforeach
                            </select>
                        </td>
                        <td class="px-4 py-2 text-right">
                            <input type="number" step="0.01" name="items[${itemIndex}][unit_cost]" value="0" class="w-24 text-right border-gray-300 rounded-md text-sm p-1 unit-cost" required>
                        </td>
                        <td class="px-4 py-2 text-center">
                            <input type="number" step="0.01" name="items[${itemIndex}][quantity]" value="1" class="w-24 text-center border-gray-300 rounded-md text-sm p-1 quantity" required>
                        </td>
                        <td class="px-4 py-2 text-right text-sm font-medium row-total">
                            0.00
                        </td>
                        <td class="px-4 py-2 text-center">
                            <button type="button" class="text-red-600 hover:text-red-900 remove-row">Remove</button>
                        </td>
                    </tr>
                `;
                $('#items-body').append(newRow);
                initSelect2($(`#items-body tr:last .select2-product`));
                itemIndex++;
                calculateTotals();
            });

            $(document).on('click', '.remove-row', function() {
                if ($('.item-row').length > 1) {
                    $(this).closest('tr').remove();
                    calculateTotals();
                } else {
                    alert('At least one item is required.');
                }
            });

            calculateTotals();
        });
    </script>
    @endpush
</x-tenant-layout>
