@extends('layouts.app')
@section('title', \App\Helpers\TranslationHelper::transFromDatabase('Add New Invoice', __('Add New Invoice')))

@push('styles')
<style>
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.8);
        z-index: 9999;
        display: none;
        align-items: center;
        justify-content: center;
        flex-direction: column;
    }
    .loading-spinner {
        width: 50px;
        height: 50px;
        border: 5px solid #f3f3f3;
        border-top: 5px solid #28a745;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 15px;
    }
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
</style>
@endpush

@php
    $company = \App\Models\Company::find(auth()->user()->company_id);
    $activeSubscription = \App\Models\Subscription::where('company_id', auth()->user()->company_id)
        ->where('status', 'active')
        ->where('subscription_end_date', '>=', now())
        ->first();
    
    $trialSubscription = \App\Models\Subscription::where('company_id', auth()->user()->company_id)
        ->where('status', 'trial')
        ->where('trial_end_date', '>=', now())
        ->first();
    
    $invoicesCount = \App\Models\CustomerInvoice::where('company_id', auth()->user()->company_id)->count();
    $hasActiveSubscription = $activeSubscription || $trialSubscription;
    $invoicesRemaining = max(0, 30 - $invoicesCount);
@endphp

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            @if(!$hasActiveSubscription && $invoicesRemaining <= 1)
                <div class="alert alert-warning alert-dismissible fade show" role="alert" style="margin-bottom: 20px;">
                    <h4 class="alert-heading" style="margin-bottom: 10px;">
                        <i class="fas fa-exclamation-triangle"></i> تنبيه مهم!
                    </h4>
                    <p style="margin-bottom: 0;">
                        ⚠️ <strong>لا يوجد اشتراك نشط حالياً</strong><br>
                        📋 عدد الفواتير المتبقية: <strong style="color: #d9534f;">{{ $invoicesRemaining }}</strong> من 30<br>
                        💡 بعد انتهاء الفواتير المسموح بها، لن تتمكن من إنشاء فواتير جديدة إلا بتفعيل الاشتراك.<br>
                        📞 يرجى التواصل مع مدير الحساب لتفعيل الاشتراك أو تجديد النسخة التجريبية.
                    </p>
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            @endif

            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">{{ \App\Helpers\TranslationHelper::transFromDatabase('Add New Invoice', __('Add New Invoice')) }}</h3>
                    <div class="card-tools">
                        <a href="{{ route('customer-invoices.index') }}" class="btn btn-sm btn-secondary">
                            <i class="fas fa-arrow-right"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Return to Invoices', __('Return to Invoices')) }}
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form id="invoiceForm" action="{{ route('customer-invoices.store') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <div class="card bg-light border-info">
                                    <div class="card-body py-2">
                                        <div class="row align-items-center">
                                            <div class="col-md-4">
                                                <div class="custom-control custom-checkbox">
                                                    <input type="checkbox" name="auto_warehouse_issue" class="custom-control-input" id="auto_warehouse_issue" value="1" checked>
                                                    <label class="custom-control-label font-weight-bold text-info" for="auto_warehouse_issue">
                                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Issue automatic warehouse permit', __('اصدار اذن مخزن تلقائي')) }}
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-5" id="warehouse_selector_container">
                                                <div class="form-group mb-0 row">
                                                    <label for="warehouse_id" class="col-sm-4 col-form-label text-right">{{ \App\Helpers\TranslationHelper::transFromDatabase('Warehouse', __('المخزن')) }}</label>
                                                    <div class="col-sm-8">
                                                        <select name="warehouse_id" id="warehouse_id" class="form-control form-control-sm">
                                                            <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Warehouse', __('اختر المخزن')) }} --</option>
                                                            @foreach($warehouses as $warehouse)
                                                                <option value="{{ $warehouse->id }}">{{ $warehouse->name }}</option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        @if(isset($labOrder))
                            <input type="hidden" name="lab_order_id" value="{{ $labOrder->id }}">
                        @endif

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="customer_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customer Name', __('Customer Name')) }} <span class="text-danger">*</span></label>
                                    <select name="customer_id" id="customer_id" class="form-control @error('customer_id') is-invalid @enderror" required>
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Customer', __('Choose Customer')) }} --</option>
                                        @foreach($customers as $customer)
                                            <option value="{{ $customer->id }}" 
                                                data-account-code="{{ $customer->chartOfAccount->code ?? '' }}"
                                                {{ (old('customer_id') ?? $matchedCustomerId ?? (isset($salesOrder) ? $salesOrder->customer_id : (isset($deliveryNote) ? $deliveryNote->customer_id : ''))) == $customer->id ? 'selected' : '' }}>
                                                {{ $customer->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('customer_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="customer_account_number">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customer Account Number', __('رقم حساب العميل')) }}</label>
                                    <input type="text" id="customer_account_number" class="form-control bg-light" readonly>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="sales_representative_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Sales Representative', __('Sales Representative')) }} <span class="text-danger">*</span></label>
                                    <select name="sales_representative_id" id="sales_representative_id" class="form-control @error('sales_representative_id') is-invalid @enderror" required>
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Sales Representative', __('Choose Sales Representative')) }} --</option>
                                        @foreach($salesRepresentatives as $representative)
                                            <option value="{{ $representative->id }}" {{ (old('sales_representative_id') ?? (isset($salesOrder) ? $salesOrder->sales_representative_id : '')) == $representative->id ? 'selected' : '' }}>
                                                {{ $representative->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('sales_representative_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="reference_number">{{ \App\Helpers\TranslationHelper::transFromDatabase('Reference Number', __('الرقم المرجعي')) }}</label>
                                    <input type="text" name="reference_number" id="reference_number" class="form-control @error('reference_number') is-invalid @enderror" value="{{ old('reference_number', isset($referenceNumber) ? $referenceNumber : '') }}">
                                    @error('reference_number')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                    @if(isset($deliveryNote) && $deliveryNote)
                                        <input type="hidden" name="delivery_note_id" value="{{ $deliveryNote->id }}">
                                    @endif
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="diverse_customer_name">{{ \App\Helpers\TranslationHelper::transFromDatabase('Diverse Customer Name', __('اسم العميل المتنوع')) }}</label>
                                    <input type="text" name="diverse_customer_name" id="diverse_customer_name" class="form-control @error('diverse_customer_name') is-invalid @enderror" value="{{ old('diverse_customer_name') }}">
                                    @error('diverse_customer_name')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="invoice_number">{{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Number', __('Invoice Number')) }} <span class="text-danger">*</span></label>
                                    <input type="text" name="invoice_number" id="invoice_number" class="form-control bg-light @error('invoice_number') is-invalid @enderror" value="{{ $nextInvoiceNumber }}" readonly>
                                    <small class="form-text text-muted">{{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Number is Auto Generated', __('Invoice Number is Auto Generated')) }}</small>
                                    @error('invoice_number')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="invoice_date">{{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Date', __('Invoice Date')) }} <span class="text-danger">*</span></label>
                                    <input type="date" name="invoice_date" id="invoice_date" class="form-control @error('invoice_date') is-invalid @enderror" value="{{ old('invoice_date', date('Y-m-d')) }}" required>
                                    @error('invoice_date')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="due_date">{{ \App\Helpers\TranslationHelper::transFromDatabase('Due Date', __('Due Date')) }}</label>
                                    <input type="date" name="due_date" id="due_date" class="form-control @error('due_date') is-invalid @enderror" value="{{ old('due_date', date('Y-m-d', strtotime('+30 days'))) }}">
                                    @error('due_date')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="form-group mt-4">
                            <h5>{{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Items', __('Invoice Items')) }} <span class="text-danger">*</span></h5>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm" id="itemsTable">
                                    <thead class="bg-light">
                                        <tr>
                                            <th>{{ \App\Helpers\TranslationHelper::transFromDatabase('Item Name', __('Item Name')) }}</th>
                                            <th style="width: 115px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Item Unit', __('Item Unit')) }}</th>
                                            <th style="width: 180px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Description', __('Description')) }}</th>
                                            <th style="width: 95px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Quantity', __('Quantity')) }}</th>
                                            <th style="width: 115px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Unit Price', __('Unit Price')) }}</th>
                                            <th style="width: 90px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Discount %', __('Discount %')) }}</th>
                                            <th style="width: 90px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Tax %', __('Tax %')) }}</th>
                                            <th style="width: 100px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('WHT %', __('خصم/إضافة %')) }}</th>
                                            <th style="width: 105px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Line Total', __('Line Total')) }}</th>
                                            <th style="width: 100px; text-align: center;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Actions', __('Actions')) }}</th>
                                        </tr>
                                    </thead>
                                    <tbody id="itemsBody">
                                    </tbody>
                                </table>
                            </div>
                            <button type="button" class="btn btn-sm btn-primary" id="addItemBtn">
                                <i class="fas fa-plus"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Add Item', __('Add Item')) }}
                            </button>
                        </div>

                        <div class="row mt-4">
                            <div class="col-md-8"></div>
                            <div class="col-md-4">
                                <div class="card bg-light">
                                    <div class="card-body p-3">
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Subtotal', __('Subtotal')) }}:</span>
                                            <strong><span id="subtotalDisplay">0.00</span></strong>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Total Discount', __('Total Discount')) }}:</span>
                                            <strong><span id="totalDiscountDisplay">0.00</span></strong>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Total Tax', __('Total Tax')) }}:</span>
                                            <strong><span id="totalTaxDisplay">0.00</span></strong>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Total WHT', __('إجمالي الخصم والإضافة')) }}:</span>
                                            <strong><span id="totalWHTDisplay">0.00</span></strong>
                                        </div>
                                        <hr>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="font-weight-bold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Total Amount', __('Total Amount')) }}:</span>
                                            <strong class="text-primary"><span id="totalDisplay">0.00</span></strong>
                                        </div>
                                        <div class="d-flex justify-content-between">
                                            <span class="font-weight-bold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Net Payable', __('صافي المستحق')) }}:</span>
                                            <strong class="text-success"><span id="netPayableDisplay">0.00</span></strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="notes">{{ \App\Helpers\TranslationHelper::transFromDatabase('Notes', __('Notes')) }}</label>
                                    <textarea name="notes" id="notes" class="form-control @error('notes') is-invalid @enderror" rows="4">{{ old('notes') }}</textarea>
                                    @error('notes')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="attachment">{{ \App\Helpers\TranslationHelper::transFromDatabase('Attachment', __('Attachment')) }}</label>
                                    <input type="file" name="attachment" id="attachment" class="form-control-file @error('attachment') is-invalid @enderror">
                                    @error('attachment')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col-md-12">
                                <button type="submit" id="submitBtn" class="btn btn-success">
                                    <i class="fas fa-save"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Save Invoice', __('Save Invoice')) }}
                                </button>
                                <a href="{{ route('customer-invoices.index') }}" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Cancel', __('Cancel')) }}
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
    <h4 class="text-success font-weight-bold">جارٍ حفظ الفاتورة...</h4>
    <p class="text-muted">يرجى الانتظار، قد يستغرق الأمر لحظات</p>
</div>

<input type="hidden" id="itemsData" name="itemsData">

<script>
let itemCount = 0;

document.getElementById('addItemBtn').addEventListener('click', function() {
    const tbody = document.getElementById('itemsBody');
    const row = createItemRow(itemCount++);
    tbody.appendChild(row);
    attachItemEventListeners();
});

function createItemRow(inde, data = null) {
    const row = document.createElement('tr');
    const itemsOptions = document.getElementById('itemsData').value ? JSON.parse(document.getElementById('itemsData').value) : {!! json_encode($items->map(fn($item) => ['id' => $item->id, 'name' => $item->name])->toArray()) !!};

    let itemSelect = '<select name="items[' + inde + '][item_id]" class="form-control form-control-sm item-select" data-index="' + inde + '">';
    itemSelect += '<option value="">-- اختر الصنف --</option>';
    itemsOptions.forEach(item => {
        const selected = data && data.item_id == item.id ? 'selected' : '';
        itemSelect += '<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>';
    });
    itemSelect += '</select>';

    const description = data && data.description ? data.description : '';
    const quantity = data && data.quantity ? data.quantity : '';
    const price = data && data.unit_price ? data.unit_price : '';
    const tax = data && data.tax_rate ? data.tax_rate : '15';
    const wht = data && data.withholding_tax_rate ? data.withholding_tax_rate : '0';

    row.innerHTML = `
        <td>
            ${itemSelect}
        </td>
        <td>
            <select name="items[${inde}][item_unit_id]" class="form-control form-control-sm item-unit-select" data-index="${inde}">
                <option value="">-- اختر الوحدة --</option>
            </select>
        </td>
        <td>
            <textarea name="items[${inde}][description]" class="form-control form-control-sm item-description" placeholder="وصف البند" rows="2" style="resize: vertical; min-height: 38px;">${description}</textarea>
        </td>
        <td>
            <input type="number" name="items[${inde}][quantity]" class="form-control form-control-sm item-qty" step="0.01" min="0.01" placeholder="0.00" value="${quantity}" required>
        </td>
        <td>
            <input type="number" name="items[${inde}][unit_price]" class="form-control form-control-sm item-price" step="0.01" min="0" placeholder="0.00" value="${price}" required>
        </td>
        <td>
            <input type="number" name="items[${inde}][discount_amount]" class="form-control form-control-sm item-discount" step="0.01" min="0" max="100" placeholder="0" value="0">
            <input type="hidden" name="items[${inde}][discount_type]" value="percentage">
        </td>
        <td>
            <input type="number" name="items[${inde}][tax_rate]" class="form-control form-control-sm item-tax" data-index="${inde}" step="0.01" min="0" max="100" placeholder="15" value="${tax}">
        </td>
        <td>
            <input type="number" name="items[${inde}][withholding_tax_rate]" class="form-control form-control-sm item-wht" data-index="${inde}" step="0.01" min="0" max="100" placeholder="0" value="${wht}">
        </td>
        <td>
            <span class="item-total">0.00</span>
        </td>
        <td class="text-center">
            <button type="button" class="btn btn-sm btn-danger remove-item" title="حذف هذا البند" data-toggle="tooltip" data-placement="top" style="padding: 8px 12px; white-space: nowrap; min-width: 100px;">
                <i class="fas fa-trash-alt mr-2"></i>
                <span>حذف</span>
            </button>
        </td>
    `;
    return row;
}

function attachItemEventListeners() {
    document.querySelectorAll('.item-select').forEach(select => {
        select.addEventListener('change', function() {
            const index = this.dataset.index;
            const itemId = this.value;

            const unitSelect = document.querySelector(`.item-unit-select[data-index="${index}"]`);
            unitSelect.innerHTML = '<option value="">-- اختر الوحدة --</option>';

            if (itemId) {
                const targetUnitId = this.dataset.targetUnitId || null;
                delete this.dataset.targetUnitId;

                // جلب الوحدات ونسبة الضريبة من الصنف
                fetch(`{{ route("inventory.items.units.api", ":itemId") }}`.replace(':itemId', itemId), { credentials: 'same-origin' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.data && data.data.length > 0) {
                            let defaultUnitId = null;
                            
                            // إضافة الوحدات وتحديد الافتراضية
                            data.data.forEach(unit => {
                                const option = document.createElement('option');
                                option.value = unit.item_unit_id;
                                option.textContent = unit.unit_name;
                                unitSelect.appendChild(option);
                                
                                // حفظ معرف الوحدة الافتراضية
                                if (unit.is_default) {
                                    defaultUnitId = unit.item_unit_id;
                                }
                            });
                            
                            // اختيار الوحدة المطلوبة أو الافتراضية أو الأولى
                            if (targetUnitId) {
                                unitSelect.value = targetUnitId;
                            } else if (defaultUnitId) {
                                unitSelect.value = defaultUnitId;
                                console.log(`✅ تم اختيار الوحدة الافتراضية: ${defaultUnitId}`);
                            } else if (data.data.length > 0) {
                                unitSelect.value = data.data[0].item_unit_id;
                                console.log(`✅ تم اختيار أول وحدة: ${data.data[0].item_unit_id}`);
                            }
                            
                            // تطبيق حدث التغيير لتحديث البيانات الأخرى
                            unitSelect.dispatchEvent(new Event('change'));
                        }
                    })
                    .catch(error => console.error('Error:', error));
                
                // جلب نسبة الضريبة من الصنف وتحديثها في الحقل
                fetch(`{{ route("inventory.items.data", ":itemId") }}`.replace(':itemId', itemId), { 
                    credentials: 'same-origin',
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data && data.tax_rate) {
                            const taxInput = document.querySelector(`.item-tax[data-index="${index}"]`);
                            if (taxInput && !taxInput.value) {
                                taxInput.value = data.tax_rate;
                                taxInput.dispatchEvent(new Event('change'));
                            }
                        }
                    })
                    .catch(error => console.error('Error loading tax rate:', error));
            }
        });
    });

    document.querySelectorAll('.item-qty, .item-price, .item-discount, .item-tax, .item-wht').forEach(input => {
        input.addEventListener('change', updateTotals);
        input.addEventListener('keyup', updateTotals);
    });
}

function updateTotals() {
    let grandTotal = 0;
    let totalDiscount = 0;
    let totalTax = 0;
    let totalWHT = 0;

    document.querySelectorAll('#itemsBody tr').forEach(row => {
        const qty = parseFloat(row.querySelector('.item-qty').value) || 0;
        const price = parseFloat(row.querySelector('.item-price').value) || 0;
        const discount = parseFloat(row.querySelector('.item-discount').value) || 0;
        const tax = parseFloat(row.querySelector('.item-tax').value) || 0;
        const wht = parseFloat(row.querySelector('.item-wht').value) || 0;

        const subtotal = qty * price;
        const discountAmount = (subtotal * discount) / 100;
        const afterDiscount = subtotal - discountAmount;
        const taxAmount = (afterDiscount * tax) / 100;
        const whtAmount = (afterDiscount * wht) / 100;
        const itemTotal = afterDiscount + taxAmount;

        row.querySelector('.item-total').textContent = itemTotal.toFixed(2);

        grandTotal += subtotal;
        totalDiscount += discountAmount;
        totalTax += taxAmount;
        totalWHT += whtAmount;
    });

    const totalAmount = grandTotal - totalDiscount + totalTax;
    const netPayable = totalAmount - totalWHT;

    document.getElementById('subtotalDisplay').textContent = grandTotal.toFixed(2);
    document.getElementById('totalDiscountDisplay').textContent = totalDiscount.toFixed(2);
    document.getElementById('totalTaxDisplay').textContent = totalTax.toFixed(2);
    document.getElementById('totalWHTDisplay').textContent = totalWHT.toFixed(2);
    document.getElementById('totalDisplay').textContent = totalAmount.toFixed(2);
    document.getElementById('netPayableDisplay').textContent = netPayable.toFixed(2);
}

attachItemEventListeners();

// ✅ استعادة البيانات القديمة أو تعبئة بيانات من أمر معمل
function initializeInvoiceItems() {
    console.log("Initializing invoice items...");
    const oldItems = {!! json_encode(old('items', [])) !!};
    const mappedItems = {!! isset($mappedItems) ? json_encode($mappedItems) : '[]' !!};
    const labOrderItems = {!! isset($labOrder) ? json_encode($labOrder->items->map(function($item) use ($labOrder) {
        return [
            'item_id' => null, 
            'description' => $item->service->name . ' -- ' . ($labOrder->patient_name ?? ($labOrder->patient->name ?? '')),
            'quantity' => 1,
            'unit_price' => $item->unit_price,
            'tax_rate' => 15,
        ];
    })) : '[]' !!};
    
    console.log("Old Items:", oldItems);
    console.log("Mapped Items (SO):", mappedItems);
    console.log("Lab Order Items:", labOrderItems);

    let itemsToLoad = [];
    if (oldItems && Array.isArray(oldItems) && oldItems.length > 0) {
        itemsToLoad = oldItems;
    } else if (mappedItems && Array.isArray(mappedItems) && mappedItems.length > 0) {
        itemsToLoad = mappedItems;
    } else if (labOrderItems && Array.isArray(labOrderItems) && labOrderItems.length > 0) {
        itemsToLoad = labOrderItems;
    }
    
    if (itemsToLoad.length > 0) {
        console.log("Loading items into table...", itemsToLoad);
        const tbody = document.getElementById('itemsBody');
        tbody.innerHTML = '';
        itemCount = 0;
        
        itemsToLoad.forEach((item) => {
            const row = createItemRow(itemCount++, item);
            tbody.appendChild(row);
        });

        attachItemEventListeners();

        const rows = tbody.querySelectorAll('tr');
        itemsToLoad.forEach((item, idx) => {
            const row = rows[idx];
            if (item.item_id) {
                const itemSelect = row.querySelector('.item-select');
                if (item.item_unit_id || item.unit_id) {
                    itemSelect.dataset.targetUnitId = item.item_unit_id || item.unit_id;
                }
                itemSelect.dispatchEvent(new Event('change'));
            }
        });

        updateTotals();
    } else {
        console.log("No items to load, adding empty row.");
        document.getElementById('addItemBtn').click();
    }
}

if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initializeInvoiceItems);
} else {
    initializeInvoiceItems();
}

// التعامل مع حذف الصفوف
document.addEventListener('click', function(e) {
    if (e.target.closest('.remove-item')) {
        const row = e.target.closest('tr');
        const itemCount = document.querySelectorAll('#itemsBody tr').length;
        
        if (itemCount <= 1) {
            alert('يجب أن تحتوي الفاتورة على بند واحد على الأقل!');
            return;
        }
        
        if (confirm('هل تريد بالفعل حذف هذا البند؟')) {
            row.remove();
            updateTotals();
        }
    }
});

// تفعيل Tooltips
if (typeof $ !== 'undefined') {
    $(document).ready(function() {
        $(function () {
            $('[data-toggle="tooltip"]').tooltip()
        })

        $('#auto_warehouse_issue').change(function() {
            if ($(this).is(':checked')) {
                $('#warehouse_selector_container').show();
                $('#warehouse_id').attr('required', true);
            } else {
                $('#warehouse_selector_container').hide();
                $('#warehouse_id').attr('required', false);
            }
        });

        // تحديث رقم حساب العميل عند الاختيار
        $('#customer_id').change(function() {
            const selectedOption = $(this).find('option:selected');
            const accountCode = selectedOption.data('account-code') || '';
            $('#customer_account_number').val(accountCode);
        });

        // تشغيل التحديث عند تحميل الصفحة في حال كان هناك عميل مختار
        $('#customer_id').trigger('change');

        // Trigger change to set initial state
        $('#auto_warehouse_issue').trigger('change');

        // منع تكرار الحفظ عند الضغط المتعدد
        $('#invoiceForm').on('submit', function() {
            const submitBtn = $('#submitBtn');
            
            // التحقق من صحة النموذج قبل التعطيل
            if (this.checkValidity()) {
                // تعطيل الزر وتغيير النص
                submitBtn.prop('disabled', true);
                submitBtn.html('<i class="fas fa-spinner fa-spin"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase("Saving...", "جارٍ الحفظ...") }}');
                
                // إظهار شاشة التحميل
                $('#loadingOverlay').css('display', 'flex');
                
                return true;
            }
            return false;
        });
    });
}
</script>

@endsection
