<div class="row justify-content-center">
    <div class="col-lg-10">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="fas fa-file-invoice me-2"></i><?= lang('finance.create_invoice') ?></h5>
            </div>
            <div class="card-body">
                <form id="invoice-form" method="POST" action="/finance/invoices" data-ajax="true">
                    <?= csrf_field() ?>

                    <div class="row g-3 mb-4">
                        <div class="col-md-5">
                            <label class="form-label"><?= lang('finance.member') ?> <span class="text-danger">*</span></label>
                            <select name="member_id" id="member-select" class="form-select" required></select>
                            <div class="invalid-feedback" data-field="member_id"></div>
                            <div id="member-info" class="mt-2 small text-muted d-none"></div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label"><?= lang('finance.invoice_type') ?> <span class="text-danger">*</span></label>
                            <select name="invoice_type" class="form-select" required>
                                <option value="registration">Registration</option>
                                <option value="subscription" selected>Subscription</option>
                                <option value="renewal">Renewal</option>
                                <option value="transfer">Transfer</option>
                                <option value="freeze">Freeze</option>
                                <option value="penalty">Penalty</option>
                                <option value="sport">Sport</option>
                                <option value="facility">Facility</option>
                                <option value="guest">Guest</option>
                                <option value="card">Card</option>
                                <option value="carnet">Carnet</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><?= lang('finance.due_date') ?> <span class="text-danger">*</span></label>
                            <input type="date" name="due_date" class="form-control" value="<?= date('Y-m-d', strtotime('+30 days')) ?>" required>
                            <div class="invalid-feedback" data-field="due_date"></div>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <div class="form-check mt-2">
                                <input type="checkbox" name="issue_now" value="1" class="form-check-input" id="issue-now">
                                <label class="form-check-label" for="issue-now"><?= lang('finance.issue_immediately') ?></label>
                            </div>
                        </div>
                    </div>

                    <h6 class="mb-3"><?= lang('finance.line_items') ?></h6>
                    <div class="table-responsive mb-3">
                        <table class="table table-bordered" id="items-table">
                            <thead class="table-light">
                                <tr>
                                    <th style="width:25%"><?= lang('finance.fee_type') ?></th>
                                    <th style="width:20%"><?= lang('finance.description') ?></th>
                                    <th style="width:8%"><?= lang('finance.qty') ?></th>
                                    <th style="width:12%"><?= lang('finance.unit_price') ?></th>
                                    <th style="width:10%"><?= lang('finance.discount') ?></th>
                                    <th style="width:8%"><?= lang('finance.tax_rate') ?>%</th>
                                    <th style="width:12%"><?= lang('finance.total') ?></th>
                                    <th style="width:5%"></th>
                                </tr>
                            </thead>
                            <tbody id="items-body">
                                <tr class="item-row">
                                    <td>
                                        <select name="items[0][fee_type_id]" class="form-select form-select-sm fee-type-select">
                                            <option value="">-- <?= lang('finance.select_fee_type') ?> --</option>
                                            <?php foreach ($feeTypes as $ft): ?>
                                            <option value="<?= $ft['id'] ?>"><?= e($ft['name_en']) ?> (<?= e($ft['fee_code']) ?>)</option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="text" name="items[0][description_en]" class="form-control form-control-sm" placeholder="Description"></td>
                                    <td><input type="number" name="items[0][quantity]" class="form-control form-control-sm item-qty" value="1" min="1"></td>
                                    <td><input type="number" name="items[0][unit_price]" class="form-control form-control-sm item-price" step="0.01" value="0" min="0"></td>
                                    <td><input type="number" name="items[0][discount_amount]" class="form-control form-control-sm item-discount" step="0.01" value="0" min="0"></td>
                                    <td><input type="number" name="items[0][tax_rate]" class="form-control form-control-sm item-tax" step="0.01" value="0" min="0" max="100"></td>
                                    <td><strong class="item-total">0.00</strong></td>
                                    <td><button type="button" class="btn btn-sm btn-outline-danger btn-remove-item"><i class="fas fa-trash"></i></button></td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="6" class="text-end"><strong><?= lang('finance.grand_total') ?>:</strong></td>
                                    <td><strong id="grand-total">0.00</strong></td>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-success mb-3" id="add-item-btn">
                        <i class="fas fa-plus me-1"></i><?= lang('finance.add_item') ?>
                    </button>

                    <div class="mb-3">
                        <label class="form-label"><?= lang('finance.notes') ?></label>
                        <textarea name="notes" class="form-control" rows="2"></textarea>
                    </div>

                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i><?= lang('common.save') ?></button>
                        <a href="/finance/invoices" class="btn btn-secondary"><?= lang('common.cancel') ?></a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php $__view->push('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Member Select2
    $('#member-select').select2({
        theme: 'bootstrap-5',
        width: '100%',
        ajax: {
            url: '/finance/api/members/search',
            dataType: 'json',
            delay: 300,
            data: function(params) { return { q: params.term, page: params.page || 1 }; },
            processResults: function(data) { return data; }
        },
        minimumInputLength: 2,
        placeholder: '<?= lang('finance.search_member') ?>...'
    }).on('select2:select', function(e) {
        var d = e.params.data;
        if (d.outstanding > 0) {
            $('#member-info').removeClass('d-none').html('<span class="text-danger"><?= lang('finance.outstanding') ?>: ' + d.outstanding.toFixed(2) + ' <?= Config::get('default_currency','EGP') ?></span>');
        } else {
            $('#member-info').addClass('d-none');
        }
    });

    // Line item calculations
    var itemIndex = 1;
    function recalcRow(row) {
        var qty = parseFloat(row.querySelector('.item-qty').value) || 0;
        var price = parseFloat(row.querySelector('.item-price').value) || 0;
        var discount = parseFloat(row.querySelector('.item-discount').value) || 0;
        var taxRate = parseFloat(row.querySelector('.item-tax').value) || 0;
        var subtotal = (qty * price) - discount;
        var tax = subtotal * taxRate / 100;
        var total = subtotal + tax;
        row.querySelector('.item-total').textContent = total.toFixed(2);
        recalcGrand();
    }

    function recalcGrand() {
        var grand = 0;
        document.querySelectorAll('.item-total').forEach(function(el) {
            grand += parseFloat(el.textContent) || 0;
        });
        document.getElementById('grand-total').textContent = grand.toFixed(2);
    }

    document.getElementById('items-body').addEventListener('input', function(e) {
        var row = e.target.closest('.item-row');
        if (row) recalcRow(row);
    });

    document.getElementById('add-item-btn').addEventListener('click', function() {
        var tbody = document.getElementById('items-body');
        var firstRow = tbody.querySelector('.item-row');
        var newRow = firstRow.cloneNode(true);
        newRow.querySelectorAll('input').forEach(function(inp) {
            inp.name = inp.name.replace(/\[\d+\]/, '[' + itemIndex + ']');
            if (inp.classList.contains('item-qty')) inp.value = '1';
            else if (inp.type === 'number') inp.value = '0';
            else inp.value = '';
        });
        newRow.querySelectorAll('select').forEach(function(sel) {
            sel.name = sel.name.replace(/\[\d+\]/, '[' + itemIndex + ']');
            sel.value = '';
        });
        newRow.querySelector('.item-total').textContent = '0.00';
        tbody.appendChild(newRow);
        itemIndex++;
    });

    document.getElementById('items-body').addEventListener('click', function(e) {
        var btn = e.target.closest('.btn-remove-item');
        if (btn) {
            var rows = document.querySelectorAll('.item-row');
            if (rows.length > 1) {
                btn.closest('.item-row').remove();
                recalcGrand();
            }
        }
    });
});
</script>
<?php $__view->endPush(); ?>