@extends('layouts.app')

@section('title', 'تعديل مرتجع مشتريات')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">تعديل مرتجع مشتريات #{{ $purchaseReturn->return_number }}</h3>
                    <div class="card-tools">
                        <a href="{{ route('inventory.purchase-returns.show', $purchaseReturn->id) }}" class="btn btn-default">
                            <i class="fas fa-arrow-right"></i> العودة للتفاصيل
                        </a>
                    </div>
                </div>
                <form action="{{ route('inventory.purchase-returns.update', $purchaseReturn->id) }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    @method('PUT')
                    <div class="card-body">
                        @if(session('error'))
                            <div class="alert alert-danger">
                                {{ session('error') }}
                            </div>
                        @endif

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="supplier_id">المورد <span class="text-danger">*</span></label>
                                    <select name="supplier_id" id="supplier_id" class="form-control @error('supplier_id') is-invalid @enderror" required>
                                        <option value="">-- اختر المورد --</option>
                                        @foreach($suppliers as $supplier)
                                            <option value="{{ $supplier->id }}" {{ old('supplier_id', $purchaseReturn->supplier_id) == $supplier->id ? 'selected' : '' }}>
                                                {{ $supplier->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('supplier_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="warehouse_id">المستودع <span class="text-danger">*</span></label>
                                    <select name="warehouse_id" id="warehouse_id" class="form-control @error('warehouse_id') is-invalid @enderror" required>
                                        <option value="">-- اختر المستودع --</option>
                                        @foreach($warehouses as $warehouse)
                                            <option value="{{ $warehouse->id }}" {{ old('warehouse_id', $purchaseReturn->warehouse_id) == $warehouse->id ? 'selected' : '' }}>
                                                {{ $warehouse->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('warehouse_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="purchase_invoice_id">فاتورة المشتريات</label>
                                    <select name="purchase_invoice_id" id="purchase_invoice_id" class="form-control @error('purchase_invoice_id') is-invalid @enderror">
                                        <option value="">-- اختر فاتورة المشتريات --</option>
                                        @foreach($purchaseInvoices as $invoice)
                                            <option value="{{ $invoice->id }}" {{ old('purchase_invoice_id', $purchaseReturn->purchase_invoice_id) == $invoice->id ? 'selected' : '' }}>
                                                {{ $invoice->invoice_number }} - {{ $invoice->supplier->name }} - {{ number_format($invoice->total_amount, 2) }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('purchase_invoice_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="return_date">تاريخ المرتجع <span class="text-danger">*</span></label>
                                    <input type="date" name="return_date" id="return_date" class="form-control @error('return_date') is-invalid @enderror" value="{{ old('return_date', $purchaseReturn->return_date->format('Y-m-d')) }}" required>
                                    @error('return_date')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-8">
                                <div class="form-group">
                                    <label for="notes">ملاحظات</label>
                                    <textarea name="notes" id="notes" class="form-control @error('notes') is-invalid @enderror" rows="1">{{ old('notes', $purchaseReturn->notes) }}</textarea>
                                    @error('notes')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="attachment">مرفق</label>
                                    <input type="file" name="attachment" id="attachment" class="form-control @error('attachment') is-invalid @enderror">
                                    @if($purchaseReturn->attachment)
                                        <small class="form-text text-muted">
                                            <a href="{{ asset($purchaseReturn->attachment) }}" target="_blank">
                                                <i class="fas fa-file"></i> عرض المرفق الحالي
                                            </a>
                                        </small>
                                    @endif
                                    @error('attachment')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <hr>
                        <h4>عناصر المرتجع</h4>

                        <div class="table-responsive">
                            <table class="table table-bordered" id="items-table">
                                <thead>
                                    <tr>
                                        <th>الصنف <span class="text-danger">*</span></th>
                                        <th>الكمية <span class="text-danger">*</span></th>
                                        <th>سعر الوحدة <span class="text-danger">*</span></th>
                                        <th>نسبة الضريبة %</th>
                                        <th>مبلغ الخصم</th>
                                        <th>الإجمالي</th>
                                        <th>ملاحظات</th>
                                        <th>الإجراءات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($purchaseReturn->items as $index => $item)
                                        <tr>
                                            <td>
                                                <select name="items[{{ $index }}][inventory_item_id]" class="form-control item-select" required>
                                                    <option value="">-- اختر الصنف --</option>
                                                    @foreach($inventoryItems as $inventoryItem)
                                                        <option value="{{ $inventoryItem->id }}" data-price="{{ $inventoryItem->purchase_price }}" {{ $item->inventory_item_id == $inventoryItem->id ? 'selected' : '' }}>
                                                            {{ $inventoryItem->name }} - {{ $inventoryItem->code }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                                @if($item->purchase_invoice_item_id)
                                                    <input type="hidden" name="items[{{ $index }}][purchase_invoice_item_id]" value="{{ $item->purchase_invoice_item_id }}">
                                                @endif
                                            </td>
                                            <td>
                                                <input type="number" name="items[{{ $index }}][quantity]" class="form-control item-quantity" min="0.01" step="0.01" value="{{ $item->quantity }}" required>
                                            </td>
                                            <td>
                                                <input type="number" name="items[{{ $index }}][unit_price]" class="form-control item-price" min="0" step="0.01" value="{{ $item->unit_price }}" required>
                                            </td>
                                            <td>
                                                <input type="number" name="items[{{ $index }}][tax_rate]" class="form-control item-tax" min="0" step="0.01" value="{{ $item->tax_rate }}">
                                            </td>
                                            <td>
                                                <input type="number" name="items[{{ $index }}][discount_amount]" class="form-control item-discount" min="0" step="0.01" value="{{ $item->discount_amount }}">
                                            </td>
                                            <td>
                                                <input type="text" class="form-control item-total" value="{{ $item->total_amount }}" readonly>
                                            </td>
                                            <td>
                                                <input type="text" name="items[{{ $index }}][notes]" class="form-control" value="{{ $item->notes }}">
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-danger btn-sm remove-item">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="8">
                                            <button type="button" class="btn btn-success btn-sm" id="add-item">
                                                <i class="fas fa-plus"></i> إضافة صنف
                                            </button>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        <div class="row mt-4">
                            <div class="col-md-6 offset-md-6">
                                <table class="table table-bordered">
                                    <tr>
                                        <th>المجموع الفرعي</th>
                                        <td><span id="subtotal">{{ number_format($purchaseReturn->subtotal, 2) }}</span></td>
                                    </tr>
                                    <tr>
                                        <th>مجموع الضريبة</th>
                                        <td><span id="tax-total">{{ number_format($purchaseReturn->tax_amount, 2) }}</span></td>
                                    </tr>
                                    <tr>
                                        <th>مجموع الخصم</th>
                                        <td><span id="discount-total">{{ number_format($purchaseReturn->discount_amount, 2) }}</span></td>
                                    </tr>
                                    <tr>
                                        <th>الإجمالي النهائي</th>
                                        <td><span id="final-total">{{ number_format($purchaseReturn->total_amount, 2) }}</span></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="card-footer">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> حفظ التغييرات
                        </button>
                        <a href="{{ route('inventory.purchase-returns.show', $purchaseReturn->id) }}" class="btn btn-default">
                            <i class="fas fa-times"></i> إلغاء
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    $(document).ready(function() {
        // تحديث الإجماليات عند تغيير أي قيمة
        function updateTotals() {
            let subtotal = 0;
            let taxTotal = 0;
            let discountTotal = 0;
            let finalTotal = 0;

            $('#items-table tbody tr').each(function() {
                const quantity = parseFloat($(this).find('.item-quantity').val()) || 0;
                const price = parseFloat($(this).find('.item-price').val()) || 0;
                const taxRate = parseFloat($(this).find('.item-tax').val()) || 0;
                const discount = parseFloat($(this).find('.item-discount').val()) || 0;

                const rowSubtotal = quantity * price;
                const rowTax = rowSubtotal * (taxRate / 100);
                const rowTotal = rowSubtotal + rowTax - discount;

                $(this).find('.item-total').val(rowTotal.toFixed(2));

                subtotal += rowSubtotal;
                taxTotal += rowTax;
                discountTotal += discount;
            });

            finalTotal = subtotal + taxTotal - discountTotal;

            $('#subtotal').text(subtotal.toFixed(2));
            $('#tax-total').text(taxTotal.toFixed(2));
            $('#discount-total').text(discountTotal.toFixed(2));
            $('#final-total').text(finalTotal.toFixed(2));
        }

        // تحديث الإجماليات عند تغيير أي قيمة
        $(document).on('change', '.item-quantity, .item-price, .item-tax, .item-discount', function() {
            updateTotals();
        });

        // تحديث سعر الوحدة عند اختيار الصنف
        $(document).on('change', '.item-select', function() {
            const selectedOption = $(this).find('option:selected');
            const price = selectedOption.data('price') || 0;
            $(this).closest('tr').find('.item-price').val(price);
            updateTotals();
        });

        // إضافة صنف جديد
        let itemIndex = {{ count($purchaseReturn->items) }};
        $('#add-item').click(function() {
            const newRow = `
                <tr>
                    <td>
                        <select name="items[${itemIndex}][inventory_item_id]" class="form-control item-select" required>
                            <option value="">-- اختر الصنف --</option>
                            @foreach($inventoryItems as $item)
                                <option value="{{ $item->id }}" data-price="{{ $item->purchase_price }}">
                                    {{ $item->name }} - {{ $item->code }}
                                </option>
                            @endforeach
                        </select>
                    </td>
                    <td>
                        <input type="number" name="items[${itemIndex}][quantity]" class="form-control item-quantity" min="0.01" step="0.01" value="1" required>
                    </td>
                    <td>
                        <input type="number" name="items[${itemIndex}][unit_price]" class="form-control item-price" min="0" step="0.01" value="0" required>
                    </td>
                    <td>
                        <input type="number" name="items[${itemIndex}][tax_rate]" class="form-control item-tax" min="0" step="0.01" value="0">
                    </td>
                    <td>
                        <input type="number" name="items[${itemIndex}][discount_amount]" class="form-control item-discount" min="0" step="0.01" value="0">
                    </td>
                    <td>
                        <input type="text" class="form-control item-total" readonly>
                    </td>
                    <td>
                        <input type="text" name="items[${itemIndex}][notes]" class="form-control">
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger btn-sm remove-item">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
            $('#items-table tbody').append(newRow);
            itemIndex++;
            updateTotals();
        });

        // حذف صنف
        $(document).on('click', '.remove-item', function() {
            if ($('#items-table tbody tr').length > 1) {
                $(this).closest('tr').remove();
                updateTotals();
            } else {
                alert('يجب أن يحتوي المرتجع على صنف واحد على الأقل');
            }
        });

        // تحديث الإجماليات عند تحميل الصفحة
        updateTotals();
    });
</script>
@endpush