<?php $this->start('body');
    $r     = $this->data['retirement'] ?? [];
    $lpo   = $this->data['lpo']        ?? [];
    $lines = $this->data['lines']      ?? [];
    $isReviewer = (bool)($this->data['is_reviewer'] ?? false);
    $isDiscovery = (bool)($this->data['is_discovery'] ?? false);
    $findings    = $this->data['findings'] ?? [];
    $currency = (string)($lpo['currency'] ?? 'TZS');
    $lpoAmt   = (float)($lpo['amount'] ?? 0);
    $bal      = abs((float)$r['variance']) < 0.005;
    $recChip = [
        'SHORTLIST' => ['#EAF2E8','#3F5C43','Shortlist'],
        'MAYBE'     => ['#FEF3E7','#8B6914','Maybe'],
        'REJECT'    => ['#F5EAE1','#C48579','Reject'],
    ];
    $shortlistCount = 0; foreach ($findings as $f) if ($f['recommendation'] === 'SHORTLIST') $shortlistCount++;
    $statusChip = [
        'DRAFT'     => ['#F1F5F9','#334155','Draft'],
        'SUBMITTED' => ['#EEF2F6','#7A8BA1','Submitted'],
        'APPROVED'  => ['#EAF2E8','#3F5C43','Approved'],
        'REJECTED'  => ['#F5EAE1','#C48579','Bounced back'],
    ];
    $sc = $statusChip[$r['status']] ?? ['#F1F5F9','#334155',$r['status']];
    $canAct = $isReviewer && $r['status'] === 'SUBMITTED';
?>

