@extends('layouts.app')
@section('title', 'إنشاء ' . ($returnType === 'credit_note' ? 'إشعار دائن' : 'فاتورة مرتجعة'))

@section('content')
<style>
    .form-control-xs {
        height: calc(1.5em + .5rem + 2px);
        padding: .25rem .25rem;
        font-size: .75rem;
        line-height: 1.5;
        border-radius: .2rem;
    }
    .table-compact td, .table-compact th {
        padding: 0.4rem;
        vertical-align: middle;
        font-size: 0.85rem;
    }
    .table-compact input.form-control {
        font-size: 0.85rem;
        padding: 0.2rem 0.4rem;
    }
</style>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="card shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <div class="d-flex justify-content-between align-items-center">
                        <h3 class="card-title font-weight-bold text-dark mb-0">
                            <i class="fas fa-undo-alt text-primary mr-2"></i>
                            {{ $returnType === 'credit_note' ? 'إنشاء إشعار دائن' : 'إنشاء فاتورة مرتجعة' }}
                        </h3>
                        <a href="{{ route('customer-invoices.show', $invoice->id) }}" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-arrow-right"></i> عودة للفاتورة
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form action="{{ route('customer-invoice-returns.store') }}" method="POST" enctype="multipart/form-data">
                        @csrf

                        <div class="row bg-light p-3 rounded mb-4 border">
                            <div class="col-md-3">
                                <div class="form-group mb-0">
                                    <label class="small font-weight-bold">تاريخ المرتجع</label>
                                    <input type="date" class="form-control form-control-sm @error('return_date') is-invalid @enderror" 
                                           id="return_date" name="return_date" value="{{ old('return_date', date('Y-m-d')) }}" required>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group mb-0">
                                    <label class="small font-weight-bold">نوع المرتجع</label>
                                    <select class="form-control form-control-sm" name="return_type">
                                        <option value="sales_return" {{ $returnType === 'sales_return' ? 'selected' : '' }}>فاتورة مرتجعة</option>
                                        <option value="credit_note" {{ $returnType === 'credit_note' ? 'selected' : '' }}>إشعار دائن</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6 border-left">
                                <div class="row">
                                    <div class="col-md-4">
                                        <label class="small font-weight-bold text-muted">العميل</label>
                                        <div class="text-dark font-weight-bold truncate">{{ $invoice->customer ? $invoice->customer->name : 'العميل غير موجود' }}</div>
                                        <input type="hidden" name="customer_id" value="{{ $invoice->customer_id }}">
                                    </div>
                                    <div class="col-md-4 border-left">
                                        <label class="small font-weight-bold text-muted">الفاتورة الأصلية</label>
                                        <div class="text-dark font-weight-bold">{{ $invoice->invoice_number ?? '-' }}</div>
                                        <input type="hidden" name="customer_invoice_id" value="{{ $invoice->id }}">
                                    </div>
                                    <div class="col-md-4 border-left">
                                        <label class="small font-weight-bold text-muted">تاريخ الفاتورة</label>
                                        <div class="text-dark font-weight-bold">{{ $invoice->invoice_date ? $invoice->invoice_date->format('Y-m-d') : '-' }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="table-responsive mb-4">
                            <table class="table table-bordered table-compact table-hover mb-0">
                                <thead class="bg-secondary text-white">
                                    <tr>
                                        <th style="width: 40px;" class="text-center">#</th>
                                        <th style="width: 180px;">اسم الصنف</th>
                                        <th style="width: 80px;" class="text-center">الوحدة</th>
                                        <th>الوصف</th>
                                        <th style="width: 90px;" class="text-center">الكمية</th>
                                        <th style="width: 110px;" class="text-center">سعر الوحدة</th>
                                        <th style="width: 75px;" class="text-center">خصم %</th>
                                        <th style="width: 75px;" class="text-center">ضريبة %</th>
                                        <th style="width: 120px;" class="text-center">الإجمالي</th>
                                    </tr>
                                </thead>
                                <tbody id="items-table">
                                    @forelse($items as $index => $item)
                                    @if($item && $item->id)
                                    <tr>
                                        <td class="text-center text-muted">{{ $index + 1 }}</td>
                                        <td class="font-weight-bold">{{ optional($item->item)->name ?? '-' }}</td>
                                        <td class="text-center"><span class="badge badge-light border">{{ optional(optional($item->itemUnit)->unit)->name ?? '-' }}</span></td>
                                        <td>
                                            <input type="text" class="form-control form-control-sm w-100" 
                                                   name="items[{{ $index }}][description]" 
                                                   value="{{ old('items.' . $index . '.description', $item->description) }}"
                                                   placeholder="أضف وصفاً...">
                                            <input type="hidden" name="items[{{ $index }}][customer_invoice_item_id]" value="{{ $item->id }}">
                                            <input type="hidden" name="items[{{ $index }}][discount_type]" value="percentage">
                                        </td>
                                        <td>
                                            <input type="number" class="form-control form-control-sm text-center quantity font-weight-bold" 
                                                   name="items[{{ $index }}][quantity]" 
                                                   value="{{ old('items.' . $index . '.quantity', $item->quantity) }}" 
                                                   step="0.01" min="0" required>
                                        </td>
                                        <td>
                                            <div class="input-group input-group-sm">
                                                <input type="number" class="form-control text-center unit-price font-weight-bold" 
                                                       name="items[{{ $index }}][unit_price]" 
                                                       value="{{ old('items.' . $index . '.unit_price', $item->unit_price) }}" 
                                                       step="0.01" min="0" required>
                                            </div>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control form-control-sm text-center discount-rate text-danger" 
                                                   name="items[{{ $index }}][discount_amount]" 
                                                   value="{{ old('items.' . $index . '.discount_amount', $item->discount_amount) }}" 
                                                   step="0.01" min="0" max="100">
                                        </td>
                                        <td>
                                            <input type="number" class="form-control form-control-sm text-center tax-rate text-success" 
                                                   name="items[{{ $index }}][tax_rate]" 
                                                   value="{{ old('items.' . $index . '.tax_rate', $item->tax_rate) }}" 
                                                   step="0.01" min="0" max="100">
                                        </td>
                                        <td class="text-right bg-light font-weight-bold">
                                            <span class="item-total text-dark">{{ number_format($item->total, 2) }}</span>
                                        </td>
                                    </tr>
                                    @endif
                                    @empty
                                        <tr>
                                            <td colspan="9" class="text-center text-muted py-5 bg-white">
                                                <i class="fas fa-box-open text-muted mb-3" style="font-size: 3rem; opacity: 0.3;"></i>
                                                <p class="h6">لا توجد عناصر في الفاتورة الأصلية</p>
                                            </td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>

                        <div class="row">
                            <div class="col-md-7">
                                <div class="form-group">
                                    <label for="notes" class="small font-weight-bold"><i class="fas fa-sticky-note mr-1"></i> ملاحظات</label>
                                    <textarea class="form-control" id="notes" name="notes" rows="4" placeholder="أضف ملاحظات إضافية هنا...">{{ old('notes') }}</textarea>
                                </div>
                                <div class="form-group mt-3">
                                    <label for="attachment" class="small font-weight-bold"><i class="fas fa-paperclip mr-1"></i> المرفق</label>
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input @error('attachment') is-invalid @enderror" 
                                               id="attachment" name="attachment">
                                        <label class="custom-file-label" for="attachment">اختر ملف...</label>
                                    </div>
                                    @error('attachment')
                                        <span class="invalid-feedback d-block">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-5">
                                <div class="card border-primary shadow-sm">
                                    <div class="card-body p-0">
                                        <div class="p-3 border-bottom d-flex justify-content-between">
                                            <span class="text-muted">المبلغ الفرعي:</span>
                                            <span class="font-weight-bold" id="subtotal">0.00</span>
                                        </div>
                                        <div class="p-3 border-bottom d-flex justify-content-between">
                                            <span class="text-muted text-danger">إجمالي الخصم (-):</span>
                                            <span class="font-weight-bold text-danger" id="discount">0.00</span>
                                        </div>
                                        <div class="p-3 border-bottom d-flex justify-content-between">
                                            <span class="text-muted text-success">إجمالي الضريبة (+):</span>
                                            <span class="font-weight-bold text-success" id="tax">0.00</span>
                                        </div>
                                        <div class="p-3 bg-primary text-white d-flex justify-content-between align-items-center rounded-bottom">
                                            <span class="h6 mb-0">الإجمالي النهائي:</span>
                                            <span class="h4 mb-0 font-weight-bold" id="total">0.00</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="mt-4 d-flex">
                                    <button type="submit" class="btn btn-primary btn-lg flex-grow-1 mr-2 shadow">
                                        <i class="fas fa-check-circle mr-1"></i> حفظ المرتجع
                                    </button>
                                    <a href="{{ route('customer-invoices.show', $invoice->id) }}" class="btn btn-outline-secondary btn-lg px-4">
                                        إلغاء
                                    </a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // تحديث اسم الملف المرفق
    document.querySelector('.custom-file-input')?.addEventListener('change', function(e) {
        var fileName = e.target.files[0]?.name || "اختر ملف...";
        var nextSibling = e.target.nextElementSibling;
        nextSibling.innerText = fileName;
    });

    function calculateTotals() {
        let subtotal = 0;
        let totalDiscount = 0;
        let totalTax = 0;

        document.querySelectorAll('#items-table tr').forEach(row => {
            const quantityInput = row.querySelector('.quantity');
            if (!quantityInput) return;

            const quantity = parseFloat(quantityInput.value) || 0;
            const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
            const discountRate = parseFloat(row.querySelector('.discount-rate').value) || 0;
            const taxRate = parseFloat(row.querySelector('.tax-rate').value) || 0;

            const basePrice = quantity * unitPrice;
            const discountAmount = (basePrice * discountRate) / 100;
            const priceAfterDiscount = basePrice - discountAmount;
            const taxAmount = (priceAfterDiscount * taxRate) / 100;
            const itemTotal = priceAfterDiscount + taxAmount;

            subtotal += basePrice;
            totalDiscount += discountAmount;
            totalTax += taxAmount;

            const itemTotalSpan = row.querySelector('.item-total');
            if (itemTotalSpan) {
                itemTotalSpan.textContent = itemTotal.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
            }
        });

        const total = subtotal - totalDiscount + totalTax;

        document.getElementById('subtotal').textContent = subtotal.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
        document.getElementById('discount').textContent = totalDiscount.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
        document.getElementById('tax').textContent = totalTax.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
        document.getElementById('total').textContent = total.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
    }

    document.querySelectorAll('.quantity, .unit-price, .discount-rate, .tax-rate').forEach(input => {
        input.addEventListener('input', calculateTotals);
    });

    calculateTotals();
});
</script>
@endsection
