@extends('layouts.app')

@section('content')
<div class="container m-auto p-4 sm:p-6 lg:p-8">
    <div class="bg-white rounded-lg shadow-lg p-6">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2l font-bold text-gray-900">تعديل إذن صرف</h1>
            <div class="flex space-y-2 space-y-reverse">
                <a href="{{ route('inventory.issues.index') }}" class="inline-flex items-center p-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
                    <svg class="h-5 w-5 ml-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                    </svg>
                    العودة للقائمة
                </a>
                <a href="{{ route('inventory.issues.show', $document->id) }}" class="inline-flex items-center p-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                    <svg class="h-5 w-5 ml-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>
                    عرض
                </a>
            </div>
        </div>

        @if ($errors->any())
        <div class="mb-6 bg-red-50 p-4 rounded-md">
            <div class="flex">
                <div class="flex-shrink-0">
                    <svg class="h-5 w-5 text-red-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
                    </svg>
                </div>
                <div class="mr-3">
                    <h3 class="text-sm font-medium text-red-800">يوجد {{ $errors->count() }} أخطاء في البيانات المدخلة</h3>
                    <div class="mt-2 text-sm text-red-700">
                        <ul class="list-disc list-inside space-y-1">
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        @endif

        <form action="{{ route('inventory.issues.update', $document->id) }}" method="POST">
            @csrf
            @method('PUT')
            
            <div class="mb-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="document_number" class="block text-sm font-medium text-gray-700 mb-1">رقم المستند <span class="text-red-600">*</span></label>
                    <input type="text" id="document_number" name="document_number" value="{{ old('document_number', $document->document_number) }}" readonly class="block w-full rounded-md border-gray-300 bg-gray-100 shadow-sm text-gray-600 font-semibold">
                </div>
                
                <div>
                    <label for="document_date" class="block text-sm font-medium text-gray-700 mb-1">تاريخ المستند <span class="text-red-600">*</span></label>
                    <input type="date" id="document_date" name="document_date" value="{{ old('document_date', $document->document_date->format('Y-m-d')) }}" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                </div>
            </div>

            <div class="mb-6 grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                    <label for="from_warehouse_id" class="block text-sm font-medium text-gray-700 mb-1">المخزن <span class="text-red-600">*</span></label>
                    <select id="from_warehouse_id" name="from_warehouse_id" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                        <option value="">اختر المخزن</option>
                        @foreach($warehouses as $warehouse)
                            <option value="{{ $warehouse->id }}" {{ old('from_warehouse_id', $document->from_warehouse_id) == $warehouse->id ? 'selected' : '' }}>{{ $warehouse->name }}</option>
                        @endforeach
                    </select>
                </div>

                <div>
                    <label for="customer_invoice_id" class="block text-sm font-medium text-gray-700 mb-1">فاتورة مبيعات العميل</label>
                    <select id="customer_invoice_id" name="customer_invoice_id" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                        <option value="">-- اختر فاتورة العميل --</option>
                        @foreach($customerInvoices as $invoice)
                            <option value="{{ $invoice->id }}" {{ old('customer_invoice_id', $document->customer_invoice_id) == $invoice->id ? 'selected' : '' }}>
                                {{ $invoice->invoice_number }} - {{ $invoice->customer->name ?? $invoice->customer_name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <div>
                    <label for="reference_number" class="block text-sm font-medium text-gray-700 mb-1">رقم المرجع</label>
                    <input type="text" id="reference_number" name="reference_number" value="{{ old('reference_number', $document->reference_number) }}" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50" placeholder="رقم المرجع (اختياري)">
                </div>
            </div>

            <div class="mb-6">
                <label for="notes" class="block text-sm font-medium text-gray-700 mb-1">ملاحظات</label>
                <textarea id="notes" name="notes" rows="3" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">{{ old('notes', $document->notes) }}</textarea>
            </div>
            
            <div class="mb-6">
                <h2 class="text-lg font-bold text-gray-900 mb-4">الأصناف</h2>
                
                <div class="overflow--auto mb-4">
                    <table class="min-w-full divide-y divide-gray-200" id="items-table">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الصنف <span class="text-red-600">*</span></th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الوحدة <span class="text-red-600">*</span></th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الكمية <span class="text-red-600">*</span></th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">تكلفة الوحدة <span class="text-red-600">*</span></th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الإجمالي</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">مركز التكلفة</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">ملاحظات</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="items-container">
                            @foreach($document->items as $inde => $item)
                            <tr class="item-row">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <select name="item_ids[]" required class="item-select block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                                        <option value="">اختر الصنف</option>
                                        @foreach($items as $inventoryItem)
                                            <option value="{{ $inventoryItem->id }}" data-primary-unit="{{ $inventoryItem->primary_unit_id }}" {{ $item->item_id == $inventoryItem->id ? 'selected' : '' }}>{{ $inventoryItem->name }}</option>
                                        @endforeach
                                    </select>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <select name="unit_ids[]" required class="unit-select block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                                        <option value="">اختر الوحدة</option>
                                        @if($item->unit)
                                            <option value="{{ $item->unit_id }}" selected>{{ $item->unit->name }}</option>
                                        @endif
                                    </select>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input type="number" name="quantities[]" value="{{ old('quantities.'.$inde, $item->quantity) }}" step="0.01" min="0.01" required class="quantity-input block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input type="number" name="unit_costs[]" value="{{ old('unit_costs.'.$inde, $item->unit_cost) }}" step="0.01" min="0" required class="unit-cost-input block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input type="number" readonly value="{{ number_format($item->total_cost, 2) }}" class="total-cost-display block w-full bg-gray-100 rounded-md border-gray-300 shadow-sm">
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <select name="cost_center_ids[]" class="cost-center-select block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                                        <option value="">-- بدون --</option>
                                        @foreach($costCenters as $center)
                                            <option value="{{ $center->id }}" {{ $item->cost_center_id == $center->id ? 'selected' : '' }}>{{ $center->code }} - {{ $center->name }}</option>
                                        @endforeach
                                    </select>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <input type="text" name="item_notes[]" value="{{ old('item_notes.'.$inde, $item->notes) }}" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <button type="button" class="remove-item text-red-600 hover:text-red-900">
                                        <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                        </svg>
                                    </button>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                
                <div class="flex justify-end">
                    <button type="button" id="add-item" class="inline-flex items-center p-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                        <svg class="h-5 w-5 ml-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                        </svg>
                        إضافة صنف
                    </button>
                </div>
            </div>
            
            <div class="flex justify-end">
                <button type="submit" class="inline-flex items-center p-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                    <svg class="h-5 w-5 ml-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                    </svg>
                    حفظ التعديلات
                </button>
            </div>
        </form>
    </div>
</div>

<template id="item-row-template">
    <tr class="item-row">
        <td class="px-6 py-4 whitespace-nowrap">
            <select name="item_ids[]" required class="item-select block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                <option value="">اختر الصنف</option>
                @foreach($items as $item)
                    <option value="{{ $item->id }}" data-primary-unit="{{ $item->primary_unit_id }}">{{ $item->name }}</option>
                @endforeach
            </select>
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <select name="unit_ids[]" required class="unit-select block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                <option value="">اختر الوحدة</option>
            </select>
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <input type="number" name="quantities[]" step="0.01" min="0.01" required class="quantity-input block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <input type="number" name="unit_costs[]" step="0.01" min="0" required class="unit-cost-input block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <input type="number" readonly class="total-cost-display block w-full bg-gray-100 rounded-md border-gray-300 shadow-sm">
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <select name="cost_center_ids[]" class="cost-center-select block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                <option value="">-- بدون --</option>
                @foreach($costCenters as $center)
                    <option value="{{ $center->id }}">{{ $center->code }} - {{ $center->name }}</option>
                @endforeach
            </select>
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <input type="text" name="item_notes[]" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
        </td>
        <td class="px-6 py-4 whitespace-nowrap">
            <button type="button" class="remove-item text-red-600 hover:text-red-900">
                <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
            </button>
        </td>
    </tr>
</template>

@endsection

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        if (document.querySelectorAll('.item-row').length === 0) {
            addItemRow();
        }
        
        const addBtn = document.getElementById('add-item');
        if (addBtn) {
            addBtn.addEventListener('click', addItemRow);
        }
        
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-item') || e.target.closest('.remove-item')) {
                const row = e.target.closest('.item-row');
                if (document.querySelectorAll('.item-row').length > 1) {
                    row.remove();
                } else {
                    alert('يجب أن يحتوي المستند على صنف واحد على الأقل');
                }
            }
        });
        
        document.addEventListener('change', function(e) {
            if (e.target.classList.contains('item-select')) {
                const row = e.target.closest('.item-row');
                const unitSelect = row.querySelector('.unit-select');
                
                unitSelect.innerHTML = '<option value="">اختر الوحدة</option>';
                
                if (e.target.value) {
                    fetch(`{{ route("inventory.items.units.api", ":itemId") }}`.replace(':itemId', e.target.value), { credentials: "same-origin" })
                        .then(response => response.json())
                        .then(data => {
                            data.data.forEach(unit => {
                                const option = document.createElement('option');
                                option.value = unit.unit_id;
                                option.textContent = unit.unit_name;
                                unitSelect.appendChild(option);
                            });
                        })
                        .catch(error => {
                            console.error('Error fetching units:', error);
                        });
                }
            }
        });
        
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('quantity-input') || e.target.classList.contains('unit-cost-input')) {
                const row = e.target.closest('.item-row');
                const quantity = parseFloat(row.querySelector('.quantity-input').value) || 0;
                const unitCost = parseFloat(row.querySelector('.unit-cost-input').value) || 0;
                const totalCost = quantity * unitCost;
                
                row.querySelector('.total-cost-display').value = totalCost.toFixed(2);
            }
        });
        
        function addItemRow() {
            const template = document.getElementById('item-row-template');
            const container = document.getElementById('items-container');
            
            if (template && container) {
                const clone = document.importNode(template.content, true);
                container.appendChild(clone);
            }
        }
        
        document.querySelectorAll('.item-row').forEach(function(row) {
            const quantity = parseFloat(row.querySelector('.quantity-input').value) || 0;
            const unitCost = parseFloat(row.querySelector('.unit-cost-input').value) || 0;
            const totalCost = quantity * unitCost;
            
            row.querySelector('.total-cost-display').value = totalCost.toFixed(2);
        });
    });
</script>
@endpush