<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-dollar me-2 text-muted"></i>Retirement · <?= htmlspecialchars($lpo['lpo_no']); ?></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            <?= htmlspecialchars(ucfirst(strtolower(str_replace('_',' ', (string)$lpo['lpo_type'])))); ?>
            · Advance: <strong><?= $currency; ?> <?= number_format($lpoAmt); ?></strong>
            · Requested by <?= htmlspecialchars((string)$lpo['requested_by_name']); ?>
        </div>
    </div>
    <div>
        <span class="badge me-2" style="background:<?= $sc[0]; ?>;color:<?= $sc[1]; ?>;border:1px solid <?= $sc[1]; ?>;font-size:.65rem;text-transform:capitalize;"><?= htmlspecialchars($sc[2]); ?></span>
        <a href="<?= PROOT; ?>Lpos/view/<?= (int)$lpo['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back to LPO</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 py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;">
                <i class="fas fa-list me-1 text-muted"></i>Spend lines
            </div>
            <div class="table-responsive">
                <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:130px;">Amount</th>
                            <th style="width:150px;">Notes</th>
                            <th style="width:130px;">Receipt</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($lines as $ln): ?>
                            <tr>
                                <td class="text-muted small"><?= (int)$ln['line_no']; ?></td>
                                <td class="small"><?= htmlspecialchars($ln['description']); ?></td>
                                <td class="text-end small" style="font-weight:600;color:#334155;"><?= number_format((float)$ln['amount']); ?></td>
                                <td class="small text-muted"><?= htmlspecialchars((string)$ln['notes']); ?></td>
                                <td class="small">
                                    <?php if (!empty($ln['receipt_attachment_path'])): ?>
                                        <a href="<?= PROOT; ?>Retirements/receiptDownload/<?= (int)$ln['c0d']; ?>" target="_blank" class="text-decoration-none"><i class="fas fa-paperclip me-1" style="color:#7A8BA1;"></i>Open</a>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($lines)): ?>
                            <tr><td colspan="5" class="text-center text-muted py-3" style="font-size:.72rem;">No spend lines.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if ($isDiscovery): ?>
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header py-2 small d-flex align-items-center justify-content-between" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;">
                <div><i class="fas fa-binoculars me-1 text-muted"></i>Discovery findings</div>
                <div class="text-muted" style="font-weight:400;font-size:.65rem;">
                    <?= count($findings); ?> profiled · <?= $shortlistCount; ?> shortlisted for RFQ
                </div>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0 align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>Supplier</th>
                            <th>Contact</th>
                            <th class="text-end" style="width:130px;">Quote</th>
                            <th class="text-center" style="width:70px;">Sample</th>
                            <th style="width:110px;">Verdict</th>
                            <th style="width:220px;">Rationale</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($findings as $f):
                            $fc = $recChip[$f['recommendation']] ?? $recChip['MAYBE'];
                        ?>
                            <tr>
                                <td class="small">
                                    <strong><?= htmlspecialchars($f['supplier_name']); ?></strong>
                                    <?php if (!empty($f['country'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($f['country']); ?></div><?php endif; ?>
                                </td>
                                <td class="small text-muted">
                                    <?= htmlspecialchars($f['contact_name']); ?>
                                    <?php if (!empty($f['phone']) || !empty($f['email'])): ?><div style="font-size:.62rem;"><?= htmlspecialchars(trim($f['phone'] . ' · ' . $f['email'], ' ·')); ?></div><?php endif; ?>
                                </td>
                                <td class="text-end small">
                                    <?php if ((int)$f['quote_received'] === 1 && !empty($f['quote_amount'])): ?>
                                        <span style="font-weight:600;color:#334155;"><?= htmlspecialchars($f['quote_currency'] ?: $currency); ?> <?= number_format((float)$f['quote_amount']); ?></span>
                                        <?php if (!empty($f['quote_lead_time_days'])): ?><div class="text-muted" style="font-size:.62rem;"><?= (int)$f['quote_lead_time_days']; ?>d</div><?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <?php if ((int)$f['sample_received'] === 1): ?><i class="fas fa-check" style="color:#3F5C43;"></i><?php else: ?><span class="text-muted">—</span><?php endif; ?>
                                </td>
                                <td><span class="badge" style="background:<?= $fc[0]; ?>;color:<?= $fc[1]; ?>;border:1px solid <?= $fc[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($fc[2]); ?></span></td>
                                <td class="small text-muted"><?= htmlspecialchars((string)$f['rationale']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($findings)): ?>
                            <tr><td colspan="6" class="text-center text-muted py-3" style="font-size:.72rem;">No supplier profiles captured.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!empty($r['reviewer_notes'])): ?>
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;">
                    <i class="fas fa-comment-dots me-1 text-muted"></i>Reviewer notes
                </div>
                <div class="card-body small" style="color:#334155;">
                    <?= nl2br(htmlspecialchars((string)$r['reviewer_notes'])); ?>
                    <div class="text-muted mt-2" style="font-size:.62rem;">
                        by <?= htmlspecialchars((string)$r['reviewer_name']); ?>
                        · <?= htmlspecialchars(date('d M · H:i', strtotime((string)$r['reviewed_on']))); ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <div class="col-lg-4">
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;">
                <i class="fas fa-balance-scale me-1 text-muted"></i>Reconcile
            </div>
            <div class="card-body p-3">
                <div class="d-flex justify-content-between mb-1 small"><span class="text-muted">Advance issued</span><span style="font-weight:600;color:#334155;"><?= $currency; ?> <?= number_format($lpoAmt); ?></span></div>
                <div class="d-flex justify-content-between mb-1 small"><span class="text-muted">Total spent</span><span style="font-weight:600;color:#334155;"><?= $currency; ?> <?= number_format((float)$r['total_spent']); ?></span></div>
                <div class="d-flex justify-content-between mb-1 small"><span class="text-muted">Cash returned</span><span style="font-weight:600;color:#334155;"><?= $currency; ?> <?= number_format((float)$r['cash_returned']); ?></span></div>
                <hr class="my-2">
                <div class="d-flex justify-content-between small">
                    <span class="text-muted">Variance</span>
                    <span class="badge" style="background:<?= $bal ? '#EAF2E8' : '#F5EAE1'; ?>;color:<?= $bal ? '#3F5C43' : '#C48579'; ?>;border:1px solid <?= $bal ? '#3F5C43' : '#C48579'; ?>;font-size:.65rem;">
                        <?= $currency; ?> <?= number_format((float)$r['variance']); ?>
                    </span>
                </div>
                <?php if (!empty($r['journal_entry_id'])): ?>
                    <hr class="my-2">
                    <div class="small text-muted"><i class="fas fa-book me-1"></i>Journal posted: <strong>#<?= (int)$r['journal_entry_id']; ?></strong></div>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($canAct): ?>
            <div class="card border-0 shadow-sm">
                <div class="card-body p-3">
                    <button type="button" id="btn_approve" class="btn btn-sm w-100 mb-2" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                        <i class="fas fa-check me-1"></i>Approve retirement
                    </button>
                    <button type="button" id="btn_reject" class="btn btn-sm w-100" style="background:#fff;border:1px solid #C48579;color:#C48579;font-weight:600;">
                        <i class="fas fa-undo me-1"></i>Bounce back to requester
                    </button>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php if ($canAct): ?>
<script>
(function () {
    var RID = <?= (int)$r['c0d']; ?>;

    document.getElementById('btn_approve').addEventListener('click', function () {
        $.confirm({
            title: 'Approve retirement?',
            content:
                '<div class="small mb-2">The advance will be closed and a journal will be posted (best-effort).</div>' +
                '<label class="form-label small">Notes (optional)</label>' +
                '<textarea id="ap_notes" class="form-control form-control-sm" rows="2" placeholder="Anything worth noting…"></textarea>',
            type: 'green',
            buttons: {
                yes: { text: 'Approve', btnClass: 'btn-success', action: function () {
                    var notes = document.getElementById('ap_notes').value || '';
                    $.post('<?= PROOT; ?>Retirements/approveAj', { retirement_id: RID, notes: notes }, function (r) {
                        if (r && r.ok) { rsToast(r.msg || 'Approved.', 'success'); setTimeout(function(){ location.reload(); }, 500); }
                        else $.alert({title:'Could not approve', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }},
                cancel: function () {}
            }
        });
    });

    document.getElementById('btn_reject').addEventListener('click', function () {
        $.confirm({
            title: 'Bounce retirement back?',
            content:
                '<label class="form-label small">Reason *</label>' +
                '<textarea id="rj_reason" class="form-control form-control-sm" rows="3" placeholder="Explain what needs fixing…"></textarea>',
            type: 'red',
            buttons: {
                yes: { text: 'Bounce back', btnClass: 'btn-danger', action: function () {
                    var reason = (document.getElementById('rj_reason').value || '').trim();
                    if (!reason) { $.alert({title:'Reason required', content:'Explain why you are bouncing this back.', type:'orange'}); return false; }
                    $.post('<?= PROOT; ?>Retirements/rejectAj', { retirement_id: RID, reason: reason }, function (r) {
                        if (r && r.ok) { rsToast('Bounced back.', 'success'); setTimeout(function(){ location.reload(); }, 500); }
                        else $.alert({title:'Could not bounce', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>
<?php endif; ?>

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