<?php $this->start('body');
    $po      = $this->data['po'];
    $items   = $this->data['items'] ?? [];
    $project = $this->data['project'] ?? [];
    $isScrubbed = !empty($po['scrubbed_at']);
    $editable   = in_array($po['status'], ['DRAFT','CONFIRMED','SOURCING'], true);
?>
<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-broom me-1 text-muted"></i>
            <?= htmlspecialchars($po['client_po_no']); ?>
            <?php if ($isScrubbed): ?><span class="badge ms-2" style="background:#22c55e;color:#fff;">Scrubbed</span><?php endif; ?>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($po['customer_name']); ?> ·
            <?= htmlspecialchars($po['currency']); ?> <?= number_format((float)$po['total']); ?> total · <?= count($items); ?> lines
        </div>
    </div>
    <div>
        <a href="<?= PROOT; ?>GoodsScrub/scrubPo/<?= (int)($project['c0d'] ?? $po['project_id']); ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back</a>
        <a href="<?= PROOT; ?>GoodsClientPos/view/<?= (int)$po['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-file-invoice me-1"></i> Full PO</a>
    </div>
</div>

<?php if (!$editable): ?>
    <div class="alert alert-warning py-2 small">Status <code><?= htmlspecialchars($po['status']); ?></code> is past the scrub window — read-only.</div>
<?php endif; ?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong>Line items</strong>
        <div class="small text-muted">
            Sell <strong id="rs-sum-sell"><?= number_format((float)$po['subtotal_sell']); ?></strong> ·
            COG <strong id="rs-sum-cog"><?= number_format((float)$po['subtotal_cog']); ?></strong> ·
            VAT <?= (int)$po['vat_rate']; ?>% <strong id="rs-sum-vat"><?= number_format((float)$po['vat_amount']); ?></strong> ·
            Total <strong id="rs-sum-total"><?= number_format((float)$po['total']); ?></strong>
        </div>
    </div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th style="width:40px;">#</th>
                    <th>Description</th>
                    <th style="width:80px;">Qty</th>
                    <th style="width:70px;">UoM</th>
                    <th style="width:110px;" class="text-end">Sell</th>
                    <th style="width:110px;" class="text-end">COG</th>
                    <th style="width:70px;" class="text-end">Margin</th>
                    <th style="width:130px;" class="text-end">Line total</th>
                    <?php if ($editable): ?><th style="width:80px;" class="text-end">Save</th><?php endif; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $it):
                    $scrubbed = !empty($it['scrubbed_at']);
                ?>
                    <tr data-item="<?= (int)$it['c0d']; ?>" data-scrubbed="<?= $scrubbed ? '1' : '0'; ?>">
                        <td class="text-muted"><?= (int)$it['item_no']; ?></td>
                        <td>
                            <?php if ($editable): ?>
                                <input type="text" class="form-control form-control-sm rs-item-desc" value="<?= htmlspecialchars($it['description']); ?>">
                                <input type="text" class="form-control form-control-sm mt-1 rs-item-notes" value="<?= htmlspecialchars($it['notes'] ?? ''); ?>" placeholder="notes (optional)" style="font-size:.7rem;">
                            <?php else: ?>
                                <?= htmlspecialchars($it['description']); ?>
                                <?php if (!empty($it['notes'])): ?><div class="text-muted small"><?= htmlspecialchars($it['notes']); ?></div><?php endif; ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($editable): ?>
                                <input type="number" step="0.01" class="form-control form-control-sm text-end rs-item-qty" value="<?= (float)$it['qty']; ?>">
                            <?php else: ?><?= (float)$it['qty']; ?><?php endif; ?>
                        </td>
                        <td>
                            <?php if ($editable): ?>
                                <input type="text" class="form-control form-control-sm rs-item-unit" value="<?= htmlspecialchars($it['unit']); ?>">
                            <?php else: ?><?= htmlspecialchars($it['unit']); ?><?php endif; ?>
                        </td>
                        <td class="text-end">
                            <?php if ($editable): ?>
                                <input type="number" step="0.01" class="form-control form-control-sm text-end rs-item-sell" value="<?= (float)$it['unit_price_sell']; ?>">
                            <?php else: ?><?= number_format((float)$it['unit_price_sell']); ?><?php endif; ?>
                        </td>
                        <td class="text-end">
                            <?php if ($editable): ?>
                                <input type="number" step="0.01" class="form-control form-control-sm text-end rs-item-cog" value="<?= (float)$it['unit_price_cog']; ?>">
                            <?php else: ?><?= number_format((float)$it['unit_price_cog']); ?><?php endif; ?>
                        </td>
                        <td class="text-end">
                            <span class="rs-item-margin badge" style="background:<?= ((float)$it['margin_pct'] >= 15) ? '#22c55e' : '#f59e0b'; ?>;color:#fff;">
                                <?= number_format((float)$it['margin_pct'], 1); ?>%
                            </span>
                        </td>
                        <td class="text-end"><span class="rs-item-line-total"><?= number_format((float)$it['line_total_sell']); ?></span></td>
                        <?php if ($editable): ?>
                            <td class="text-end">
                                <button type="button" class="btn btn-sm btn-outline-primary rs-item-save"><i class="fas fa-save"></i></button>
                            </td>
                        <?php endif; ?>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($items)): ?>
                    <tr><td colspan="9" class="text-center text-muted py-4">No line items on this PO.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if ($editable): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3 d-flex align-items-end gap-3">
        <div class="flex-grow-1">
            <label class="form-label mb-1" style="font-size:.72rem;">Scrub notes (optional)</label>
            <input type="text" id="rs-scrub-notes" class="form-control form-control-sm" value="<?= htmlspecialchars($po['scrub_notes'] ?? ''); ?>">
        </div>
        <?php if ($isScrubbed): ?>
            <button type="button" class="btn btn-sm btn-outline-warning" onclick="rsUnscrub()"><i class="fas fa-undo me-1"></i> Unscrub</button>
        <?php else: ?>
            <button type="button" class="btn btn-sm btn-success" onclick="rsMarkScrubbed()"><i class="fas fa-check me-1"></i> Mark scrub complete</button>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

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

