@extends('layouts.app')

@section('title', 'تعديل طلب الشراء الداخلي')

@section('content')
<div class="min-h-screen bg-slate-50 py-6 px-4 md:px-8">
    <div class="max-w-7xl mx-auto">
        <!-- Compact Header -->
        <div class="mb-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">تعديل طلب الشراء الداخلي</h1>
                <div class="flex items-center gap-2 mt-1">
                    <span class="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-bold rounded-md border border-blue-200">{{ $purchaseRequisition->requisition_number }}</span>
                    <p class="text-gray-500 text-sm">تحديث بيانات طلب الشراء الحالي</p>
                </div>
            </div>
            <a href="{{ route('purchase-requisitions.index') }}" class="inline-flex items-center px-4 py-2 bg-white text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition-all duration-200 border border-gray-300 shadow-sm">
                <i class="fas fa-arrow-right ml-2 text-xs"></i>
                <span>العودة للمقائمة</span>
            </a>
        </div>

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

        <form action="{{ route('purchase-requisitions.update', $purchaseRequisition) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')

            <!-- Main Info Section -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 mb-6 overflow-hidden">
                <div class="px-5 py-3 bg-gray-50 border-b border-gray-200 flex items-center">
                    <i class="fas fa-info-circle text-blue-600 ml-2"></i>
                    <h2 class="text-base font-bold text-gray-800">معلومات الطلب</h2>
                </div>
                
                <div class="p-6 space-y-6">
                    <!-- Description Field - Full Width for better readability -->
                    <div>
                        <label for="description" class="block text-sm font-bold text-gray-700 mb-1.5 flex items-center">
                            <span>وصف الطلب *</span>
                            <span class="mr-1 text-xs font-normal text-gray-400 font-sans">(الغرض الأساسي من الشراء)</span>
                        </label>
                        <textarea id="description" name="description" rows="2" class="w-full px-4 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all @error('description') border-red-500 @enderror" required placeholder="أدخل وصفاً موجزاً للطلب">{{ old('description', $purchaseRequisition->description) }}</textarea>
                        @error('description')
                        <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 pt-2 border-t border-gray-50">
                        <!-- Right Side fields -->
                        <div class="space-y-4">
                            <div>
                                <label for="cost_center_id" class="block text-sm font-bold text-gray-700 mb-1.5">مركز التكلفة العام</label>
                                <select id="cost_center_id" name="cost_center_id" class="w-full px-4 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all bg-white">
                                    <option value="">اختر مركز تكلفة (اختياري)</option>
                                    @foreach($costCenters as $center)
                                    <option value="{{ $center->id }}" {{ old('cost_center_id', $purchaseRequisition->cost_center_id) == $center->id ? 'selected' : '' }}>{{ $center->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            
                            <div class="bg-blue-50/50 p-4 rounded-xl border border-blue-100 flex items-center justify-around">
                                <div class="text-center">
                                    <span class="block text-[10px] text-gray-400 font-bold uppercase">تاريخ الإنشاء</span>
                                    <span class="text-xs font-bold text-blue-800">{{ $purchaseRequisition->created_at->format('Y-m-d') }}</span>
                                </div>
                                <div class="w-px h-8 bg-blue-200"></div>
                                <div class="text-center">
                                    <span class="block text-[10px] text-gray-400 font-bold uppercase">حالة الطلب</span>
                                    <span class="px-2 py-0.5 bg-yellow-100 text-yellow-700 text-[10px] uppercase font-bold rounded-full border border-yellow-200">مسودة</span>
                                </div>
                            </div>
                        </div>

                        <!-- Left Side fields -->
                        <div class="space-y-4">
                            <div>
                                <label for="notes" class="block text-sm font-bold text-gray-700 mb-1.5">ملاحظات إضافية</label>
                                <textarea id="notes" name="notes" rows="4" class="w-full px-4 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all" placeholder="أدخل أي تفاصيل فنية أو ملاحظات إضافية">{{ old('notes', $purchaseRequisition->notes) }}</textarea>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

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

                <div class="overflow-x-auto">
                    <table class="w-full text-right border-collapse">
                        <thead>
                            <tr class="bg-gray-50/50 text-gray-600 text-xs font-bold uppercase border-b border-gray-200">
                                <th class="px-4 py-3 min-w-[200px]">الصنف *</th>
                                <th class="px-4 py-3 w-32">الكمية *</th>
                                <th class="px-4 py-3 w-40">الوحدة *</th>
                                <th class="px-4 py-3 w-44">السعر التقديري</th>
                                <th class="px-4 py-3">مركز التكلفة</th>
                                <th class="px-4 py-3 w-16 text-center">حذف</th>
                            </tr>
                        </thead>
                        <tbody id="itemsContainer" class="divide-y divide-gray-100">
                            @forelse($purchaseRequisition->items as $index => $item)
                            <tr class="itemRow hover:bg-gray-50/30 transition-colors">
                                <td class="px-3 py-2">
                                    <select name="items[{{ $index }}][item_id]" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-500 focus:border-blue-500 bg-white" required>
                                        <option value="">اختر صنف</option>
                                        @foreach($items as $it)
                                        <option value="{{ $it->id }}" {{ $item->item_id == $it->id ? 'selected' : '' }}>{{ $it->name }}</option>
                                        @endforeach
                                    </select>
                                </td>
                                <td class="px-3 py-2">
                                    <input type="number" name="items[{{ $index }}][quantity]" step="0.01" min="0.01" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-500 focus:border-blue-500" value="{{ $item->quantity }}" required placeholder="0.00">
                                </td>
                                <td class="px-3 py-2">
                                    <select name="items[{{ $index }}][unit_id]" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-500 focus:border-blue-500 bg-white" required>
                                        <option value="">اختر وحدة</option>
                                        @foreach($units as $unit)
                                        <option value="{{ $unit->id }}" {{ $item->unit_id == $unit->id ? 'selected' : '' }}>{{ $unit->name }}</option>
                                        @endforeach
                                    </select>
                                </td>
                                <td class="px-3 py-2">
                                    <div class="relative">
                                        <input type="number" name="items[{{ $index }}][estimated_unit_price]" step="0.01" min="0" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-500 focus:border-blue-500 pr-8" value="{{ $item->estimated_unit_price }}" placeholder="0.00">
                                        <span class="absolute left-3 top-1.5 text-gray-400 text-xs">ر.س</span>
                                    </div>
                                </td>
                                <td class="px-3 py-2">
                                    <select name="items[{{ $index }}][cost_center_id]" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-500 focus:border-blue-500 bg-white">
                                        <option value="">مركز التكلفة</option>
                                        @foreach($costCenters as $center)
                                        <option value="{{ $center->id }}" {{ $item->cost_center_id == $center->id ? 'selected' : '' }}>{{ $center->name }}</option>
                                        @endforeach
                                    </select>
                                </td>
                                <td class="px-3 py-2 text-center">
                                    <button type="button" class="text-red-400 hover:text-red-600 transition-colors p-2" onclick="removeItemRow(this)">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </td>
                            </tr>
                            @empty
                            <tr class="itemRow hover:bg-gray-50/30 transition-colors">
                                <td colspan="6" class="px-3 py-6 text-center text-gray-500">لا توجد أصناف حالياً</td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
                
                <!-- Footer for items section -->
                <div class="px-5 py-4 bg-gray-50 border-t border-gray-200 flex justify-between items-center text-xs text-gray-500">
                    <p>* جميع الحقول المؤشرة بالنجمة مطلوبة</p>
                    <p>إجمالي الأصناف: <span id="itemsCount" class="font-bold text-blue-600">0</span></p>
                </div>
            </div>

            <!-- Submission Actions -->
            <div class="mt-8 flex items-center justify-end gap-4">
                <a href="{{ route('purchase-requisitions.show', $purchaseRequisition) }}" class="px-6 py-2.5 text-gray-700 font-bold hover:bg-gray-200 rounded-xl transition-all">
                    إلغاء
                </a>
                <button type="submit" class="inline-flex items-center px-8 py-2.5 bg-blue-600 text-white font-bold rounded-xl hover:bg-blue-700 transition-all shadow-md hover:shadow-lg">
                    <i class="fas fa-save ml-2"></i>
                    <span>حفظ التغييرات</span>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // Update items count
    function updateItemsCount() {
        const count = document.querySelectorAll('.itemRow').length;
        document.getElementById('itemsCount').textContent = count;
    }

    function addItemRow() {
        const container = document.getElementById('itemsContainer');
        const rowCount = container.querySelectorAll('.itemRow').length;
        
        // Remove empty state if exists
        const emptyRow = container.querySelector('td[colspan="6"]')?.parentElement;
        if (emptyRow) emptyRow.remove();

        const newRow = document.createElement('tr');
        newRow.className = 'itemRow hover:bg-gray-50/30 transition-colors';
        newRow.innerHTML = `
            <td class="px-3 py-2">
                <select name="items[${rowCount}][item_id]" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-500 focus:border-blue-500 bg-white" required>
                    <option value="">اختر صنف</option>
                    @foreach($items as $it)
                    <option value="{{ $it->id }}">{{ $it->name }}</option>
                    @endforeach
                </select>
            </td>
            <td class="px-3 py-2">
                <input type="number" name="items[${rowCount}][quantity]" step="0.01" min="0.01" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-500 focus:border-blue-500" required placeholder="0.00">
            </td>
            <td class="px-3 py-2">
                <select name="items[${rowCount}][unit_id]" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-500 focus:border-blue-500 bg-white" required>
                    <option value="">اختر وحدة</option>
                    @foreach($units as $unit)
                    <option value="{{ $unit->id }}">{{ $unit->name }}</option>
                    @endforeach
                </select>
            </td>
            <td class="px-3 py-2">
                <div class="relative">
                    <input type="number" name="items[${rowCount}][estimated_unit_price]" step="0.01" min="0" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-500 focus:border-blue-500 pr-8" placeholder="0.00">
                    <span class="absolute left-3 top-1.5 text-gray-400 text-xs">ر.س</span>
                </div>
            </td>
            <td class="px-3 py-2">
                <select name="items[${rowCount}][cost_center_id]" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-500 focus:border-blue-500 bg-white">
                    <option value="">مركز التكلفة</option>
                    @foreach($costCenters as $center)
                    <option value="{{ $center->id }}">{{ $center->name }}</option>
                    @endforeach
                </select>
            </td>
            <td class="px-3 py-2 text-center">
                <button type="button" class="text-red-400 hover:text-red-600 transition-colors p-2" onclick="removeItemRow(this)">
                    <i class="fas fa-trash-alt"></i>
                </button>
            </td>
        `;
        
        container.appendChild(newRow);
        updateItemsCount();
    }

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

    // Initialize count
    document.addEventListener('DOMContentLoaded', function() {
        updateItemsCount();
    });
</script>
@endsection
