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

    <div class="py-12" x-data="returnApp()">
        <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">
                    
                    @if($sale)
                        <!-- Invoice Header -->
                        <div class="flex justify-between items-start mb-6 pb-6 border-b">
                            <div>
                                <h3 class="text-lg font-bold text-gray-900">Invoice: {{ $sale->invoice_no }}</h3>
                                <p class="text-sm text-gray-500">Date: {{ $sale->created_at->format('Y-m-d H:i') }}</p>
                                <p class="text-sm text-gray-500">Customer: {{ $sale->customer->name ?? 'Walk-in' }}</p>
                            </div>
                            <div class="text-right">
                                <p class="text-sm text-gray-500">Total Amount</p>
                                <p class="text-2xl font-bold text-gray-900">${{ number_format($sale->total, 2) }}</p>
                            </div>
                        </div>

                        <!-- Return Form -->
                        <form action="{{ route('tenant.returns.store') }}" method="POST">
                            @csrf
                            <input type="hidden" name="sale_id" value="{{ $sale->id }}">
                            
                            <h4 class="font-medium text-gray-700 mb-4">Select Items to Return</h4>
                            
                            <table class="min-w-full divide-y divide-gray-200 mb-6">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Item</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Sold Qty</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Sold Price</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Return Qty</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Refund Amount</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    @foreach($sale->items as $index => $item)
                                        <tr x-data="{ 
                                            qty: 0, 
                                            maxQty: {{ $item->quantity }}, 
                                            price: {{ $item->price }},
                                            updateTotal() {
                                                this.qty = Math.min(Math.max(0, this.qty), this.maxQty);
                                                $dispatch('update-refund');
                                            }
                                        }">
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                {{ $item->variant->product->name }} - {{ $item->variant->name }}
                                                @if($item->productUnit)
                                                    <span class="text-xs text-gray-500">({{ $item->productUnit->name }})</span>
                                                @endif
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-right text-gray-500">
                                                {{ $item->quantity + 0 }}
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-right text-gray-500">
                                                ${{ number_format($item->price, 2) }}
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap text-right">
                                                <div class="flex items-center justify-end gap-2">
                                                    <input type="hidden" name="items[{{ $index }}][variant_id]" value="{{ $item->variant_id }}">
                                                    <input type="hidden" name="items[{{ $index }}][unit_price]" value="{{ $item->price }}">
                                                    
                                                    <input type="number" 
                                                           name="items[{{ $index }}][quantity]" 
                                                           x-model="qty" 
                                                           @input="updateTotal()"
                                                           min="0" 
                                                           max="{{ $item->quantity }}" 
                                                           step="0.01"
                                                           class="w-24 rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 text-right">
                                                </div>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-right font-medium text-gray-900">
                                                <span x-text="'$' + (qty * price).toFixed(2)"></span>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                                <tfoot class="bg-gray-50">
                                    <tr>
                                        <td colspan="4" class="px-6 py-4 text-right font-bold text-gray-900">Total Refund:</td>
                                        <td class="px-6 py-4 text-right font-bold text-indigo-600 text-lg">
                                            <span x-text="'$' + totalRefund.toFixed(2)"></span>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>

                            <div class="mb-6">
                                <label class="block text-sm font-medium text-gray-700">Reason / Note</label>
                                <textarea name="note" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"></textarea>
                            </div>

                            <div class="flex justify-end gap-4">
                                <a href="{{ route('tenant.returns.index') }}" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300">Cancel</a>
                                <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700" :disabled="totalRefund <= 0">Process Return</button>
                            </div>
                        </form>
                    @else
                        <div class="text-center py-10">
                            <p class="text-gray-500">Please search for an invoice to process a return.</p>
                            <a href="{{ route('tenant.returns.index') }}" class="mt-4 inline-block text-indigo-600 hover:text-indigo-900">Go Back</a>
                        </div>
                    @endif

                </div>
            </div>
        </div>
    </div>

    @section('scripts')
    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('returnApp', () => ({
                totalRefund: 0,
                
                init() {
                    this.$el.addEventListener('update-refund', () => {
                        this.calculateTotal();
                    });
                },

                calculateTotal() {
                    let total = 0;
                    // Iterate through all rows inputs
                    const rows = this.$el.querySelectorAll('tbody tr');
                    rows.forEach(row => {
                        const qtyInput = row.querySelector('input[type="number"]');
                        const priceInput = row.querySelector('input[name$="[unit_price]"]');
                        
                        if(qtyInput && priceInput) {
                            total += (parseFloat(qtyInput.value) || 0) * (parseFloat(priceInput.value) || 0);
                        }
                    });
                    this.totalRefund = total;
                }
            }));
        });
    </script>
    @endsection
</x-tenant-layout>