<div class="card-box">

    <div class="card-box-header">
        <h5><i class="fa-solid fa-cart-shopping text-primary"></i>
            <?= isset($row) ? 'Edit Purchase Entry' : 'New Purchase Entry' ?>
        </h5>
        <a href="<?= site_url('purchase_entry') ?>" 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">
        <i class="fa-solid fa-circle-exclamation me-2"></i>
        <?= 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" enctype="multipart/form-data" action="<?= isset($row) ? site_url('purchase_entry/edit/'.$row->id) : site_url('purchase_entry/create') ?>">

        <!-- Header Info -->
        <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> Purchase Details
            </div>
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Supplier <span class="required-star">*</span></label>
                    <div class="d-flex align-items-center gap-2">
                        <div style="flex:1;min-width:0;">
                            <select name="supplier_id" id="supplier_id" class="form-select select2 <?= form_error('supplier_id') ? 'is-invalid' : '' ?>">
                                <option value="">— Select Supplier —</option>
                                <?php foreach($suppliers as $s): ?>
                                <option value="<?= $s->id ?>"
                                    <?= set_select('supplier_id', $s->id, isset($row) && $row->supplier_id == $s->id) ?>>
                                    <?= htmlspecialchars($s->supplier_name) ?><?= !empty($s->mobile) ? ' - ' . htmlspecialchars($s->mobile) : '' ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button type="button" class="btn btn-primary flex-shrink-0 d-none" id="btnAddSupplier" title="Add New Supplier">
                            <i class="fa-solid fa-plus"></i>
                        </button>
                    </div>
                    <?php if(form_error('supplier_id')): ?><div class="invalid-feedback d-block"><?= form_error('supplier_id') ?></div><?php endif; ?>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Purchase Date <span class="required-star">*</span></label>
                    <input type="date" name="purchase_date"
                           class="form-control <?= form_error('purchase_date') ? 'is-invalid' : '' ?>"
                           value="<?= set_value('purchase_date', isset($row) ? $row->purchase_date : date('Y-m-d')) ?>">
                    <?php if(form_error('purchase_date')): ?><div class="invalid-feedback"><?= form_error('purchase_date') ?></div><?php endif; ?>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Invoice No</label>
                    <input type="text" name="invoice_no" class="form-control"
                           value="<?= set_value('invoice_no', isset($row) ? $row->invoice_no : '') ?>"
                           placeholder="e.g. INV-2024-001">
                </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 class="col-md-6">
                    <label class="form-label">Attachment (Image / PDF)</label>
                    <input type="file" id="attachmentInput" name="attachment" class="form-control" accept=".jpg,.jpeg,.png,.pdf">
                    <?php if(isset($row) && !empty($row->attachment)): ?>
                    <div class="mt-1">
                        <small class="text-muted">
                            Current file:
                            <a href="<?= base_url('uploads/purchase_entry/'.$row->attachment) ?>" target="_blank">
                                <?= htmlspecialchars($row->attachment) ?>
                            </a>
                            — upload a new file to replace it.
                        </small>
                    </div>
                    <?php endif; ?>
                    <div id="attachmentPreview" class="mt-2"></div>
                </div>
            </div>
        </div>

        <script>
        (function() {
            var input   = document.getElementById('attachmentInput');
            var preview = document.getElementById('attachmentPreview');
            if (!input) return;

            input.addEventListener('change', function(e) {
                var file = e.target.files[0];
                preview.innerHTML = '';
                if (!file) return;

                var url = URL.createObjectURL(file);

                if (file.type.startsWith('image/')) {
                    preview.innerHTML =
                        '<div class="fw-bold text-muted mb-1" style="font-size:11px;">New file preview:</div>' +
                        '<img src="' + url + '" alt="Preview" style="max-height:130px;border-radius:6px;border:1px solid #e2e8f0;">';
                } else if (file.type === 'application/pdf') {
                    preview.innerHTML =
                        '<div class="fw-bold text-muted mb-1" style="font-size:11px;">New file preview:</div>' +
                        '<iframe src="' + url + '" style="width:100%;max-width:420px;height:200px;border:1px solid #e2e8f0;border-radius:6px;"></iframe>';
                } else {
                    preview.innerHTML = '<small class="text-danger">Only JPG, PNG or PDF files are allowed.</small>';
                }
            });
        })();
        </script>

        <!-- Items Table -->
        <!--<div class="p-3 mb-3 rounded" style="background:#1e293b;border:1px solid #e2e8f0;">-->
        <!--<div class="p-3 mb-3 rounded" style="background:#475569;border:1px solid #64748b;color:white;">-->
        <div class="p-3 mb-3 rounded text-dark" style="background-color:#e0ffff;">
        
        <!--<div class="p-3 mb-3 rounded bg-dark text-white border">-->
            <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-boxes-stacked 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">Rate (₹)</th>
                            <th width="80">GST %</th>
                            <th width="120">Amount (₹)</th>
                            <th width="120">Total (₹)</th>
                            
                            <th width="40" style="background:#e4d4e9;"></th>
                            <th width="120"></th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody">

                        <?php
                        // Edit mode: show saved items
                        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-gst="<?= $p->gst_percent ?>"
                                        data-rate="<?= $p->purchase_rate ?>"
                                        <?= ($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: ?>
                        <!-- Default first blank row for create -->
                        <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-gst="<?= $p->gst_percent ?>" data-rate="<?= $p->purchase_rate ?>">
                                        <?= 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"></td>
                            <td><input type="number" name="rate[]" class="form-control form-control-sm rate-inp" step="0.01" min="0" placeholder="0.00"></td>
                            <td><input type="number" name="gst_percent[]" class="form-control form-control-sm gst-inp" step="0.01" min="0" max="100" placeholder="0" 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">Grand Total:</td>-->
                    <!--        <td colspan="5" class="text-end fw-bold">Grand Total:</td>-->
                    <!--        <td><input type="text" id="grand_amt" class="form-control form-control-sm bg-light fw-bold" readonly value="0.00"></td>-->
                    <!--        <td><input type="text" id="grand_total" class="form-control form-control-sm bg-light fw-bold text-success" 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>-->
                    <!--</tfoot>-->
                    
                    <tfoot>
    <tr>
        <td colspan="5" class="text-end fw-bold">Grand Total:</td>

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

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

        <!-- Remove Button Column -->
        <td></td>

        <!-- Add Row Button Last Column -->
        <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>
</tfoot>
                </table>
            </div>
        </div>

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

    </form>
</div>

<!-- ── Add New Supplier Modal ───────────────────────────────────────────── -->
<div class="modal fade" id="addSupplierModal" 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 Supplier
                </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">Supplier Name <span class="text-danger">*</span></label>
                        <input type="text" id="ns_name" class="form-control" placeholder="Enter Supplier Name">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-primary fw-semibold">Mobile <span class="text-danger">*</span></label>
                        <input type="text" id="ns_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="ns_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="ns_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="btnSaveSupplier">
                        <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>

<script>
$(document).ready(function(){

    // Select2 init — supplier dropdown
    $('#supplier_id').select2({ theme: 'bootstrap-5', width: '100%' });
    $('#supplier_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 Supplier</div>');
                $opt.on('mousedown', function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    $('#supplier_id').select2('close');
                    $('#btnAddSupplier').trigger('click');
                });
                $dropdown.find('.select2-results').after($opt);
            }
        }, 0);
    });

    // ── Add New Supplier Modal Logic ─────────────────────────────────────────
    $('#btnAddSupplier').on('click', function(){
        $('#ns_name').val('');
        $('#ns_mobile').val('');
        $('#ns_gst').val('');
        $('#ns_address').val('');

        // Bootstrap 5 native modal API (jQuery .modal() plugin is NOT bundled with BS5)
        var modalEl = document.getElementById('addSupplierModal');
        var modalInstance = bootstrap.Modal.getOrCreateInstance(modalEl);
        modalInstance.show();
    });

    $('#btnSaveSupplier').on('click', function(){
        var name    = $('#ns_name').val().trim();
        var mobile  = $('#ns_mobile').val().trim();
        var gst_no  = $('#ns_gst').val().trim();
        var address = $('#ns_address').val().trim();

        if(!name){ showProAlert('error', 'Error', 'Supplier 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; }

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

        $.ajax({
            url: '<?= site_url("purchase_entry/ajax_add_supplier") ?>',
            type: 'POST',
            data: { supplier_name: name, mobile: mobile, gst_no: gst_no, address: address },
            dataType: 'json',
            success: function(res){
                if(res.status === 'success'){
                    var displayText = res.supplier_name + (res.mobile ? ' - ' + res.mobile : '');
                    var newOption = new Option(displayText, res.id, true, true);
                    $('#supplier_id').append(newOption).trigger('change');

                    var modalEl = document.getElementById('addSupplierModal');
                    bootstrap.Modal.getOrCreateInstance(modalEl).hide();

                    showProAlert('success', 'Added!', res.supplier_name + ' successfully added!');
                } else {
                    showProAlert('error', 'Error', res.message || 'Something went wrong!');
                }
            },
            error: function(){ showProAlert('error', 'Error', 'Server error. Please try again.'); },
            complete: function(){ $('#btnSaveSupplier').prop('disabled', false).html('<i class="fa-solid fa-floppy-disk me-1"></i> Submit'); }
        });
    });
});
</script>


<?php
$products_json = json_encode(array_map(function($p) {
    return ['id' => (int)$p->id, 'gst' => (float)$p->gst_percent, 'rate' => (float)$p->purchase_rate];
}, $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%'
    });

    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)));
        calcGrandTotal();
    }

    function calcGrandTotal(){
        var amt = 0, total = 0;
        $('.amt-out').each(function(){ amt   += parseFloat($(this).val()) || 0; });
        $('.total-out').each(function(){ total += parseFloat($(this).val()) || 0; });
        $('#grand_amt').val(amt);
        $('#grand_total').val(total);
    }

    // Product select change — rate & gst auto fill
    $(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);
    });

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

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

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

    // ✅ Add Row — नवीन blank row add करणे
    $('#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 new-sel">
                    <option value="">— Select —</option>
                    <?php foreach($products as $p): ?>
                    <option value="<?= $p->id ?>"
                        data-gst="<?= $p->gst_percent ?>"
                        data-rate="<?= $p->purchase_rate ?>">
                        <?= 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 च्या select ला 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)); });
});
</script>