@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">إنشاء سند تسليم</h1>
                    <p class="text-gray-600">تسجيل تسليم المواد للعميل بناءً على أمر البيع</p>
                </div>
                <a href="{{ route('delivery-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('delivery-notes.store') }}" method="POST" enctype="multipart/form-data" id="dnForm" class="space-y-6">
            @csrf

            <!-- Sales 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($salesOrders->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="sales_order_id" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-shopping-cart text-blue-600 ml-1"></i>
                                أمر البيع *
                            </label>
                            <select id="sales_order_id" name="sales_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="loadSalesOrderItems(this.value)">
                                <option value="">-- اختر أمر بيع --</option>
                                @foreach($salesOrders as $so)
                                <option value="{{ $so->id }}">
                                    {{ $so->so_number }} - {{ $so->customer->name }} ({{ $so->items->count() }} أصناف)
                                </option>
                                @endforeach
                            </select>
                            @error('sales_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="delivery_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="delivery_date" name="delivery_date" value="{{ old('delivery_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('delivery_date')
                            <p class="text-red-600 text-sm mt-1"><i class="fas fa-exclamation-circle ml-1"></i>{{ $message }}</p>
                            @enderror
                        </div>
                    </div>

                    <!-- Customer Info Display -->
                    <div id="customerInfo" 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="customerName" 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="soNumber" class="text-lg font-semibold text-gray-900"></p>
                            </div>
                        </div>
                    </div>
                    @endif
                </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>
                    </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>
                        <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">
                    </div>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="flex items-center justify-between gap-4">
                <a href="{{ route('delivery-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">
                    <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 sales orders data
const salesOrdersData = {!! json_encode($salesOrders->map(fn($so) => [
    'id' => $so->id,
    'customer' => $so->customer->name,
    'so_number' => $so->so_number,
    'items' => $so->items->map(fn($item) => [
        'id' => $item->id,
        'name' => $item->item->name ?? 'صنف غير معروف',
        'quantity_ordered' => $item->quantity_ordered,
        'quantity_delivered_previously' => $item->quantity_delivered ?? 0,
        'remaining_quantity' => $item->quantity_ordered - ($item->quantity_delivered ?? 0)
    ])
])) !!};

function loadSalesOrderItems(soId) {
    const tableBody = document.getElementById('itemsTableBody');
    const customerInfo = document.getElementById('customerInfo');
    const customerName = document.getElementById('customerName');
    const soNumber = document.getElementById('soNumber');

    if (!soId) {
        tableBody.innerHTML = `<tr><td colspan="6" class="px-6 py-12 text-center text-gray-600">اختر أمر بيع لعرض الأصناف</td></tr>`;
        customerInfo.classList.add('hidden');
        return;
    }

    const order = salesOrdersData.find(o => o.id == soId);
    if (!order) return;

    customerName.innerText = order.customer;
    soNumber.innerText = order.so_number;
    customerInfo.classList.remove('hidden');

    let html = '';
    order.items.forEach((item, index) => {
        if (item.remaining_quantity > 0) {
            html += `
                <tr class="hover:bg-gray-50 transition">
                    <td class="px-4 py-3">
                        <span class="font-medium text-gray-900">${item.name}</span>
                        <input type="hidden" name="items[${index}][sales_order_item_id]" value="${item.id}">
                    </td>
                    <td class="px-4 py-3 text-center">
                        <span class="text-gray-600">${item.quantity_ordered}</span>
                        <p class="text-xs text-gray-500 mt-1">(تم تسليم ${item.quantity_delivered_previously} سابقاً)</p>
                    </td>
                    <td class="px-4 py-3 text-center">
                        <input type="number" name="items[${index}][quantity_delivered]" step="0.01" min="0" max="${item.remaining_quantity}" value="${item.remaining_quantity}" 
                            class="w-24 px-2 py-1 border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 text-center"
                            onchange="updateAcceptedQty(this, ${index})">
                    </td>
                    <td class="px-4 py-3 text-center">
                        <input type="number" name="items[${index}][quantity_accepted]" step="0.01" min="0" value="${item.remaining_quantity}" 
                            class="w-24 px-2 py-1 border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 text-center"
                            onchange="calculateRejected(this, ${index})">
                    </td>
                    <td class="px-4 py-3 text-center">
                        <input type="number" name="items[${index}][quantity_rejected]" id="rejected_${index}" step="0.01" min="0" value="0" readonly 
                            class="w-24 px-2 py-1 border border-gray-100 bg-gray-50 rounded text-center text-red-600 font-medium">
                    </td>
                    <td class="px-4 py-3">
                        <input type="text" name="items[${index}][rejection_reason]" placeholder="سبب الرفض..." 
                            class="w-full px-3 py-1 border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 text-sm">
                    </td>
                </tr>
            `;
        }
    });

    if (html === '') {
        html = `<tr><td colspan="6" class="px-6 py-12 text-center text-yellow-600">كل الأصناف في هذا الطلب تم تسليمها بالكامل</td></tr>`;
    }

    tableBody.innerHTML = html;
}

function updateAcceptedQty(input, index) {
    const acceptedInput = document.querySelector(`input[name="items[${index}][quantity_accepted]"]`);
    acceptedInput.value = input.value;
    calculateRejected(acceptedInput, index);
}

function calculateRejected(input, index) {
    const deliveredQty = parseFloat(document.querySelector(`input[name="items[${index}][quantity_delivered]"]`).value) || 0;
    const acceptedQty = parseFloat(input.value) || 0;
    
    if (acceptedQty > deliveredQty) {
        alert('الكمية المقبولة لا يمكن أن تكون أكبر من الكمية المسلمة');
        input.value = deliveredQty;
        document.getElementById(`rejected_${index}`).value = 0;
        return;
    }

    const rejectedQty = deliveredQty - acceptedQty;
    document.getElementById(`rejected_${index}`).value = rejectedQty.toFixed(2);
}
</script>
@endsection