<?php $this->start('section_js'); ?>
<script>
(function () {
    const poId = <?= (int)$po['c0d']; ?>;
    const vatRate = <?= (float)$po['vat_rate']; ?>;

    function recomputeRow(tr) {
        const q = parseFloat(tr.querySelector('.rs-item-qty')?.value  || 0);
        const s = parseFloat(tr.querySelector('.rs-item-sell')?.value || 0);
        const c = parseFloat(tr.querySelector('.rs-item-cog')?.value  || 0);
        const lt = q * s;
        const marg = s > 0 ? ((s - c) / s) * 100 : 0;
        const badge = tr.querySelector('.rs-item-margin');
        if (badge) {
            badge.textContent = marg.toFixed(1) + '%';
            badge.style.background = marg >= 15 ? '#22c55e' : '#f59e0b';
        }
        const total = tr.querySelector('.rs-item-line-total');
        if (total) total.textContent = lt.toLocaleString();
    }

    function recomputeTotals() {
        let s = 0, c = 0;
        document.querySelectorAll('tr[data-item]').forEach(tr => {
            const q = parseFloat(tr.querySelector('.rs-item-qty')?.value  || 0);
            s += q * parseFloat(tr.querySelector('.rs-item-sell')?.value || 0);
            c += q * parseFloat(tr.querySelector('.rs-item-cog')?.value  || 0);
        });
        const vat = s * vatRate / 100;
        document.getElementById('rs-sum-sell').textContent  = Math.round(s).toLocaleString();
        document.getElementById('rs-sum-cog').textContent   = Math.round(c).toLocaleString();
        document.getElementById('rs-sum-vat').textContent   = Math.round(vat).toLocaleString();
        document.getElementById('rs-sum-total').textContent = Math.round(s + vat).toLocaleString();
    }

    document.querySelectorAll('tr[data-item]').forEach(tr => {
        tr.querySelectorAll('input').forEach(inp => {
            inp.addEventListener('input', () => { recomputeRow(tr); recomputeTotals(); });
        });
        const btn = tr.querySelector('.rs-item-save');
        if (!btn) return;
        btn.addEventListener('click', () => {
            const body = new URLSearchParams({
                item_id:         tr.dataset.item,
                description:     tr.querySelector('.rs-item-desc').value,
                qty:             tr.querySelector('.rs-item-qty').value,
                unit:            tr.querySelector('.rs-item-unit').value,
                unit_price_sell: tr.querySelector('.rs-item-sell').value,
                unit_price_cog:  tr.querySelector('.rs-item-cog').value,
                notes:           tr.querySelector('.rs-item-notes').value,
            });
            fetch('<?= PROOT; ?>GoodsScrub/saveItemAj', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: body.toString()
            }).then(r => r.json()).then(j => {
                if (typeof rsToast === 'function') rsToast(j.msg || (j.ok?'Saved':'Failed'), j.ok?'success':'error');
                else alert(j.msg || (j.ok?'Saved':'Failed'));
            }).catch(() => alert('Network error'));
        });
    });

    window.rsMarkScrubbed = function () {
        const notes = document.getElementById('rs-scrub-notes').value;
        if (!confirm('Mark this PO scrubbed? It will move to CONFIRMED and be ready for sourcing.')) return;
        fetch('<?= PROOT; ?>GoodsScrub/markScrubbedAj', {
            method: 'POST', headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body: 'po_id=' + poId + '&notes=' + encodeURIComponent(notes)
        }).then(r => r.json()).then(j => {
            alert(j.msg || (j.ok?'Done':'Failed'));
            if (j.ok) location.reload();
        });
    };
    window.rsUnscrub = function () {
        if (!confirm('Undo scrub? Only allowed if no RFQ has started against this PO.')) return;
        fetch('<?= PROOT; ?>GoodsScrub/unscrubAj', {
            method: 'POST', headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body: 'po_id=' + poId
        }).then(r => r.json()).then(j => {
            alert(j.msg || (j.ok?'Done':'Failed'));
            if (j.ok) location.reload();
        });
    };
})();
</script>
<?php $this->end(); ?>
