<div class="card-box">

    <div class="card-box-header">
        <h5><i class="fa-solid fa-file-invoice-dollar text-primary"></i>
            <?= isset($row) ? 'Edit Sales Bill' : 'New Sales Bill' ?>
        </h5>
        <a href="<?= site_url('sales_billing') ?>" class="btn btn-sm" style="background:#f1f5f9;color:#374151;">
            <i class="fa-solid fa-arrow-left me-1"></i> Back to List
        </a>
    </div>

    <?php if(validation_errors()): ?>
    <div class="alert alert-danger">
        <?= validation_errors('<ul class="mb-0 ps-3">','</ul>','<li>','</li>') ?>
    </div>
    <?php endif; ?>
    <?php if(isset($item_error)): ?>
    <div class="alert alert-danger">
        <i class="fa-solid fa-circle-exclamation me-2"></i><?= $item_error ?>
    </div>
    <?php endif; ?>

    <form method="post" action="<?= isset($row) ? site_url('sales_billing/edit/'.$row->id) : site_url('sales_billing/create') ?>">

        <div class="p-3 mb-3 rounded" style="background:#d5f2ed;border:1px solid #e2e8f0;">
            <div class="fw-bold text-muted mb-3" style="font-size:12px;letter-spacing:.8px;text-transform:uppercase;">
                <i class="fa-solid fa-circle-info me-1"></i> Bill Details
            </div>
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Customer <span class="required-star">*</span></label>
                    <!-- <div class="input-group"> -->
                    <div class="d-flex align-items-center gap-2">
                        <div style="flex:1;min-width:0;">
    
                        <select name="customer_id" id="customer_id" class="form-select select2 <?= form_error('customer_id') ? 'is-invalid' : '' ?>">
                            <option value="">— Select Customer —</option>
                            <?php foreach($customers as $c): ?>
                            <option value="<?= $c->id ?>"
                                <?= set_select('customer_id', $c->id, isset($row) && $row->customer_id == $c->id) ?>>
                                <?= htmlspecialchars($c->customer_name) ?><?= !empty($c->mobile) ? ' - ' . htmlspecialchars($c->mobile) : '' ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                            </div>  
                        <button type="button" class="btn btn-primary d-none" id="btnAddCustomer" title="Add New Customer">
                            <i class="fa-solid fa-plus"></i>
                        </button>
                    </div>
                    <?php if(form_error('customer_id')): ?><div class="invalid-feedback d-block"><?= form_error('customer_id') ?></div><?php endif; ?>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Bill Date <span class="required-star">*</span></label>
                    <input type="date" name="bill_date"
                           class="form-control <?= form_error('bill_date') ? 'is-invalid' : '' ?>"
                           value="<?= set_value('bill_date', isset($row) ? $row->bill_date : date('Y-m-d')) ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Bill No</label>
                    <input type="text" name="bill_no" class="form-control"
                           value="<?= set_value('bill_no', isset($row) ? $row->bill_no : $bill_no) ?>"
                           placeholder="e.g. BILL-001">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Discount (₹)</label>
                    <input type="number" name="discount" step="0.01" min="0" class="form-control"
                           value="<?= set_value('discount', isset($row) ? $row->discount : '0') ?>"
                           id="discount_inp">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Notes</label>
                    <input type="text" name="notes" class="form-control"
                           value="<?= set_value('notes', isset($row) ? $row->notes : '') ?>"
                           placeholder="Optional notes">
                </div>
            </div>
        </div>

        <!-- Items -->
        <div class="p-3 mb-3 rounded text-dark" style="background-color:#e0ffff;">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div class="fw-bold text-dark" style="font-size:12px;letter-spacing:.8px;text-transform:uppercase;">
                    <i class="fa-solid fa-bag-shopping me-1"></i> Items
                </div>
            </div>
            <div class="table-responsive bg-white rounded p-2">
                <table class="table table-bordered mb-0" id="itemsTable" style="font-size:13px;">
                    <thead>
                        <tr>
                            <th width="35">#</th>
                            <th width="280">Product</th>
                            <th width="100">Qty</th>
                            <th width="120">Sale Rate (₹)</th>
                            <th width="80">GST %</th>
                            <th width="120">Amount (₹)</th>
                            <th width="120">Total (₹)</th>
                            <th width="40"></th>
