<?php $this->start('body');
    $cn    = $this->data['cn'];
    $lines = $this->data['lines'] ?? [];
    $canIssue  = !empty($this->data['can_issue']);
    $canCancel = !empty($this->data['can_cancel']);
    $chip = [
        'DRAFT'     => ['#F1F5F9','#334155','Draft'],
        'ISSUED'    => ['#EAF2E8','#3F5C43','Issued'],
        'CANCELLED' => ['#F5EAE1','#C48579','Cancelled'],
    ];
    $sc = $chip[$cn['status']] ?? ['#F1F5F9','#334155',$cn['status']];
?>
<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>Credit Note <?= htmlspecialchars($cn['cn_no']); ?></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            Against <a href="<?= PROOT; ?>Sales/view/<?= (int)$cn['sale_id']; ?>"><strong><?= htmlspecialchars((string)$cn['sale_no']); ?></strong></a>
            &middot; <?= htmlspecialchars((string)$cn['customer_name']); ?>
            <?php if (!empty($cn['project_no'])): ?> &middot; <?= htmlspecialchars((string)$cn['project_no']); ?><?php endif; ?>
        </div>
    </div>
    <div class="d-flex align-items-center gap-2">
        <span class="badge" style="background:<?= $sc[0]; ?>;color:<?= $sc[1]; ?>;border:1px solid <?= $sc[1]; ?>;font-weight:600;text-transform:capitalize;padding:.4rem .55rem;font-size:.7rem;"><?= htmlspecialchars($sc[2]); ?></span>
        <a href="<?= PROOT; ?>CreditNotes" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    </div>
</div>

