@extends('layouts.app')

@section('title', 'إنشاء أمر شراء جديد')

@section('content')
<div class="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 py-8 px-4 md:px-8">
    <div class="max-w-5xl mx-auto">
        <div class="mb-8">
            @isset($purchaseRequisition)
            <div class="bg-blue-50 border-r-4 border-blue-500 p-4 mb-6 rounded-l-lg shadow-sm">
                <div class="flex items-start gap-3">
                    <i class="fas fa-info-circle text-blue-500 text-lg mt-0.5"></i>
                    <div>
                        <p class="text-blue-800 font-bold text-sm">تحويل طلب الشراء الداخلي إلى أمر شراء</p>
                        <p class="text-blue-700 text-xs mt-1">تم تعبئة البيانات من طلب الشراء الداخلي رقم <strong>{{ $purchaseRequisition->requisition_number }}</strong>. يرجى اختيار المورد وتاريخ التسليم ثم مراجعة الأصناف قبل الحفظ.</p>
                    </div>
                </div>
            </div>
            @endisset
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">إنشاء أمر شراء جديد</h1>
                    <p class="text-gray-600">{{ isset($purchaseRequisition) ? 'تحويل طلب الشراء الداخلي ' . $purchaseRequisition->requisition_number . ' إلى أمر شراء' : 'أضف أصناف جديدة لأمر شراء' }}</p>
                </div>
                <a href="{{ route('purchase-orders.index') }}" class="inline-flex items-center px-6 py-3 bg-gray-600 text-white font-semibold rounded-lg hover:bg-gray-700 transition-all duration-200">
                    <i class="fas fa-arrow-right ml-2"></i>
                    <span>العودة</span>
                </a>
            </div>

            @if ($errors->any())
            <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-6 rounded-r-lg">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-circle text-red-500 text-xl"></i>
                    </div>
                    <div class="mr-3">
                        <p class="text-red-700 font-medium">حدث خطأ في البيانات المدخلة:</p>
                        <ul class="mt-2 list-disc list-inside text-red-600 text-sm">
                            @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
            @endif
        </div>

        <form action="{{ route('purchase-orders.store') }}" method="POST" enctype="multipart/form-data" class="space-y-6">
            @csrf

            <!-- Basic Information -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200">
                <div class="px-6 py-4 bg-gradient-to-r from-gray-800 to-gray-900 text-white">
                    <h2 class="text-xl font-semibold">معلومات الطلب</h2>
                </div>
                <div class="p-6 space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="supplier_id" class="block text-sm font-medium text-gray-700 mb-2">المورد *</label>
                            <select id="supplier_id" name="supplier_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent @error('supplier_id') border-red-500 @enderror" required>
                                <option value="">اختر مورد</option>
                                @foreach($suppliers as $supplier)
                                <option value="{{ $supplier->id }}" {{ old('supplier_id') == $supplier->id ? 'selected' : '' }}>{{ $supplier->name }}</option>
                                @endforeach
                            </select>
                            @error('supplier_id')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <div></div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="requisition_id" class="block text-sm font-medium text-gray-700 mb-2">طلب شراء داخلي (اختياري)</label>
                            <select id="requisition_id" name="requisition_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                <option value="">اختر طلب شراء داخلي (اختياري)</option>
                                @foreach($requisitions as $requisition)
                                <option value="{{ $requisition->id }}" {{ (old('requisition_id') == $requisition->id || (isset($purchaseRequisition) && $purchaseRequisition->id == $requisition->id)) ? 'selected' : '' }}>{{ $requisition->requisition_number }}</option>
                                @endforeach
                            </select>
                            @error('requisition_id')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <div></div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="po_date" class="block text-sm font-medium text-gray-700 mb-2">تاريخ الطلب *</label>
                            <input type="date" id="po_date" name="po_date" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent @error('po_date') border-red-500 @enderror" value="{{ old('po_date', now()->format('Y-m-d')) }}" required>
                            @error('po_date')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="delivery_date" class="block text-sm font-medium text-gray-700 mb-2">تاريخ التسليم *</label>
                            <input type="date" id="delivery_date" name="delivery_date" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent @error('delivery_date') border-red-500 @enderror" value="{{ old('delivery_date') }}" required>
                            @error('delivery_date')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                            @enderror
                        </div>
                    </div>

                    <div>
                        <label for="notes" class="block text-sm font-medium text-gray-700 mb-2">ملاحظات (اختيارية)</label>
                        <textarea id="notes" name="notes" rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="أضف أي ملاحظات إضافية">{{ old('notes', isset($purchaseRequisition) ? $purchaseRequisition->description . ($purchaseRequisition->notes ? "\n" . $purchaseRequisition->notes : '') : '') }}</textarea>
                        @error('notes')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="attachment" class="block text-sm font-medium text-gray-700 mb-2">مرفق (اختياري)</label>
                        <input type="file" id="attachment" name="attachment" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
                        @error('attachment')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>
                </div>
            </div>

            <!-- Items Section -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200">
                <div class="px-6 py-4 bg-gradient-to-r from-gray-800 to-gray-900 text-white flex justify-between items-center">
                    <h2 class="text-xl font-semibold">الأصناف المطلوبة</h2>
                    <button type="button" class="inline-flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-all" onclick="addItemRow()">
                        <i class="fas fa-plus ml-2"></i>
                        <span>إضافة صنف</span>
                    </button>
                </div>

                <div class="p-6">
                    <div id="itemsContainer" class="space-y-4">
                        @php
                            if (old('items')) {
                                $prefillItems = old('items');
                                $prefillSource = 'old';
                            } elseif (isset($purchaseRequisition) && $purchaseRequisition->items->count() > 0) {
                                $prefillItems = $purchaseRequisition->items->map(fn($i) => [
                                    'item_id' => $i->item_id,
                                    'quantity_ordered' => $i->quantity,
                                    'unit_id' => $i->unit_id,
                                    'unit_price' => $i->estimated_unit_price ?? 0,
                                    'cost_center_id' => $i->cost_center_id,
                                ])->toArray();
                                $prefillSource = 'requisition';
                            } else {
                                $prefillItems = [[]];
                                $prefillSource = 'empty';
                            }
                        @endphp
                        @foreach($prefillItems as $index => $item)
                        <div class="itemRow border border-gray-300 rounded-lg p-4 {{ $prefillSource === 'requisition' ? 'border-blue-200 bg-blue-50/30' : '' }}">
                            @if($prefillSource === 'requisition')
                            <div class="flex items-center gap-1 mb-3">
                                <i class="fas fa-link text-blue-400 text-xs"></i>
                                <span class="text-xs text-blue-600 font-medium">مستورد من الطلب الداخلي</span>
                            </div>
                            @endif
                            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">الصنف *</label>
                                    <select name="items[{{ $index }}][item_id]" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                                        <option value="">اختر صنف</option>
                                        @foreach($items as $it)
                                        <option value="{{ $it->id }}" {{ ($item['item_id'] ?? '') == $it->id ? 'selected' : '' }}>{{ $it->name }}</option>
                                        @endforeach
                                    </select>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">الكمية المطلوبة *</label>
                                    <input type="number" name="items[{{ $index }}][quantity_ordered]" step="0.01" min="0.01" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" value="{{ $item['quantity_ordered'] ?? '' }}" required>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">الوحدة *</label>
                                    <select name="items[{{ $index }}][unit_id]" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                                        <option value="">اختر وحدة</option>
                                        @foreach($units as $unit)
                                        <option value="{{ $unit->id }}" {{ ($item['unit_id'] ?? '') == $unit->id ? 'selected' : '' }}>{{ $unit->name }}</option>
                                        @endforeach
                                    </select>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">سعر الوحدة *</label>
                                    <input type="number" name="items[{{ $index }}][unit_price]" step="0.01" min="0" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" value="{{ $item['unit_price'] ?? '' }}" required>
                                </div>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">مركز التكلفة (اختياري)</label>
                                    <select name="items[{{ $index }}][cost_center_id]" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                        <option value="">اختر مركز تكلفة</option>
                                        @foreach($costCenters as $center)
                                        <option value="{{ $center->id }}" {{ ($item['cost_center_id'] ?? '') == $center->id ? 'selected' : '' }}>{{ $center->name }}</option>
                                        @endforeach
                                    </select>
                                </div>

                                <div></div>
                            </div>

                            <button type="button" class="mt-4 inline-flex items-center px-4 py-2 bg-red-100 text-red-600 rounded-lg hover:bg-red-200 transition-all" onclick="removeItemRow(this)">
                                <i class="fas fa-trash ml-2"></i>
                                <span>حذف</span>
                            </button>
                        </div>
                        @endforeach
                    </div>
                </div>
            </div>

            <!-- Actions -->
            <div class="flex gap-3 justify-end">
                <a href="{{ route('purchase-orders.index') }}" class="inline-flex items-center px-6 py-3 bg-gray-600 text-white font-semibold rounded-lg hover:bg-gray-700 transition-all duration-200">
                    <i class="fas fa-times ml-2"></i>
                    <span>إلغاء</span>
                </a>
                <button type="submit" class="inline-flex items-center px-6 py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-semibold rounded-lg hover:from-blue-700 hover:to-blue-800 transition-all duration-200 shadow-lg hover:shadow-xl">
                    <i class="fas fa-check ml-2"></i>
                    <span>إنشاء الطلب</span>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function addItemRow() {
    const container = document.getElementById('itemsContainer');
    const rowCount = container.querySelectorAll('.itemRow').length;
    
    const newRow = document.createElement('div');
    newRow.className = 'itemRow border border-gray-300 rounded-lg p-4';
    newRow.innerHTML = `
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">الصنف *</label>
                <select name="items[${rowCount}][item_id]" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                    <option value="">اختر صنف</option>
                    @foreach($items as $it)
                    <option value="{{ $it->id }}">{{ $it->name }}</option>
                    @endforeach
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">الكمية المطلوبة *</label>
                <input type="number" name="items[${rowCount}][quantity_ordered]" step="0.01" min="0.01" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">الوحدة *</label>
                <select name="items[${rowCount}][unit_id]" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                    <option value="">اختر وحدة</option>
                    @foreach($units as $unit)
                    <option value="{{ $unit->id }}">{{ $unit->name }}</option>
                    @endforeach
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">سعر الوحدة *</label>
                <input type="number" name="items[${rowCount}][unit_price]" step="0.01" min="0" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">مركز التكلفة (اختياري)</label>
                <select name="items[${rowCount}][cost_center_id]" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    <option value="">اختر مركز تكلفة</option>
                    @foreach($costCenters as $center)
                    <option value="{{ $center->id }}">{{ $center->name }}</option>
                    @endforeach
                </select>
            </div>

            <div></div>
        </div>

        <button type="button" class="mt-4 inline-flex items-center px-4 py-2 bg-red-100 text-red-600 rounded-lg hover:bg-red-200 transition-all" onclick="removeItemRow(this)">
            <i class="fas fa-trash ml-2"></i>
            <span>حذف</span>
        </button>
    `;
    
    container.appendChild(newRow);
}

function removeItemRow(button) {
    const container = document.getElementById('itemsContainer');
    if (container.querySelectorAll('.itemRow').length > 1) {
        button.closest('.itemRow').remove();
    } else {
        alert('يجب أن يحتوي الطلب على صنف واحد على الأقل');
    }
}
</script>
@endsection