<th width="120"></th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody">

                        <?php
                        if (isset($edit_items) && !empty($edit_items)):
                            foreach($edit_items as $idx => $item): ?>
                        <tr class="item-row">
                            <td class="row-num"><?= $idx + 1 ?></td>
                            <td>
                                <select name="product_id[]" class="form-select form-select-sm select2 product-sel">
                                    <option value="">— Select —</option>
                                    <?php foreach($products as $p): ?>
                                    <option value="<?= $p->id ?>"
                                        data-rate="<?= $p->sale_rate ?>"
                                        data-gst="<?= $p->gst_percent ?>"
                                        <?= ($p->id == $item->product_id) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($p->product_name) ?> (Stock: <?= (float)$p->current_stock ?><?= !empty($p->unit_name) ? ' ' . htmlspecialchars($p->unit_name) : '' ?>)
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td><input type="number" name="qty[]" class="form-control form-control-sm qty-inp" step="0.01" min="0" value="<?= $item->qty ?>"></td>
                            <td><input type="number" name="rate[]" class="form-control form-control-sm rate-inp" step="0.01" min="0" value="<?= $item->rate ?>"></td>
                            <td><input type="number" name="gst_percent[]" class="form-control form-control-sm gst-inp" step="0.01" min="0" max="100" value="<?= $item->gst_percent ?>"></td>
                            <td><input type="text" class="form-control form-control-sm amt-out bg-light" readonly value="<?= (int)($item->amount) ?>"></td>
                            <td><input type="text" class="form-control form-control-sm total-out bg-light fw-bold" readonly value="<?= (int)($item->total) ?>"></td>
                            <td><button type="button" class="btn btn-sm btn-danger remove-row no-loader"><i class="fa-solid fa-times"></i></button></td>
                        </tr>
                        <?php endforeach;
                        else: ?>
                        <tr class="item-row">
                            <td class="row-num">1</td>
                            <td>
                                <select name="product_id[]" class="form-select form-select-sm select2 product-sel">
                                    <option value="">— Select —</option>
                                    <?php foreach($products as $p): ?>
                                    <option value="<?= $p->id ?>" data-rate="<?= $p->sale_rate ?>" data-gst="<?= $p->gst_percent ?>">
                                        <?= htmlspecialchars($p->product_name) ?> (Stock: <?= (float)$p->current_stock ?><?= !empty($p->unit_name) ? ' ' . htmlspecialchars($p->unit_name) : '' ?>)
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td><input type="number" name="qty[]" class="form-control form-control-sm qty-inp" step="0.01" min="0"></td>
                            <td><input type="number" name="rate[]" class="form-control form-control-sm rate-inp" step="0.01" min="0"></td>
                            <td><input type="number" name="gst_percent[]" class="form-control form-control-sm gst-inp" step="0.01" min="0" max="100" value="0"></td>
                            <td><input type="text" class="form-control form-control-sm amt-out bg-light" readonly value="0.00"></td>
                            <td><input type="text" class="form-control form-control-sm total-out bg-light fw-bold" readonly value="0.00"></td>
                            <td><button type="button" class="btn btn-sm btn-danger remove-row no-loader"><i class="fa-solid fa-times"></i></button></td>
                        </tr>
                        <?php endif; ?>

                    </tbody>
                    <tfoot>
                        <!--<tr>-->
                        <!--    <td colspan="6" class="text-end fw-bold">Sub Total:</td>-->
                        <!--    <td><input type="text" id="sub_amt" class="form-control form-control-sm bg-light" readonly value="0.00"></td>-->
                        <!--    <td><input type="text" id="sub_total" class="form-control form-control-sm bg-light" readonly value="0.00"></td>-->
                        <!--    <td><button type="button" id="addRow" class="btn btn-sm btn-success no-loader" style="white-space:nowrap;"><i class="fa-solid fa-plus me-1"></i>Add Row</button></td>-->
                        <!--</tr>-->
                        
                        <tr>
    <td colspan="5" class="text-end fw-bold">Sub Total:</td>

    <td>
        <input type="text" id="sub_amt"
               class="form-control form-control-sm bg-light"
               readonly value="0.00">
    </td>

    <td>
        <input type="text" id="sub_total"
               class="form-control form-control-sm bg-light"
               readonly value="0.00">
    </td>

    <td></td>

    <td>
        <button type="button" id="addRow"
                class="btn btn-sm btn-success no-loader"
                style="white-space:nowrap;">
            <i class="fa-solid fa-plus me-1"></i>Add Row
        </button>
    </td>
</tr>
                        <tr>
                            <td colspan="8" class="text-end fw-bold text-success">Net Payable (after discount):</td>
                            <td colspan="2"><input type="text" id="net_payable" class="form-control form-control-sm bg-light fw-bold text-success" readonly value="0.00"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <div class="d-flex gap-2">
            <!--<button type="submit" name="save_bill" value="1" class="btn btn-success px-4">-->
            <!--    <i class="fa-solid fa-floppy-disk me-1"></i>-->
            <!--    <?= isset($row) ? 'Update Bill' : 'Save Bill' ?>-->
            <!--</button>-->
            <button type="submit" name="save_bill" value="1" class="btn btn-primary px-4">
                <i class="fa-solid fa-floppy-disk me-1"></i>
                <?= isset($row) ? 'Update Bill' : 'Save Bill' ?>
            </button>
            <a href="<?= site_url('sales_billing') ?>" class="btn" style="background:#f1f5f9;color:#374151;">Cancel</a>
        </div>

    </form>
