<x-admin-layout>
    <div class="mb-6">
        <h2 class="text-2xl font-bold text-slate-800">إنشاء أمر شراء جديد</h2>
        <p class="text-slate-500 text-sm">أدخل تفاصيل الطلب والمنتجات</p>
    </div>

    <form action="{{ route('admin.purchase-orders.store') }}" method="POST" x-data="purchaseOrderForm()">
        @csrf

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Order Details -->
            <div class="lg:col-span-1 bg-white rounded-2xl shadow-sm border border-slate-100 p-6 h-fit">
                <h3 class="text-lg font-bold text-slate-800 mb-4 border-b pb-2">بيانات الفاتورة</h3>
                <div class="space-y-4">
                    <!-- Supplier -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-2">المورد <span class="text-red-500">*</span></label>
                        <select name="supplier_id" required class="w-full rounded-xl border-gray-200 focus:border-blue-500 focus:ring-blue-500">
                            <option value="">اختر المورد...</option>
                            @foreach($suppliers as $supplier)
                                <option value="{{ $supplier->id }}" {{ old('supplier_id') == $supplier->id ? 'selected' : '' }}>{{ $supplier->name }}</option>
                            @endforeach
                        </select>
                    </div>

                    <!-- Order Date -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-2">تاريخ الطلب <span class="text-red-500">*</span></label>
                        <input type="date" name="order_date" value="{{ old('order_date', date('Y-m-d')) }}" required class="w-full rounded-xl border-gray-200 focus:border-blue-500 focus:ring-blue-500">
                    </div>

                    <!-- Expected Delivery Date -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-2">تاريخ الاستلام المتوقع</label>
                        <input type="date" name="expected_delivery_date" value="{{ old('expected_delivery_date') }}" class="w-full rounded-xl border-gray-200 focus:border-blue-500 focus:ring-blue-500">
                    </div>

                    <!-- Notes -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-2">ملاحظات</label>
                        <textarea name="notes" rows="3" class="w-full rounded-xl border-gray-200 focus:border-blue-500 focus:ring-blue-500">{{ old('notes') }}</textarea>
                    </div>
                </div>
            </div>

            <!-- Items -->
            <div class="lg:col-span-2 bg-white rounded-2xl shadow-sm border border-slate-100 p-6">
                <div class="flex justify-between items-center mb-4 border-b pb-2">
                    <h3 class="text-lg font-bold text-slate-800">المنتجات</h3>
                    <button type="button" @click="addItem()" class="text-sm bg-blue-50 text-blue-600 px-3 py-1.5 rounded-lg hover:bg-blue-100 transition-colors font-semibold">
                        + إضافة منتج
                    </button>
                </div>

                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr class="bg-gray-50">
                                <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">المنتج</th>
                                <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase w-24">الكمية</th>
                                <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase w-32">السعر (ج.م)</th>
                                <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase w-32">الإجمالي</th>
                                <th class="px-4 py-2 text-center text-xs font-medium text-gray-500 uppercase w-16"></th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <template x-for="(item, index) in items" :key="index">
                                <tr>
                                    <td class="px-4 py-2">
                                        <select :name="'items['+index+'][product_id]'" x-model="item.product_id" @change="updatePrice(index)" required class="w-full text-sm rounded-lg border-gray-200 focus:border-blue-500 focus:ring-blue-500">
                                            <option value="">اختر منتج...</option>
                                            @foreach($products as $product)
                                                <option value="{{ $product->id }}" data-price="{{ $product->price }}">{{ $product->name }}</option>
                                            @endforeach
                                        </select>
                                    </td>
                                    <td class="px-4 py-2">
                                        <input type="number" :name="'items['+index+'][quantity]'" x-model="item.quantity" min="1" required class="w-full text-sm rounded-lg border-gray-200 focus:border-blue-500 focus:ring-blue-500">
                                    </td>
                                    <td class="px-4 py-2">
                                        <input type="number" :name="'items['+index+'][unit_price]'" x-model="item.unit_price" step="0.01" min="0" required class="w-full text-sm rounded-lg border-gray-200 focus:border-blue-500 focus:ring-blue-500">
                                    </td>
                                    <td class="px-4 py-2 font-bold text-slate-700">
                                        <span x-text="(item.quantity * item.unit_price).toFixed(2)"></span>
                                    </td>
                                    <td class="px-4 py-2 text-center">
                                        <button type="button" @click="removeItem(index)" class="text-red-500 hover:text-red-700">
                                            <x-icon name="Trash" class="h-4 w-4" />
                                        </button>
                                    </td>
                                </tr>
                            </template>
                        </tbody>
                        <tfoot>
                            <tr class="bg-gray-50 font-bold">
                                <td colspan="3" class="px-4 py-3 text-right">الإجمالي الكلي:</td>
                                <td class="px-4 py-3 text-blue-600 space-x-1">
                                    <span x-text="calculateTotal()"></span> <span>ج.م</span>
                                </td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <div class="mt-4" x-show="items.length === 0">
                    <div class="text-center py-8 bg-slate-50 rounded-xl border border-dashed border-slate-300">
                        <p class="text-slate-500">لا يوجد منتجات في القائمة. اضغط على "إضافة منتج" للبدء.</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="flex justify-end gap-4 mt-6">
            <a href="{{ route('admin.purchase-orders.index') }}" class="px-6 py-2.5 rounded-xl border border-gray-200 text-gray-700 font-semibold hover:bg-gray-50 transition-colors">إلغاء</a>
            <button type="submit" class="px-6 py-2.5 rounded-xl bg-blue-600 text-white font-semibold hover:bg-blue-700 transition-colors shadow-sm" :disabled="items.length === 0">
                حفظ أمر الشراء
            </button>
        </div>
    </form>

    @push('scripts')
    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('purchaseOrderForm', () => ({
                items: [
                    { product_id: '', quantity: 1, unit_price: 0 }
                ],
                addItem() {
                    this.items.push({ product_id: '', quantity: 1, unit_price: 0 });
                },
                removeItem(index) {
                    this.items.splice(index, 1);
                },
                updatePrice(index) {
                    // Logic to update price based on selected product (requires accessing DOM or mapping)
                    // We'll trust user input for now or use Alpine refs if needed, but pure specific logic needs data access.
                    // Simple hack: listen to change event and get data-price attribute
                    const select = document.querySelector(`select[name='items[${index}][product_id]']`);
                    if(select){
                        const option = select.options[select.selectedIndex];
                        const price = option.getAttribute('data-price');
                        if(price) {
                            this.items[index].unit_price = parseFloat(price);
                        }
                    }
                },
                calculateTotal() {
                    return this.items.reduce((sum, item) => {
                        return sum + (item.quantity * item.unit_price);
                    }, 0).toFixed(2);
                }
            }));
        });
    </script>
    @endpush
</x-admin-layout>
