@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-6xl mx-auto">
        <!-- Page Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">إنشاء إشعار استقبال مواد (GRN)</h1>
                    <p class="text-gray-600">سجل المواد المستلمة من طلب الشراء</p>
                </div>
                <a href="{{ route('goods-receipt-notes.index') }}" class="inline-flex items-center px-6 py-3 bg-gradient-to-r from-gray-600 to-gray-700 text-white font-semibold rounded-lg hover:from-gray-700 hover:to-gray-800 transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105">
                    <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>

        <!-- Main Form -->
        <form action="{{ route('goods-receipt-notes.store') }}" method="POST" enctype="multipart/form-data" id="grnForm" class="space-y-6">
            @csrf

            <!-- Purchase Order 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">
                    <h2 class="text-xl font-semibold">اختيار طلب الشراء</h2>
                </div>
                <div class="p-6 space-y-4">
                    @if($purchaseOrders->isEmpty())
                    <div class="bg-yellow-50 border-l-4 border-yellow-500 p-4 rounded-r-lg">
                        <div class="flex">
                            <div class="flex-shrink-0">
                                <i class="fas fa-info-circle text-yellow-500 text-xl"></i>
                            </div>
                            <div class="mr-3">
                                <p class="text-yellow-700 font-medium">لا توجد طلبات شراء متاحة للاستقبال</p>
                                <p class="text-yellow-600 text-sm mt-1">يجب أن يكون طلب الشراء في حالة "مرسل" أو "مقبول" أو "استقبال جزئي"</p>
                            </div>
                        </div>
                    </div>
                    @else
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <label for="purchase_order_id" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-shopping-bag text-blue-600 ml-1"></i>
                                طلب الشراء *
                            </label>
                            <select id="purchase_order_id" name="purchase_order_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition" onchange="loadPurchaseOrderItems(this.value)">
                                <option value="">-- اختر طلب شراء --</option>
                                @foreach($purchaseOrders as $po)
                                <option value="{{ $po->id }}" data-supplier="{{ $po->supplier->name }}" data-po-number="{{ $po->po_number }}" {{ isset($purchaseOrder) && $purchaseOrder->id == $po->id ? 'selected' : '' }}>
                                    {{ $po->po_number }} - {{ $po->supplier->name }} ({{ $po->items->count() }} أصناف)
                                </option>
                                @endforeach
                            </select>
                            @error('purchase_order_id')
                            <p class="text-red-600 text-sm mt-1"><i class="fas fa-exclamation-circle ml-1"></i>{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="warehouse_id" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-warehouse text-blue-600 ml-1"></i>
                                المخزن *
                            </label>
                            <select id="warehouse_id" name="warehouse_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition">
                                <option value="">-- اختر مخزن --</option>
                                @foreach($warehouses as $warehouse)
                                <option value="{{ $warehouse->id }}" {{ old('warehouse_id') == $warehouse->id ? 'selected' : '' }}>
                                    {{ $warehouse->name }}
                                </option>
                                @endforeach
                            </select>
                            @error('warehouse_id')
                            <p class="text-red-600 text-sm mt-1"><i class="fas fa-exclamation-circle ml-1"></i>{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label for="receipt_date" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-calendar text-blue-600 ml-1"></i>
                                تاريخ الاستقبال *
                            </label>
                            <input type="date" id="receipt_date" name="receipt_date" value="{{ old('receipt_date', date('Y-m-d')) }}" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition">
                            @error('receipt_date')
                            <p class="text-red-600 text-sm mt-1"><i class="fas fa-exclamation-circle ml-1"></i>{{ $message }}</p>
                            @enderror
                        </div>
                    </div>

                    <!-- Supplier Info Display -->
                    <div id="supplierInfo" class="hidden pt-4 border-t border-gray-200">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="bg-blue-50 rounded-lg p-4">
                                <p class="text-sm text-gray-600">المورد</p>
                                <p id="supplierName" class="text-lg font-semibold text-gray-900"></p>
                            </div>
                            <div class="bg-blue-50 rounded-lg p-4">
                                <p class="text-sm text-gray-600">رقم طلب الشراء</p>
                                <p id="poNumber" class="text-lg font-semibold text-gray-900"></p>
                            </div>
                        </div>
                    </div>
                    @endif
                </div>
            </div>

            <!-- Quality Check 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">
                    <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 class="flex items-center">
                            <input type="checkbox" id="quality_check_passed" name="quality_check_passed" value="1" class="w-4 h-4 text-green-600 border-gray-300 rounded focus:ring-2 focus:ring-green-500 transition">
                            <label for="quality_check_passed" class="ml-2 block text-sm font-medium text-gray-700">
                                <i class="fas fa-check-circle text-green-600 ml-1"></i>
                                نجح فحص الجودة
                            </label>
                        </div>
                    </div>

                    <div>
                        <label for="quality_check_notes" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-sticky-note text-blue-600 ml-1"></i>
                            ملاحظات فحص الجودة
                        </label>
                        <textarea id="quality_check_notes" name="quality_check_notes" rows="3" placeholder="أدخل أي ملاحظات عن فحص الجودة..." class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition resize-none">{{ old('quality_check_notes') }}</textarea>
                        @error('quality_check_notes')
                        <p class="text-red-600 text-sm mt-1"><i class="fas fa-exclamation-circle ml-1"></i>{{ $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">
                    <h2 class="text-xl font-semibold">
                        <i class="fas fa-boxes ml-1"></i>
                        الأصناف
                    </h2>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-4 py-3 text-right text-sm font-semibold text-gray-700">اسم الصنف</th>
                                <th class="px-4 py-3 text-center text-sm font-semibold text-gray-700">الكمية المطلوبة</th>
                                <th class="px-4 py-3 text-center text-sm font-semibold text-gray-700">الكمية المستلمة</th>
                                <th class="px-4 py-3 text-center text-sm font-semibold text-gray-700">الكمية المقبولة</th>
                                <th class="px-4 py-3 text-center text-sm font-semibold text-gray-700">الكمية المرفوضة</th>
                                <th class="px-4 py-3 text-right text-sm font-semibold text-gray-700">سبب الرفض</th>
                            </tr>
                        </thead>
                        <tbody id="itemsTableBody" class="divide-y divide-gray-200">
                            <tr>
                                <td colspan="6" class="px-6 py-12 text-center">
                                    <div class="flex flex-col items-center justify-center">
                                        <i class="fas fa-inbox text-gray-400 text-4xl mb-3"></i>
                                        <p class="text-gray-600 font-medium">اختر طلب شراء لعرض الأصناف</p>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                @error('items')
                <div class="px-6 py-4 bg-red-50 border-t border-red-200">
                    <p class="text-red-600 text-sm"><i class="fas fa-exclamation-circle ml-1"></i>{{ $message }}</p>
                </div>
                @enderror
            </div>

            <!-- Additional Notes 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">
                    <h2 class="text-xl font-semibold">معلومات إضافية</h2>
                </div>
                <div class="p-6 space-y-4">
                    <div>
                        <label for="notes" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-comment-dots text-blue-600 ml-1"></i>
                            ملاحظات عامة
                        </label>
                        <textarea id="notes" name="notes" rows="4" placeholder="أدخل أي ملاحظات عامة عن الاستقبال..." class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition resize-none">{{ old('notes') }}</textarea>
                        @error('notes')
                        <p class="text-red-600 text-sm mt-1"><i class="fas fa-exclamation-circle ml-1"></i>{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label for="attachment" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-paperclip text-blue-600 ml-1"></i>
                            المرفقات
                        </label>
                        <div class="flex items-center justify-center w-full">
                            <label for="attachment" class="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 transition">
                                <div class="flex flex-col items-center justify-center pt-5 pb-6">
                                    <i class="fas fa-cloud-upload-alt text-gray-400 text-3xl mb-2"></i>
                                    <p class="text-sm text-gray-600"><span class="font-semibold">انقر لتحميل</span> أو اسحب وأفلت</p>
                                    <p class="text-xs text-gray-500 mt-1">PDF, DOC, DOCX, JPG, PNG (أقصى 10MB)</p>
                                </div>
                                <input type="file" id="attachment" name="attachment" class="hidden" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
                            </label>
                        </div>
                        <p id="attachmentName" class="text-sm text-green-600 mt-2 hidden"><i class="fas fa-check-circle ml-1"></i></p>
                        @error('attachment')
                        <p class="text-red-600 text-sm mt-1"><i class="fas fa-exclamation-circle ml-1"></i>{{ $message }}</p>
                        @enderror
                    </div>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="flex items-center justify-between gap-4">
                <a href="{{ route('goods-receipt-notes.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 shadow-lg hover:shadow-xl transform hover:scale-105">
                    <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-green-600 to-green-700 text-white font-semibold rounded-lg hover:from-green-700 hover:to-green-800 transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105">
                    <i class="fas fa-save ml-2"></i>
                    <span>حفظ الاستقبال</span>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
// Store purchase orders data in a global variable
const purchaseOrdersData = {!! json_encode($purchaseOrders->map(fn($po) => [
    'id' => $po->id,
    'supplier' => $po->supplier->name,
    'po_number' => $po->po_number,
    'items' => $po->items->map(fn($item) => [
        'id' => $item->id,
        'name' => $item->item->name ?? 'Unknown Item',
        'quantity_ordered' => $item->quantity_ordered,
        'unit' => $item->unit->name ?? '',
    ])->toArray(),
])->toArray()) !!};

function loadPurchaseOrderItems(poId) {
    const itemsTableBody = document.getElementById('itemsTableBody');
    const supplierInfo = document.getElementById('supplierInfo');

    if (!poId) {
        itemsTableBody.innerHTML = `
            <tr>
                <td colspan="6" class="px-6 py-12 text-center">
                    <div class="flex flex-col items-center justify-center">
                        <i class="fas fa-inbox text-gray-400 text-4xl mb-3"></i>
                        <p class="text-gray-600 font-medium">اختر طلب شراء لعرض الأصناف</p>
                    </div>
                </td>
            </tr>
        `;
        supplierInfo.classList.add('hidden');
        return;
    }

    const po = purchaseOrdersData.find(p => p.id == poId);
    if (!po) return;

    // Update supplier info
    document.getElementById('supplierName').textContent = po.supplier;
    document.getElementById('poNumber').textContent = po.po_number;
    supplierInfo.classList.remove('hidden');

    // Build table rows
    let html = '';
    if (po.items.length === 0) {
        html = `
            <tr>
                <td colspan="6" class="px-6 py-12 text-center">
                    <p class="text-gray-500">لا توجد أصناف في هذا الطلب</p>
                </td>
            </tr>
        `;
    } else {
        po.items.forEach((item, index) => {
            html += `
                <tr class="hover:bg-blue-50 transition-colors">
                    <td class="px-4 py-3 text-right text-sm text-gray-900">
                        <div class="font-semibold">${item.name}</div>
                        <div class="text-xs text-gray-500">${item.unit}</div>
                    </td>
                    <td class="px-4 py-3 text-center text-sm text-gray-900 font-semibold">
                        ${parseFloat(item.quantity_ordered).toFixed(2)}
                    </td>
                    <td class="px-4 py-3">
                        <input type="hidden" name="items[${index}][purchase_order_item_id]" value="${item.id}">
                        <input type="number" name="items[${index}][quantity_received]" step="0.01" min="0" value="0" class="w-full px-2 py-1 border border-gray-300 rounded text-center text-sm" placeholder="0" required>
                    </td>
                    <td class="px-4 py-3">
                        <input type="number" name="items[${index}][quantity_accepted]" step="0.01" min="0" value="0" class="w-full px-2 py-1 border border-gray-300 rounded text-center text-sm" placeholder="0" required>
                    </td>
                    <td class="px-4 py-3">
                        <input type="number" name="items[${index}][quantity_rejected]" step="0.01" min="0" value="0" class="w-full px-2 py-1 border border-gray-300 rounded text-center text-sm" placeholder="0">
                    </td>
                    <td class="px-4 py-3 text-right">
                        <input type="text" name="items[${index}][rejection_reason]" class="w-full px-2 py-1 border border-gray-300 rounded text-sm" placeholder="السبب...">
                    </td>
                </tr>
            `;
        });
    }
    itemsTableBody.innerHTML = html;
}

@isset($purchaseOrder)
document.addEventListener('DOMContentLoaded', function() {
    loadPurchaseOrderItems({{ $purchaseOrder->id }});
});
@endisset

// File upload handling
document.getElementById('attachment')?.addEventListener('change', function(e) {
    const fileName = e.target.files[0]?.name;
    const attachmentName = document.getElementById('attachmentName');
    if (fileName) {
        attachmentName.textContent = `✓ تم تحميل: ${fileName}`;
        attachmentName.classList.remove('hidden');
    } else {
        attachmentName.classList.add('hidden');
    }
});
</script>
@endsection