</div>

<!-- ── Add New Customer Modal ───────────────────────────────────────────── -->
<div class="modal fade" id="addCustomerModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width:550px;">
        <div class="modal-content" style="border-radius:12px;overflow:hidden;">
            <div class="modal-header border-0 pb-1 pt-3">
                <h5 class="modal-title text-danger fw-bold w-100 text-center" style="font-size:1.15rem;">
                    Add New Customer
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body px-4 pt-2 pb-4" style="background:#eef2f7;">
                <div class="row g-3 mt-1">
                    <div class="col-md-6">
                        <label class="form-label text-primary fw-semibold">Customer Name <span class="text-danger">*</span></label>
                        <input type="text" id="nc_name" class="form-control" placeholder="Enter Customer Name">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-primary fw-semibold">Primary Mobile <span class="text-danger">*</span></label>
                        <input type="text" id="nc_mobile" class="form-control" placeholder="Enter 10-digit Mobile No" maxlength="10" pattern="[0-9]{10}">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-primary fw-semibold">GST No <span class="text-muted" style="font-weight:400;">(optional)</span></label>
                        <input type="text" id="nc_gst" class="form-control" placeholder="Enter GST No">
                    </div>
                    <div class="col-12">
                        <label class="form-label text-primary fw-semibold">Address <span class="text-danger">*</span></label>
                        <textarea id="nc_address" class="form-control" rows="3" placeholder="Enter Address"></textarea>
                    </div>
                </div>
                <div class="d-flex justify-content-end gap-2 mt-3">
                    <button type="button" class="btn btn-primary px-4" id="btnSaveCustomer">
                        <i class="fa-solid fa-floppy-disk me-1"></i> Submit
                    </button>
                    <button type="button" class="btn btn-danger px-3" data-bs-dismiss="modal">
                        <i class="fa-solid fa-times me-1"></i> Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$products_json = json_encode(array_map(function($p) {
    return ['id' => (int)$p->id, 'rate' => (float)$p->sale_rate, 'gst' => (float)$p->gst_percent];
}, $products));
?>