<div class="row g-3">
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header bg-white py-2"><strong style="font-weight:600;font-size:.85rem;">Credit lines</strong></div>
            <div class="table-responsive">
                <table class="table table-sm mb-0 align-middle">
                    <thead class="table-light">
                        <tr><th>#</th><th>Description</th><th class="text-end">Qty</th><th>Unit</th><th class="text-end">Unit price</th><th class="text-end">Total</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($lines as $ln): ?>
                            <tr>
                                <td class="text-muted small"><?= (int)$ln['line_no']; ?></td>
                                <td class="small"><?= htmlspecialchars((string)$ln['description']); ?></td>
                                <td class="text-end small"><?= number_format((float)$ln['qty'], (fmod((float)$ln['qty'],1)==0?0:2)); ?></td>
                                <td class="small text-muted"><?= htmlspecialchars((string)($ln['unit'] ?? '')); ?></td>
                                <td class="text-end small text-muted"><?= number_format((float)$ln['unit_price']); ?></td>
                                <td class="text-end small" style="font-weight:600;"><?= number_format((float)$ln['line_total']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr><td colspan="5" class="text-end small text-muted">Total</td><td class="text-end" style="font-weight:700;color:#334155;"><?= htmlspecialchars((string)$cn['currency']); ?> <?= number_format((float)$cn['total']); ?></td></tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <?php if (!empty($cn['narrative'])): ?>
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header bg-white py-2"><strong style="font-weight:600;font-size:.85rem;">Narrative</strong></div>
            <div class="card-body p-3 small"><?= nl2br(htmlspecialchars((string)$cn['narrative'])); ?></div>
        </div>
        <?php endif; ?>

        <?php if ($cn['status'] === 'ISSUED'): ?>
        <div class="card border-0 shadow-sm mb-3" style="background:#F0F7F1;">
            <div class="card-header py-2" style="background:transparent;border-bottom:1px solid #C4DEC8;">
                <strong style="color:#3F5C43;"><i class="fas fa-check-circle me-2"></i>Issued</strong>
            </div>
            <div class="card-body p-3">
                <div class="row g-2 small">
                    <div class="col-md-3"><div class="text-muted" style="font-size:.62rem;">EFD receipt</div><div><code><?= htmlspecialchars((string)($cn['efd_receipt_no'] ?: '—')); ?></code></div></div>
                    <div class="col-md-3"><div class="text-muted" style="font-size:.62rem;">EFD date</div><div><?= htmlspecialchars((string)($cn['efd_date'] ?: '—')); ?></div></div>
                    <div class="col-md-3"><div class="text-muted" style="font-size:.62rem;">TRA verification</div><div><code><?= htmlspecialchars((string)($cn['tra_verification_code'] ?: '—')); ?></code></div></div>
                    <div class="col-md-3"><div class="text-muted" style="font-size:.62rem;">Original EFD</div><div><code><?= htmlspecialchars((string)($cn['original_efd_receipt_no'] ?: '—')); ?></code></div></div>
                    <div class="col-md-6"><div class="text-muted" style="font-size:.62rem;">Issued by</div><div><?= htmlspecialchars((string)$cn['issued_by_name']); ?> &middot; <?= htmlspecialchars((string)$cn['issued_at']); ?></div></div>
                    <?php if (!empty($cn['journal_entry_id'])): ?>
                        <div class="col-md-6"><div class="text-muted" style="font-size:.62rem;">Journal entry</div><div>#<?= (int)$cn['journal_entry_id']; ?></div></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <div class="col-lg-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;"><i class="fas fa-bolt me-1 text-muted"></i>Actions</div>
            <div class="card-body p-3 d-flex flex-column gap-2">
                <?php if ($canIssue): ?>
                    <button type="button" class="btn btn-sm" id="btn_issue" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-check me-1"></i>Issue Credit Note</button>
                <?php endif; ?>
                <?php if ($canCancel): ?>
                    <button type="button" class="btn btn-sm btn-outline-danger" id="btn_cancel"><i class="fas fa-ban me-1"></i>Cancel Draft</button>
                <?php endif; ?>
                <?php if (!$canIssue && !$canCancel): ?>
                    <div class="text-muted small">No actions available at this state.</div>
                <?php endif; ?>
            </div>
        </div>

        <div class="card border-0 shadow-sm mt-3">
            <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;">Summary</div>
            <div class="card-body p-3 small">
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Reason</span><span style="text-transform:capitalize;font-weight:600;"><?= htmlspecialchars(strtolower(str_replace('_',' ', $cn['reason']))); ?></span></div>
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Original invoice total</span><span><?= htmlspecialchars((string)$cn['currency']); ?> <?= number_format((float)$cn['sale_total']); ?></span></div>
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Credit total</span><span style="font-weight:600;"><?= htmlspecialchars((string)$cn['currency']); ?> <?= number_format((float)$cn['total']); ?></span></div>
                <div class="d-flex justify-content-between mb-1"><span class="text-muted">Drafted by</span><span><?= htmlspecialchars((string)$cn['drafted_by_name']); ?></span></div>
                <div class="d-flex justify-content-between"><span class="text-muted">Drafted on</span><span><?= htmlspecialchars((string)$cn['drafted_on']); ?></span></div>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    var CN_ID = <?= (int)$cn['c0d']; ?>;
    var PROOT = '<?= PROOT; ?>';

    var b1 = document.getElementById('btn_issue');
    if (b1) b1.addEventListener('click', function () {
        $.confirm({
            title: 'Issue Credit Note',
            columnClass: 'col-md-6',
            content: '<div class="small mb-2 text-muted">Optional TRA EFD fields — leave blank if the CN is not fiscalised yet.</div>' +
                '<div class="row g-2 mb-2">' +
                '  <div class="col-6"><label class="form-label small">EFD receipt #</label><input id="cn_efd" class="form-control form-control-sm"></div>' +
                '  <div class="col-6"><label class="form-label small">EFD date</label><input id="cn_efd_date" type="date" class="form-control form-control-sm"></div>' +
                '</div>' +
                '<div class="row g-2 mb-2">' +
                '  <div class="col-6"><label class="form-label small">Original EFD (from invoice)</label><input id="cn_orig_efd" class="form-control form-control-sm"></div>' +
                '  <div class="col-6"><label class="form-label small">TRA verification code</label><input id="cn_tra" class="form-control form-control-sm"></div>' +
                '</div>',
            type: 'green',
            buttons: {
                yes: { text: 'Issue', btnClass: 'btn-success', action: function () {
                    var payload = {
                        cn_id: CN_ID,
                        efd_receipt_no:          document.getElementById('cn_efd').value || '',
                        efd_date:                document.getElementById('cn_efd_date').value || '',
                        original_efd_receipt_no: document.getElementById('cn_orig_efd').value || '',
                        tra_verification_code:   document.getElementById('cn_tra').value || ''
                    };
                    $.post(PROOT + 'CreditNotes/issueAj', payload, function (r) {
                        if (r && r.ok) { rsToast('Issued.', 'success'); setTimeout(function(){location.reload();}, 500); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }},
                cancel: function () {}
            }
        });
    });

    var b2 = document.getElementById('btn_cancel');
    if (b2) b2.addEventListener('click', function () {
        $.confirm({
            title: 'Cancel this draft?', type:'red',
            content: 'This draft will be marked CANCELLED.',
            buttons: {
                yes: { text: 'Cancel Draft', btnClass: 'btn-danger', action: function () {
                    $.post(PROOT + 'CreditNotes/cancelAj', { cn_id: CN_ID }, function (r) {
                        if (r && r.ok) { rsToast('Cancelled.', 'warning'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>
<?php $this->end(); ?>
