<?php $this->start('body');
    $s         = $this->data['s'];
    $items     = $this->data['items']    ?? [];
    $approval  = $this->data['approval'] ?? [];
    $steps     = $this->data['steps']    ?? [];
    $history   = $this->data['history']  ?? [];
    $je        = $this->data['je']       ?? [];
    $jls       = $this->data['je_lines'] ?? [];
    $curSid    = (int)($approval['current_step_id'] ?? 0);
    $curNo     = 0; foreach ($steps as $s2) if ((int)$s2['c0d']===$curSid) $curNo = (int)$s2['step_no'];
    $displayNo = $s['sale_no'] ?: $s['invoice_ref'];
    $sc = [
        'DRAFT'       => 'bg-light text-muted',
        'SUBMITTED'   => 'bg-info text-white',
        'PC_APPROVED' => 'bg-primary',
        'PM_APPROVED' => 'bg-primary',
        'ISSUED'      => 'bg-success',
        'CANCELLED'   => 'bg-secondary',
    ][$s['invoice_workflow_status']] ?? 'bg-light text-muted';
    $canSubmit = ($s['invoice_workflow_status'] === 'DRAFT');
?>

<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-file-invoice me-2 text-muted"></i><?= htmlspecialchars($displayNo); ?></h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($s['invoice_date']); ?> · <?= htmlspecialchars($s['customer_name']); ?>
            <?php if (!empty($s['project_no'])): ?> · <a href="<?= PROOT; ?>Projects/view/<?= (int)$s['project_id']; ?>"><?= htmlspecialchars($s['project_no']); ?></a><?php endif; ?>
            · <span class="badge <?= $sc; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$s['invoice_workflow_status']))); ?></span>
        </div>
    </div>
    <a href="<?= PROOT; ?>Sales" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> All invoices</a>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Subtotal</div><div style="font-weight:600;"><?= htmlspecialchars($s['currency']); ?> <?= number_format((float)$s['subtotal']); ?></div></div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">VAT @ <?= number_format((float)$s['vat_rate'],2); ?>%</div><div style="font-weight:600;"><?= number_format((float)$s['vat_amount']); ?></div></div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Total</div><div style="font-weight:700;font-size:1.1rem;"><?= htmlspecialchars($s['currency']); ?> <?= number_format((float)$s['total']); ?></div></div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Amount paid</div><div style="font-weight:600;"><?= number_format((float)$s['amount_paid']); ?></div><div class="text-muted small">balance <?= number_format((float)$s['total'] - (float)$s['amount_paid']); ?></div></div></div></div>
</div>

<?php $cpo = $this->data['cpo'] ?? []; ?>
<?php if (!empty($cpo)): ?>
<div class="alert alert-info py-2 mb-3">
    <i class="fas fa-file-contract me-1"></i> Drafted from Client PO
    <a href="<?= PROOT; ?>GoodsClientPos/view/<?= (int)$cpo['c0d']; ?>"><strong><?= htmlspecialchars($cpo['client_po_no']); ?></strong></a>
    <?php if ($cpo['customer_po_ref']): ?> · Their ref: <code class="text-body"><?= htmlspecialchars($cpo['customer_po_ref']); ?></code><?php endif; ?>
    · Contract total: <?= htmlspecialchars($cpo['currency']); ?> <?= number_format((float)$cpo['total']); ?>