<script>
$(document).ready(function(){
    var products = <?= $products_json ?>;
    var productMap = {};
    products.forEach(function(p){ productMap[p.id] = p; });

    // Select2 init — existing rows
    $('select.product-sel').select2({
        theme: 'bootstrap-5',
        width: '100%'
    });

    // Select2 init — customer dropdown
$('#customer_id').select2({
    theme: 'bootstrap-5',
    width: '100%'
});
$('#customer_id').on('select2:open', function(){
    setTimeout(function(){
        var $dropdown = $('.select2-container--open .select2-dropdown');
        if($dropdown.length && $dropdown.find('.add-new-option').length === 0){
            var $opt = $('<div class="add-new-option" style="padding:8px 14px;cursor:pointer;color:#7c3aed;font-weight:600;border-bottom:1px solid #eee;background:#f5f3ff;"><i class="fa-solid fa-plus me-2"></i>Add New Customer</div>');
            $opt.on('mousedown', function(e){
                e.preventDefault();
                e.stopPropagation();
                $('#customer_id').select2('close');
                $('#btnAddCustomer').trigger('click');
            });
            $dropdown.find('.select2-results').after($opt);
        }
    }, 0);
});

    function calcRow(row){
        var qty  = parseFloat(row.find('.qty-inp').val())  || 0;
        var rate = parseFloat(row.find('.rate-inp').val()) || 0;
        var gst  = parseFloat(row.find('.gst-inp').val())  || 0;
        var amt  = qty * rate;
        row.find('.amt-out').val(amt);
        row.find('.total-out').val((amt + (amt * gst / 100)));
        calcGrand();
    }

    function calcGrand(){
        var amt = 0, total = 0;
        $('.amt-out').each(function(){ amt   += parseFloat($(this).val()) || 0; });
        $('.total-out').each(function(){ total += parseFloat($(this).val()) || 0; });
        var disc = parseFloat($('#discount_inp').val()) || 0;
        $('#sub_amt').val(amt);
        $('#sub_total').val(total);
        $('#net_payable').val((total - disc));
    }

    function reNumberRows(){
        $('.item-row').each(function(i){
            $(this).find('.row-num').text(i + 1);
        });
    }

    $(document).on('change', '.product-sel', function(){
        var row = $(this).closest('tr');
        var pid = parseInt($(this).val());
        if(productMap[pid]){
            row.find('.rate-inp').val(productMap[pid].rate);
            row.find('.gst-inp').val(productMap[pid].gst);
        }
        calcRow(row);
        // Product select झाल्यावर cursor आपोआप Qty field ला जाईल
        setTimeout(function(){ row.find('.qty-inp').focus().select(); }, 50);
    });

    $(document).on('input', '.qty-inp, .rate-inp, .gst-inp', function(){
        calcRow($(this).closest('tr'));
    });

    $('#discount_inp').on('input', calcGrand);

    $(document).on('click', '.remove-row', function(){
        if($('.item-row').length > 1){
            $(this).closest('tr').remove();
            reNumberRows();
            calcGrand();
        }
    });

    // ✅ Add Row
    $('#addRow').on('click', function(){

        var newRow = `
        <tr class="item-row">
            <td class="row-num"></td>
            <td>
                <select name="product_id[]" class="form-select form-select-sm product-sel">
                    <option value="">— Select —</option>
                    <?php foreach($products as $p): ?>
                    <option value="<?= $p->id ?>"
                        data-rate="<?= $p->sale_rate ?>"
                        data-gst="<?= $p->gst_percent ?>">
                        <?= htmlspecialchars($p->product_name) ?> (Stock: <?= (float)$p->current_stock ?><?= !empty($p->unit_name) ? ' ' . htmlspecialchars($p->unit_name) : '' ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </td>
            <td><input type="number" name="qty[]" class="form-control form-control-sm qty-inp" step="0.01" min="0" placeholder="0" value=""></td>
            <td><input type="number" name="rate[]" class="form-control form-control-sm rate-inp" step="0.01" min="0" placeholder="0.00" value=""></td>
            <td><input type="number" name="gst_percent[]" class="form-control form-control-sm gst-inp" step="0.01" min="0" max="100" value="0"></td>
            <td><input type="text" class="form-control form-control-sm amt-out bg-light" readonly value="0.00"></td>
            <td><input type="text" class="form-control form-control-sm total-out bg-light fw-bold" readonly value="0.00"></td>
            <td><button type="button" class="btn btn-sm btn-danger remove-row no-loader"><i class="fa-solid fa-times"></i></button></td>
        </tr>`;

        $('#itemsBody').append(newRow);

        // ✅ नवीन row ला select2 init
        $('#itemsBody tr.item-row:last select.product-sel').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });

        reNumberRows();
    });

    // Edit mode — existing rows calculate
    $('.item-row').each(function(){ calcRow($(this)); });


    // ── Add New Customer Modal Logic ─────────────────────────────────────────

    $('#btnAddCustomer').on('click', function(){
        $('#nc_name').val('');
        $('#nc_mobile').val('');
        $('#nc_gst').val('');
        $('#nc_address').val('');
        $('#addCustomerModal').modal('show');
    });

    $('#btnSaveCustomer').on('click', function(){
        var name    = $('#nc_name').val().trim();
        var mobile  = $('#nc_mobile').val().trim();
        var gst_no  = $('#nc_gst').val().trim();
        var address = $('#nc_address').val().trim();

        if(!name){
            showProAlert('error', 'Error', 'Customer Name is required!');
            return;
        }
        if(!mobile || !/^[0-9]{10}$/.test(mobile)){
            showProAlert('error', 'Error', 'Valid 10-digit Mobile Number is required!');
            return;
        }
        if(!address){
            showProAlert('error', 'Error', 'Address is required!');
            return;
        }

        $('#btnSaveCustomer').prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin me-1"></i> Saving...');

        $.ajax({
            url: '<?= site_url("sales_billing/ajax_add_customer") ?>',
            type: 'POST',
            data: { customer_name: name, mobile: mobile, gst_no: gst_no, address: address },
            dataType: 'json',
            success: function(res){
                if(res.status === 'success'){
                    // Dropdown मध्ये नवीन option add करून select करा
                    var displayText = res.customer_name + (res.mobile ? ' - ' + res.mobile : '');
                    var newOption = new Option(displayText, res.id, true, true);
                    $('#customer_id').append(newOption).trigger('change');
                    $('#addCustomerModal').modal('hide');
                    showProAlert('success', 'Added!', res.customer_name + ' successfully added!');
                } else {
                    showProAlert('error', 'Error', res.message || 'Something went wrong!');
                }
            },
            error: function(){
                showProAlert('error', 'Error', 'Server error. Please try again.');
            },
            complete: function(){
                $('#btnSaveCustomer').prop('disabled', false).html('<i class="fa-solid fa-floppy-disk me-1"></i> Submit');
            }
        });
    });

});
</script>