<?php $this->start('body');
    $sale     = $this->data['sale'];
    $saleItems= $this->data['sale_items'] ?? [];
    $reasons  = $this->data['reasons'] ?? [];
?>
<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-undo-alt me-2 text-muted"></i>New Credit Note</h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            Against <a href="<?= PROOT; ?>Sales/view/<?= (int)$sale['c0d']; ?>"><strong><?= htmlspecialchars((string)$sale['sale_no']); ?></strong></a>
            &middot; <?= htmlspecialchars((string)$sale['customer_name']); ?>
            &middot; Total: <strong><?= htmlspecialchars((string)$sale['currency']); ?> <?= number_format((float)$sale['total']); ?></strong>
        </div>
    </div>
    <a href="<?= PROOT; ?>Sales/view/<?= (int)$sale['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3">
        <form id="cn_form">
            <input type="hidden" name="sale_id" value="<?= (int)$sale['c0d']; ?>">
            <div class="row g-2 mb-3">
                <div class="col-md-4"><label class="form-label small">Reason *</label>
                    <select name="reason" class="form-select form-select-sm">
                        <?php foreach ($reasons as $k => $lbl): ?>
                            <option value="<?= $k; ?>"><?= htmlspecialchars($lbl); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-8"><label class="form-label small">Narrative</label>
                    <input type="text" name="narrative" class="form-control form-control-sm" placeholder="Describe what's being credited">
                </div>
            </div>
            <div class="table-responsive mb-2">
                <table class="table table-sm mb-0 align-middle">
                    <thead class="table-light">
                        <tr>
                            <th style="width:36px;">#</th>
                            <th>Description *</th>
                            <th class="text-end" style="width:110px;">Qty *</th>
                            <th style="width:80px;">Unit</th>
                            <th class="text-end" style="width:130px;">Unit price *</th>
                            <th class="text-end" style="width:130px;">Line total</th>
                            <th style="width:36px;"></th>
                        </tr>
                    </thead>
                    <tbody id="cn_lines_body">
                        <?php foreach ($saleItems as $i => $it): ?>
                            <tr data-sales-item-id="<?= (int)$it['c0d']; ?>">
                                <td class="text-muted small"><?= $i + 1; ?></td>
                                <td><input type="text" class="form-control form-control-sm cn_desc" value="<?= htmlspecialchars((string)$it['description']); ?>"></td>
                                <td><input type="number" step="0.01" min="0" class="form-control form-control-sm text-end cn_qty" value="0" data-max="<?= (float)$it['qty']; ?>"></td>
                                <td><input type="text" class="form-control form-control-sm cn_unit" value="<?= htmlspecialchars((string)($it['unit'] ?? '')); ?>"></td>
                                <td><input type="number" step="0.01" min="0" class="form-control form-control-sm text-end cn_price" value="<?= (float)($it['unit_price'] ?? 0); ?>"></td>
                                <td class="text-end small cn_line_total" style="font-weight:600;">0</td>
                                <td><button type="button" class="btn btn-sm btn-link text-danger p-0 cn_del_line"><i class="fas fa-times"></i></button></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr><td colspan="5" class="text-end small text-muted">Credit total</td><td class="text-end small" id="cn_total" style="font-weight:700;color:#334155;">0</td><td></td></tr>
                    </tfoot>
                </table>
            </div>
            <div class="d-flex justify-content-between align-items-center">
                <button type="button" class="btn btn-sm btn-outline-secondary" id="cn_add_line"><i class="fas fa-plus me-1"></i>Add blank line</button>
                <div class="text-muted small" style="font-size:.65rem;">
                    Credit total cannot exceed original invoice: <?= htmlspecialchars((string)$sale['currency']); ?> <?= number_format((float)$sale['total']); ?>
                </div>
                <button type="button" class="btn btn-sm" id="cn_save" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-save me-1"></i>Save Draft</button>
            </div>
        </form>
    </div>
</div>

<script>
(function () {
    var PROOT   = '<?= PROOT; ?>';
    var MAX_TOT = <?= (float)$sale['total']; ?>;
    var body    = document.getElementById('cn_lines_body');
    function fmt(n) { return (parseFloat(n||0)).toLocaleString(undefined, {maximumFractionDigits:0}); }

    function recalc() {
        var total = 0;
        body.querySelectorAll('tr').forEach(function (tr) {
            var qty = parseFloat(tr.querySelector('.cn_qty').value || 0);
            var up  = parseFloat(tr.querySelector('.cn_price').value || 0);
            var lt  = qty * up;
            tr.querySelector('.cn_line_total').textContent = fmt(lt);
            total += lt;
        });
        document.getElementById('cn_total').textContent = fmt(total);
        document.getElementById('cn_total').style.color = (total > MAX_TOT + 0.01) ? '#C48579' : '#334155';
    }
    body.addEventListener('input', function (e) { if (e.target.classList.contains('cn_qty') || e.target.classList.contains('cn_price')) recalc(); });
    body.addEventListener('click', function (e) {
        var b = e.target.closest('.cn_del_line'); if (!b) return;
        var tr = b.closest('tr'); if (tr) tr.remove();
        recalc();
    });
    document.getElementById('cn_add_line').addEventListener('click', function () {
        var i = body.querySelectorAll('tr').length + 1;
        var html = '<tr>' +
            '<td class="text-muted small">' + i + '</td>' +
            '<td><input type="text" class="form-control form-control-sm cn_desc"></td>' +
            '<td><input type="number" step="0.01" min="0" class="form-control form-control-sm text-end cn_qty" value="0"></td>' +
            '<td><input type="text" class="form-control form-control-sm cn_unit"></td>' +
            '<td><input type="number" step="0.01" min="0" class="form-control form-control-sm text-end cn_price" value="0"></td>' +
            '<td class="text-end small cn_line_total" style="font-weight:600;">0</td>' +
            '<td><button type="button" class="btn btn-sm btn-link text-danger p-0 cn_del_line"><i class="fas fa-times"></i></button></td>' +
        '</tr>';
        body.insertAdjacentHTML('beforeend', html);
    });
    recalc();

    document.getElementById('cn_save').addEventListener('click', function () {
        var lines = [];
        body.querySelectorAll('tr').forEach(function (tr) {
            var qty = parseFloat(tr.querySelector('.cn_qty').value || 0);
            var up  = parseFloat(tr.querySelector('.cn_price').value || 0);
            var desc= (tr.querySelector('.cn_desc').value || '').trim();
            if (qty > 0 && up > 0 && desc) {
                lines.push({
                    sales_item_id: parseInt(tr.getAttribute('data-sales-item-id') || 0, 10),
                    description:   desc,
                    qty:           qty,
                    unit:          tr.querySelector('.cn_unit').value || '',
                    unit_price:    up
                });
            }
        });
        if (lines.length === 0) { $.alert({title:'Add at least one line with qty & price', type:'orange'}); return; }
        var payload = {
            sale_id:   document.querySelector('input[name=sale_id]').value,
            reason:    document.querySelector('select[name=reason]').value,
            narrative: document.querySelector('input[name=narrative]').value || '',
            lines:     JSON.stringify(lines)
        };
        $.post(PROOT + 'CreditNotes/saveDraftAj', payload, function (r) {
            if (r && r.ok) { rsToast('Draft saved.', 'success'); setTimeout(function(){window.location.href = PROOT + 'CreditNotes/view/' + r.cn_id;}, 500); }
            else $.alert({title:'Save failed', content:(r && r.msg) || 'Server error', type:'red'});
        }, 'json');
    });
})();
</script>
<?php $this->end(); ?>
