@extends('layouts.app')

@section('content')
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="fw-light">{{ __('Create New Invoice') }}</h2>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">{{ __('Dashboard') }}</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('accounting.invoices.index') }}">{{ __('Invoices') }}</a>
                    </li>
                    <li class="breadcrumb-item active" aria-current="page">{{ __('Create') }}</li>
                </ol>
            </nav>
        </div>
    </div>

    <form action="{{ route('accounting.invoices.store') }}" method="POST" id="invoiceForm">
        @csrf
        
        <!-- Top Section: Invoice Details -->
        <div class="card mb-4 shadow-sm border-secondary">
            <div class="card-header bg-dark text-white border-secondary py-3">
                <h5 class="mb-0">
                    <i class="fas fa-file-invoice me-2 text-primary"></i> {{ __('Invoice Details') }}
                </h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <!-- Client -->
                    <div class="col-md-3">
                        <label class="form-label">{{ __('Client') }} <span class="text-danger">*</span></label>
                        <select name="customer_id" id="customerSelect" class="form-select" required>
                            <option value="">{{ __('Select Customer') }}</option>
                            @foreach($customers as $customer)
                                <option value="{{ $customer->id }}">{{ $customer->name }}
                                    ({{ __($customer->company ?? 'Individual') }})</option>
                            @endforeach
                        </select>
                        <div class="form-text"><a href="{{ route('customers.create') }}"
                                class="text-info">{{ __('Create new customer') }}</a></div>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label fw-bold">{{ __('Invoice Number') }}</label>
                        <input type="text" name="code" class="form-control" value="{{ $code }}" readonly>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold">{{ __('Invoice Date') }} <span class="text-danger">*</span></label>
                        <input type="date" name="date" class="form-control" value="{{ date('Y-m-d') }}" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold">{{ __('Due Date') }}</label>
                        <input type="date" name="due_date" class="form-control">
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <div class="form-check form-switch mb-2">
                            <input class="form-check-input" type="checkbox" name="is_tax_invoice" id="isTaxInvoice" value="1">
                            <label class="form-check-label fw-bold text-danger" for="isTaxInvoice">
                                <i class="fas fa-file-invoice-dollar me-1"></i> {{ __('Tax Invoice') }}
                            </label>
                        </div>
                    </div>

                    <!-- Currency & Rate -->
                    <div class="col-md-3">
                        <label class="form-label">{{ __('Currency') }}</label>
                        <select name="currency_id" id="currencySelect" class="form-select">
                            @foreach($currencies as $currency)
                                <option value="{{ $currency->id }}" data-rate="{{ $currency->exchange_rate }}" 
                                    {{ $currency->is_base ? 'selected' : '' }}>
                                    {{ $currency->code }} - {{ $currency->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">{{ __('Exchange Rate') }}</label>
                        <input type="number" name="exchange_rate" id="exchangeRateInput" 
                            class="form-control" step="0.000001" min="0" 
                            value="{{ $defaultCurrency ? $defaultCurrency->exchange_rate : 1 }}" readonly>
                    </div>

                    <!-- Sales Person -->
                    <div class="col-md-3">
                        <label class="form-label">{{ __('Sales Person (Optional)') }}</label>
                        <select name="sales_person_id" class="form-select">
                            <option value="">{{ __('None') }}</option>
                            @foreach($salesPeople as $sp)
                                <option value="{{ $sp->id }}">{{ $sp->name }}</option>
                            @endforeach
                        </select>
                    </div>

                    <!-- Commission -->
                    <div class="col-md-3">
                        <label class="form-label">{{ __('Commission Amount (EGP)') }}</label>
                        <input type="number" name="commission_amount" class="form-control" step="0.01" value="0">
                    </div>
                </div>
            </div>
        </div>

        <!-- Middle Section: Items -->
        <div class="card mb-4 shadow-sm border-secondary">
            <div class="card-header bg-dark text-white border-secondary py-3">
                <h5 class="mb-0">
                    <i class="fas fa-list-ul me-2 text-success"></i> {{ __('Invoice Items') }}
                </h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered border-secondary mb-0" id="itemsTable">
                        <thead class="table-dark">
                            <tr>
                                <th class="py-3" style="width: 20%">
                                    <i class="fas fa-box me-1 small"></i> {{ __('Product/Service') }}
                                </th>
                                <th class="py-3" style="width: 25%">
                                    <i class="fas fa-align-left me-1 small"></i> {{ __('Description') }}
                                </th>
                                <th class="py-3" style="width: 10%">
                                    <i class="fas fa-weight-hanging me-1 small"></i> {{ __('Unit') }}
                                </th>
                                <th class="py-3" style="width: 15%">
                                    <i class="fas fa-key me-1 small"></i> {{ __('Serial/License') }}
                                </th>
                                <th class="py-3 text-center" style="width: 8%">
                                    <i class="fas fa-hashtag me-1 small"></i> {{ __('Qty') }}
                                </th>
                                <th class="py-3 text-end" style="width: 12%">
                                    <i class="fas fa-tag me-1 small"></i> {{ __('Unit Price') }}
                                </th>
                                <th class="py-3 text-end" style="width: 10%">
                                    <i class="fas fa-coins me-1 small"></i> {{ __('Total') }}
                                </th>
                                <th style="width: 50px"></th>
                            </tr>
                        </thead>
                        <tbody id="itemsBody">
                            <tr class="item-row">
                                <td>
                                    <select name="items[0][product_id]" class="form-select product-select" onchange="fillProductData(this)">
                                        <option value="">{{ __('Select or type below') }}</option>
                                        @foreach($products as $product)
                                            <option value="{{ $product->id }}" data-name="{{ $product->name }}"
                                                data-price="{{ $product->price }}"
                                                data-price-usd="{{ $product->price_usd ?? 0 }}"
                                                data-description="{{ $product->description }}"
                                                data-unit-id="{{ $product->unit_id }}">
                                                {{ $product->name }} ({{ number_format($product->price, 2) }}
                                                {{ __('EGP') }} / {{ $product->price_usd ? number_format($product->price_usd, 2) . ' USD' : '-' }})
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>
                                    <textarea name="items[0][description]"
                                        class="form-control description-input mb-1"
                                        placeholder="{{ __('Item description') }}" rows="2" required></textarea>

                                    <div class="row g-1 date-range d-none">
                                        <div class="col-6">
                                            <input type="date" name="items[0][start_date]"
                                                class="form-control form-control-sm" placeholder="{{ __('From') }}">
                                        </div>
                                        <div class="col-6">
                                            <input type="date" name="items[0][end_date]"
                                                class="form-control form-control-sm" placeholder="{{ __('To') }}">
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <select name="items[0][unit_id]" class="form-select unit-select"
                                        onchange="checkUnitType(this)">
                                        <option value="">{{ __('None') }}</option>
                                        @foreach($units as $u)
                                            <option value="{{ $u->id }}" data-type="{{ $u->type }}">{{ $u->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>
                                    <input type="text" name="items[0][serial_key]" class="form-control"
                                        placeholder="{{ __('Serial/License') }}">
                                </td>
                                <td>
                                    <input type="number" name="items[0][quantity]" class="form-control qty-input"
                                        value="1" step="0.01" min="0.01" required>
                                </td>
                                <td>
                                    <input type="number" name="items[0][unit_price]"
                                        class="form-control price-input" value="0" step="0.01" min="0" required>
                                </td>
                                <td>
                                    <input type="text" class="form-control-plaintext text-end total-display"
                                        value="0.00" readonly>
                                </td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-outline-danger btn-sm remove-row" disabled>
                                        <i class="fas fa-times"></i>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="mt-3">
                    <button type="button" class="btn btn-outline-success btn-sm" id="addItemBtn">
                        <i class="fas fa-plus me-1"></i> {{ __('Add Line Item') }}
                    </button>
                </div>
            </div>
        </div>

        <!-- Bottom Section: Payments, Notes & Totals -->
        <div class="row g-4">
            <!-- Left Column: Payment & Notes -->
            <div class="col-lg-7">
                <!-- Payment Details Card -->
                <div class="card mb-4 border-success shadow-sm">
                    <div class="card-header bg-success text-white py-3">
                        <h5 class="mb-0">
                            <i class="fas fa-wallet me-2"></i> {{ __('Payment Details') }}
                        </h5>
                    </div>
                    <div class="card-body">
                        <!-- Group 1: Cash/Bank -->
                        <div class="p-3 rounded mb-3 border-start border-4 border-success shadow-xs" style="background: rgba(40, 167, 69, 0.03);">
                            <h6 class="text-success mb-3 fw-bold">
                                <i class="fas fa-money-bill-wave me-1"></i> {{ __('Cash/Bank Payment') }}
                            </h6>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label fw-bold">{{ __('Cash/Bank Amount') }}</label>
                                    <input type="number" name="amount" id="cashAmount" class="form-control payment-input" step="0.01" value="0">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-bold">{{ __('Treasury') }}</label>
                                    <select name="treasury_id" class="form-select">
                                        <option value="">{{ __('Select Treasury') }}</option>
                                        @foreach($treasuries as $treasury)
                                            <option value="{{ $treasury->id }}">
                                                {{ $treasury->name }} ({{ number_format($treasury->balance, 2) }} {{ $treasury->currency->code ?? '' }})
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-12">
                                    <div class="row align-items-center">
                                        <div class="col-md-6">
                                            <label class="form-label small mb-0">{{ __('Payment Exchange Rate') }}</label>
                                            <input type="number" name="payment_exchange_rate" id="paymentExchangeRate" class="form-control form-control-sm" step="0.000001" value="1">
                                        </div>
                                        <div class="col-md-6">
                                            <small class="text-muted d-block mt-3">
                                                <i class="fas fa-info-circle me-1"></i> {{ __('Rate to base currency if different from invoice') }}
                                            </small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Group 2: Wallet & Points -->
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="p-3 rounded border-start border-4 border-primary h-100 shadow-xs" style="background: rgba(0, 123, 255, 0.03);">
                                    <h6 class="text-primary mb-3 fw-bold">
                                        <i class="fas fa-user-tag me-1"></i> {{ __('Wallet Deduction') }}
                                    </h6>
                                    <div class="input-group">
                                        <input type="number" name="wallet_amount" id="walletAmount" class="form-control payment-input" step="0.01" value="0">
                                        <span class="input-group-text bg-white">
                                            <small>{{ __('Available:') }}</small>
                                            <span id="availableWallet" class="ms-1 fw-bold text-success">0.00</span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="p-3 rounded border-start border-4 border-info h-100 shadow-xs" style="background: rgba(23, 162, 184, 0.03);">
                                    <h6 class="text-info mb-3 fw-bold">
                                        <i class="fas fa-star me-1"></i> {{ __('Redeem Points') }}
                                    </h6>
                                    <div class="input-group">
                                        <input type="number" name="redeem_points" id="redeemPoints" class="form-control payment-input" step="0.01" value="0">
                                        <span class="input-group-text bg-white">
                                            <small>{{ __('Points:') }}</small>
                                            <span id="availablePoints" class="ms-1 fw-bold text-info">0.00</span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Notes Card -->
                <div class="card border-secondary shadow-sm">
                    <div class="card-header bg-dark text-white py-3">
                        <h5 class="mb-0">
                            <i class="fas fa-sticky-note me-2"></i> {{ __('Notes / Terms') }}
                        </h5>
                    </div>
                    <div class="card-body p-0">
                        <textarea name="notes" class="form-control border-0 rounded-0" rows="4"
                            placeholder="{{ __('Payment terms, bank details, etc.') }}" style="resize: none;"></textarea>
                    </div>
                </div>
            </div>

            <!-- Right Column: Summary & Totals -->
            <div class="col-lg-5">
                <div class="card border-primary shadow-lg overflow-hidden">
                    <div class="card-header bg-primary text-white py-3">
                        <h5 class="mb-0 text-center">
                            <i class="fas fa-file-invoice-dollar me-2"></i> {{ __('Invoice Summary') }}
                        </h5>
                    </div>
                    <div class="card-body p-4 bg-dark text-light">
                        <div class="d-flex justify-content-between mb-3 fs-5">
                            <span class="text-secondary">{{ __('Subtotal') }}:</span>
                            <span class="fw-bold fs-4" id="subtotalDisplay">0.00</span>
                        </div>
                        
                        <div class="row align-items-center mb-3">
                            <div class="col-6">
                                <span class="text-secondary">{{ __('VAT (%)') }}:</span>
                            </div>
                            <div class="col-6">
                                <div class="input-group input-group-sm">
                                    <input type="number" name="tax_percent" id="taxInput"
                                        class="form-control text-end bg-dark text-light border-secondary" value="14">
                                    <span class="input-group-text bg-secondary text-white border-secondary">%</span>
                                </div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between mb-3 border-bottom border-secondary pb-3">
                            <span class="text-info small">{{ __('Tax Amount') }}:</span>
                            <span class="fw-bold text-info" id="taxDisplay">0.00</span>
                        </div>

                        <!-- Adjustments -->
                        <div class="row g-2 mb-3">
                            <div class="col-12">
                                <label class="small text-secondary mb-1 d-block">{{ __('Discount') }}</label>
                                <div class="input-group input-group-sm">
                                    <select name="discount_type" id="discountType" class="form-select bg-dark text-light border-secondary w-25">
                                        <option value="fixed">{{ __('Fixed') }}</option>
                                        <option value="percent">{{ __('%') }}</option>
                                    </select>
                                    <input type="number" name="discount_value" id="discountInput" class="form-control bg-dark text-light border-secondary text-end" value="0" min="0" step="0.01">
                                </div>
                            </div>
                            <div class="col-12 mt-3">
                                <label class="small text-secondary mb-1 d-block">{{ __('Shipping') }}</label>
                                <input type="number" name="shipping_amount" id="shippingInput" class="form-control form-control-sm bg-dark text-light border-secondary text-end" value="0" min="0" step="0.01">
                            </div>
                            <div class="col-12 mt-3">
                                <label class="small text-secondary mb-1 d-block">{{ __('Extra Exp') }}</label>
                                <div class="input-group input-group-sm">
                                    <input type="text" name="extra_expenses_note" class="form-control bg-dark text-light border-secondary w-50" placeholder="{{ __('Note') }}">
                                    <input type="number" name="extra_expenses_amount" id="extraExpensesInput" class="form-control bg-dark text-light border-secondary text-end" value="0" min="0" step="0.01">
                                </div>
                            </div>
                        </div>

                        <div class="bg-primary bg-opacity-10 p-4 rounded border border-primary mt-4">
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="fs-4 fw-bold text-white">{{ __('Total') }}</span>
                                <div class="text-end">
                                    <span class="fs-2 fw-bold text-primary d-block font-monospace" id="grandTotalDisplay">0.00</span>
                                    <small class="text-secondary currency-code-display">{{ $defaultCurrency ? $defaultCurrency->code : 'EGP' }}</small>
                                </div>
                            </div>
                        </div>

                        <div class="mt-4">
                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary btn-lg shadow">
                                    <i class="fas fa-check-circle me-2"></i> {{ __('Create Invoice') }}
                                </button>
                                <a href="{{ route('accounting.invoices.index') }}"
                                    class="btn btn-outline-secondary">
                                    <i class="fas fa-times me-2"></i> {{ __('Cancel') }}
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <datalist id="productsList">
        @foreach($products as $product)
            <option value="{{ $product->name }}">{{ $product->price }} EGP</option>
        @endforeach
    </datalist>

    <script>
        // Product data
        const productsData = @json($products->keyBy('id'));

        function checkUnitType(selectElement) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            const type = selectedOption.getAttribute('data-type');
            const row = selectElement.closest('.item-row');
            const dateRange = row.querySelector('.date-range');

            if (type === 'time') {
                dateRange.classList.remove('d-none');
            } else {
                dateRange.classList.add('d-none');
                row.querySelectorAll('.date-range input').forEach(input => input.value = '');
            }
        }

        function fillProductData(selectElement) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            const row = selectElement.closest('.item-row');
            
            // Get selected Quote Currency code (simple check)
            const currencySelect = document.getElementById('currencySelect');
            const selectedCurrencyText = currencySelect ? currencySelect.options[currencySelect.selectedIndex].text : 'EGP';
            let useUsd = false;
            // Check if selected currency text contains "USD" or "Dollar" or code check if available
            // Better: Check if currency is NOT base and assume users put USD price for foreign?
            // User requested explicit "EGP and Dollar".
            
            // We can match currency Code if we had it in ID or data. 
            // In currency loop we printed Code - Name.
            // Let's rely on simple string check for "USD"
            if (selectedCurrencyText.includes('USD') || selectedCurrencyText.includes('Dollar')) {
                useUsd = true;
            }

            if (selectedOption.value) {
                const productName = selectedOption.getAttribute('data-name');
                const productPrice = selectedOption.getAttribute('data-price');
                const productPriceUsd = selectedOption.getAttribute('data-price-usd');
                const productDescription = selectedOption.getAttribute('data-description');
                const productUnitId = selectedOption.getAttribute('data-unit-id');

                // Fill description
                row.querySelector('.description-input').value = productDescription || productName;
                
                // Fill price
                let finalPrice = parseFloat(productPrice);
                if (useUsd && parseFloat(productPriceUsd) > 0) {
                    finalPrice = parseFloat(productPriceUsd);
                } else if (useUsd) {
                    // If USD needed but no USD price, maybe convert using exchange rate?
                    // Optional: rate = parseFloat(document.getElementById('exchangeRateInput').value);
                    // finalPrice = finalPrice / rate; 
                    // But usually users want base price if not defined.
                }
                
                row.querySelector('.price-input').value = finalPrice.toFixed(2);

                // Select Unit
                const unitSelect = row.querySelector('.unit-select');
                if (productUnitId) {
                    unitSelect.value = productUnitId;
                } else {
                    unitSelect.selectedIndex = 0;
                }
                checkUnitType(unitSelect);

                // Recalculate totals
                calculateTotals();
            }
        }

        document.addEventListener('DOMContentLoaded', function () {
            let itemIndex = 1;
            const tableBody = document.getElementById('itemsBody');
            const addItemBtn = document.getElementById('addItemBtn');

            function calculateTotals() {
                let subtotal = 0;

                document.querySelectorAll('.item-row').forEach(row => {
                    const qty = parseFloat(row.querySelector('.qty-input').value) || 0;
                    const price = parseFloat(row.querySelector('.price-input').value) || 0;
                    const total = qty * price;

                    row.querySelector('.total-display').value = total.toFixed(2);
                    subtotal += total;
                });

                const taxPercent = parseFloat(document.getElementById('taxInput').value) || 0;
                const taxAmount = (subtotal * taxPercent) / 100;

                // Discount
                const discountType = document.getElementById('discountType').value;
                let discountValue = parseFloat(document.getElementById('discountInput').value) || 0;
                let discountAmount = 0;

                if (discountType === 'percent') {
                    discountAmount = (subtotal * discountValue) / 100;
                } else {
                    discountAmount = discountValue;
                }

                // Expenses
                const shippingAmount = parseFloat(document.getElementById('shippingInput').value) || 0;
                const extraExpensesAmount = parseFloat(document.getElementById('extraExpensesInput').value) || 0;

                const grandTotal = subtotal + taxAmount - discountAmount + shippingAmount + extraExpensesAmount;

                document.getElementById('subtotalDisplay').textContent = subtotal.toFixed(2);
                document.getElementById('taxDisplay').textContent = taxAmount.toFixed(2);
                document.getElementById('grandTotalDisplay').textContent = grandTotal.toFixed(2);
            }

            // Make it global for fillProductData to call
            window.calculateTotals = calculateTotals;

            // Event delegation for calculations
            document.getElementById('itemsTable').addEventListener('input', function (e) {
                if (e.target.classList.contains('qty-input') || e.target.classList.contains('price-input')) {
                    calculateTotals();
                }
            });

            // Trigger calculation on other inputs
            document.getElementById('taxInput').addEventListener('input', calculateTotals);
            document.getElementById('discountInput').addEventListener('input', calculateTotals);
            document.getElementById('discountType').addEventListener('change', calculateTotals);
            document.getElementById('shippingInput').addEventListener('input', calculateTotals);
            document.getElementById('extraExpensesInput').addEventListener('input', calculateTotals);

            document.getElementById('taxInput').addEventListener('input', calculateTotals);

            // Currency Change
            document.getElementById('currencySelect').addEventListener('change', function() {
                const selectedOption = this.options[this.selectedIndex];
                const rate = selectedOption.getAttribute('data-rate');
                const rateInput = document.getElementById('exchangeRateInput');
                rateInput.value = rate;
                
                // Optional: If you want to allow custom rates for foreign currencies
                 if (parseFloat(rate) !== 1.0) {
                     rateInput.removeAttribute('readonly');
                 } else {
                     rateInput.setAttribute('readonly', true);
                 }
                 // Actually, let's always allow editing unless it's base? Or maybe just allow editing.
                 // For now, let's make it editable if not base, or always editable.
                 rateInput.readOnly = false; 
            });

            // Fetch Customer Data (Balance & Points)
            const customerSelect = document.getElementById('customerSelect');
            customerSelect.addEventListener('change', function() {
                const customerId = this.value;
                if (!customerId) return;

                fetch(`{{ route('accounting.invoices.get-customer-data', ['customer' => ':id']) }}`.replace(':id', customerId))
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('availableWallet').textContent = parseFloat(data.balance).toFixed(2);
                        document.getElementById('availablePoints').textContent = parseFloat(data.loyalty_points).toFixed(2);
                        
                        // Set max values
                        document.getElementById('walletAmount').max = data.balance;
                        document.getElementById('redeemPoints').max = data.loyalty_points;
                    });
            });

            // Sync payment exchange rate with invoice rate initially
            document.getElementById('exchangeRateInput').addEventListener('input', function() {
                document.getElementById('paymentExchangeRate').value = this.value;
            });

            // Payment calculations
            document.querySelectorAll('.payment-input').forEach(input => {
                input.addEventListener('input', calculateTotals);
            });

            // Add Item
            addItemBtn.addEventListener('click', function () {
                const newRow = document.querySelector('.item-row').cloneNode(true);

                // Clear values
                newRow.querySelector('.product-select').selectedIndex = 0;
                newRow.querySelector('.description-input').value = '';
                newRow.querySelector('.unit-select').selectedIndex = 0;
                newRow.querySelector('.date-range').classList.add('d-none');
                newRow.querySelectorAll('.date-range input').forEach(i => i.value = '');
                newRow.querySelector('.qty-input').value = 1;
                newRow.querySelector('.price-input').value = 0;
                newRow.querySelector('.total-display').value = '0.00';

                // Clear serial key if exists
                const serialInput = newRow.querySelector('input[name*="serial_key"]');
                if (serialInput) serialInput.value = '';

                // Update names with new index
                const inputs = newRow.querySelectorAll('input, select, textarea');
                inputs.forEach(input => {
                    const currentName = input.getAttribute('name');
                    if (currentName) {
                        const newName = currentName.replace(/items\[\d+\]/, `items[${itemIndex}]`);
                        input.setAttribute('name', newName);
                    }
                });

                // Enable remove button
                newRow.querySelector('.remove-row').disabled = false;

                tableBody.appendChild(newRow);
                itemIndex++;
            });

            // Remove Item
            tableBody.addEventListener('click', function (e) {
                if (e.target.closest('.remove-row')) {
                    const row = e.target.closest('.item-row');
                    if (document.querySelectorAll('.item-row').length > 1) {
                        row.remove();
                        calculateTotals();
                    }
                }
            });
        });
    </script>
@endsection