</div>
<?php endif; ?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Line items</strong></div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th style="width:40px;">#</th><th>Description</th><th class="text-end">Qty</th><th>Unit</th><th class="text-end">Unit price</th><th class="text-end">Line total</th></tr>
            </thead>
            <tbody>
                <?php foreach ($items as $it): ?>
                    <tr>
                        <td class="text-muted"><?= (int)$it['item_no']; ?></td>
                        <td><?= htmlspecialchars($it['description']); ?></td>
                        <td class="text-end"><?= number_format((float)$it['qty'], (fmod((float)$it['qty'],1)==0?0:2)); ?></td>
                        <td class="text-muted"><?= htmlspecialchars($it['unit']); ?></td>
                        <td class="text-end"><?= number_format((float)$it['unit_price']); ?></td>
                        <td class="text-end" style="font-weight:600;"><?= number_format((float)$it['line_total']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if (!empty($approval)): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong><i class="fas fa-stream me-2 text-muted"></i>Approval Chain</strong>
        <a href="<?= PROOT; ?>FinChains/view/<?= (int)$approval['c0d']; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-arrow-right me-1"></i> Open approval</a>
    </div>
    <div class="card-body p-3">
        <div class="d-flex align-items-center flex-wrap gap-2">
            <?php foreach ($steps as $i => $st):
                $n  = (int)$st['step_no'];
                $stt = ($approval['status'] === 'APPROVED') ? 'done'
                    : (($approval['status'] === 'IN_PROGRESS' && $n < $curNo) ? 'done'
                    : (($approval['status'] === 'IN_PROGRESS' && $n === $curNo) ? 'now' : 'todo'));
                $ico  = ['done'=>'fa-check-circle','now'=>'fa-hourglass-half','todo'=>'fa-circle'][$stt];
                $col  = ['done'=>'#22c55e','now'=>'#f59e0b','todo'=>'#cbd5e1'][$stt];
            ?>
                <div class="d-flex align-items-center">
                    <div class="d-flex align-items-center gap-2 px-2 py-1 rounded" style="border:1px solid <?= $col; ?>33;background:<?= $col; ?>0d;">
                        <i class="fas <?= $ico; ?>" style="color:<?= $col; ?>;"></i>
                        <div style="line-height:1.05;">
                            <div style="font-weight:600;font-size:.78rem;"><?= htmlspecialchars($st['step_label']); ?></div>
                            <div class="text-muted" style="font-size:.62rem;text-transform:uppercase;"><?= htmlspecialchars($st['role_required']); ?></div>
                        </div>
                    </div>
                    <?php if ($i < count($steps) - 1): ?><i class="fas fa-chevron-right text-muted mx-1"></i><?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<?php elseif ($canSubmit): ?>
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-body p-3 d-flex align-items-center justify-content-between">
            <div class="text-muted small">This invoice is in <code>DRAFT</code>. Submit to send it into the <strong>GOODS_CUSTOMER_INVOICE</strong> chain (PC → PM → Accountant Ack).</div>
            <button type="button" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;" onclick="rsSubmitInvoice(<?= (int)$s['c0d']; ?>)">
                <i class="fas fa-paper-plane me-1"></i> Submit for review
            </button>
        </div>
    </div>
<?php endif; ?>

<?php
    $receipts   = $this->data['receipts']   ?? [];
    $balance    = (float)($this->data['balance'] ?? 0);
    $canReceive = !empty($this->data['can_receive']);
?>
<?php if (!empty($receipts) || $canReceive): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong><i class="fas fa-receipt me-2 text-muted"></i>Receipts</strong>
        <?php if ($canReceive): ?>
            <a href="<?= PROOT; ?>Receipts/record/<?= (int)$s['c0d']; ?>" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;">
                <i class="fas fa-plus me-1"></i> Record Receipt (balance: <?= htmlspecialchars($s['currency']); ?> <?= number_format($balance); ?>)
            </a>
        <?php endif; ?>
    </div>
    <?php if (!empty($receipts)): ?>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>Receipt #</th><th>Type</th><th>Date</th><th>EFD #</th><th>Method</th><th class="text-end">Amount</th><th class="text-end">VAT</th><th></th></tr>
            </thead>
            <tbody>
                <?php foreach ($receipts as $rc):
                    $rcCls = ['EFD_VAT'=>'bg-success','EFD_NON_VAT'=>'bg-info text-white','NORMAL'=>'bg-light text-muted'][$rc['receipt_type']] ?? 'bg-light text-muted';
                ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>Receipts/view/<?= (int)$rc['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($rc['receipt_no']); ?></strong></a></td>
                        <td><span class="badge <?= $rcCls; ?>"><?= htmlspecialchars(strtolower(str_replace('_',' ',$rc['receipt_type']))); ?></span></td>
                        <td class="text-muted small"><?= htmlspecialchars($rc['receipt_date']); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($rc['efd_receipt_number'] ?: '—'); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars(ucwords(strtolower(str_replace('_',' ',$rc['payment_method'])))); ?></td>
                        <td class="text-end" style="font-weight:600;"><?= htmlspecialchars($rc['currency']); ?> <?= number_format((float)$rc['amount']); ?></td>
                        <td class="text-end text-muted"><?= (float)$rc['efd_output_vat'] > 0 ? number_format((float)$rc['efd_output_vat']) : '—'; ?></td>
                        <td class="text-end"><a href="<?= PROOT; ?>Receipts/view/<?= (int)$rc['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php if (!empty($je)): ?>
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong><i class="fas fa-balance-scale me-2 text-muted"></i>Revenue journal</strong>
        <a href="<?= PROOT; ?>Journals/view/<?= (int)$je['c0d']; ?>" class="btn btn-sm btn-outline-primary"><?= htmlspecialchars($je['je_no']); ?> <i class="fas fa-arrow-right ms-1"></i></a>
    </div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>Account</th><th>Narrative</th><th class="text-end">Debit</th><th class="text-end">Credit</th></tr>
            </thead>
            <tbody>
                <?php foreach ($jls as $ln): ?>
                    <tr>
                        <td><code class="text-body"><?= htmlspecialchars($ln['account_code']); ?></code> · <?= htmlspecialchars($ln['account_name']); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($ln['narrative']); ?></td>
                        <td class="text-end"><?= (float)$ln['debit']  > 0 ? number_format((float)$ln['debit'])  : '—'; ?></td>
                        <td class="text-end"><?= (float)$ln['credit'] > 0 ? number_format((float)$ln['credit']) : '—'; ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<script>
function rsSubmitInvoice(sid) {
    if (!confirm('Submit this invoice for PC → PM → Accountant review?')) return;
    fetch('<?= PROOT; ?>Sales/submitAj', {
        method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'sale_id=' + encodeURIComponent(sid)
    }).then(r=>r.json()).then(j=>{
        alert(j.msg || (j.ok?'Submitted':'Failed'));
        if (j.ok) location.reload();
    });
}
</script>

<?php $this->end(); ?>
