<?php $this->start('body');
    $pr    = $this->data['pr'];
    $lines = $this->data['lines'] ?? [];
    $canPc     = !empty($this->data['can_pc']);
    $canPm     = !empty($this->data['can_pm']);
    $canFm     = !empty($this->data['can_fm']);
    $canAcct   = !empty($this->data['can_acct']);
    $canReject = !empty($this->data['can_reject']);
    $canCancel = !empty($this->data['can_cancel']);
    $currency  = (string)($pr['currency'] ?? 'TZS');

    $statusChip = [
        'DRAFT'        => ['#F1F5F9','#334155','Draft'],
        'SUBMITTED'    => ['#EEF2F6','#7A8BA1','Submitted'],
        'PC_CONFIRMED' => ['#EAF2E8','#3F5C43','PC confirmed'],
        'PM_REVIEWED'  => ['#EAF2E8','#3F5C43','PM reviewed'],
        'SCHEDULED'    => ['#FEF3E7','#8B6914','Scheduled'],
        'PAID'         => ['#EAF2E8','#3F5C43','Paid'],
        'REJECTED'     => ['#F5EAE1','#C48579','Rejected'],
        'CANCELLED'    => ['#F1F5F9','#334155','Cancelled'],
    ];
    $sc = $statusChip[$pr['status']] ?? ['#F1F5F9','#334155',$pr['status']];

    // Ladder for the strip
    $rungs = [
        ['SUBMITTED',    'Raised',        'raised_on'],
        ['PC_CONFIRMED', 'PC confirm',    'pc_confirmed_at'],
        ['PM_REVIEWED',  'PM review',     'pm_reviewed_at'],
        ['SCHEDULED',    'FM schedule',   'fm_scheduled_at'],
        ['PAID',         'Accountant',    'acct_recorded_at'],
    ];
    $rungOrder = ['DRAFT'=>0,'SUBMITTED'=>1,'PC_CONFIRMED'=>2,'PM_REVIEWED'=>3,'SCHEDULED'=>4,'PAID'=>5];
    $curIdx = $rungOrder[$pr['status']] ?? 0;
?>

<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-money-check-alt me-2 text-muted"></i>PR <?= htmlspecialchars($pr['pr_no']); ?></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            <a href="<?= PROOT; ?>Lpos/view/<?= (int)$pr['lpo_id']; ?>"><?= htmlspecialchars($pr['lpo_no']); ?></a>
            &middot; <?= htmlspecialchars((string)($pr['payee_name'] ?: '')); ?>
            <?php if (!empty($pr['project_no'])): ?> &middot; <?= htmlspecialchars($pr['project_no']); ?><?php endif; ?>
            &middot; Raised <?= htmlspecialchars((string)$pr['raised_on']); ?> by <?= htmlspecialchars((string)$pr['raised_by_name']); ?>
        </div>
    </div>
    <div class="d-flex align-items-center gap-2">
        <?php if (!empty($pr['payment_schedule_id']) && $pr['status'] !== 'PAID'): ?>
            <a href="<?= PROOT; ?>PaymentSchedules/view/<?= (int)$pr['payment_schedule_id']; ?>" class="badge text-decoration-none" style="background:#FEF3E7;color:#8B6914;border:1px solid #8B6914;font-weight:600;padding:.4rem .55rem;font-size:.65rem;">
                <i class="fas fa-layer-group me-1"></i>Batch #<?= (int)$pr['payment_schedule_id']; ?>
            </a>
        <?php endif; ?>
        <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; ?>Lpos/view/<?= (int)$pr['lpo_id']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back to LPO</a>
    </div>
</div>

<?php if ($pr['status'] === 'REJECTED'): ?>
    <div class="alert py-2 small mb-3" style="background:#F5EAE1;border:1px solid #C48579;color:#C48579;font-size:.72rem;">
        <i class="fas fa-times-circle me-1"></i><strong>Rejected at <?= htmlspecialchars((string)$pr['rejected_at_stage']); ?></strong> by <?= htmlspecialchars((string)$pr['rejected_by_name']); ?> &middot; <?= htmlspecialchars((string)$pr['rejected_at']); ?>
        <?php if (!empty($pr['rejected_reason'])): ?><div class="mt-1">Reason: <em><?= htmlspecialchars((string)$pr['rejected_reason']); ?></em></div><?php endif; ?>
    </div>
<?php endif; ?>

<!-- Ladder strip -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body py-2">
        <div class="d-flex align-items-center justify-content-between" style="font-size:.7rem;">
            <?php foreach ($rungs as $i => [$state,$label,$stampCol]):
                $done = ($rungOrder[$state] <= $curIdx && $pr['status'] !== 'REJECTED' && $pr['status'] !== 'CANCELLED');
                $active = ($state === $pr['status']);
                $stamp = (string)($pr[$stampCol] ?? '');
                $col = $done ? '#3F5C43' : '#94A3B8';
                $bg  = $active ? '#EAF2E8' : ($done ? '#F8FAFC' : '#fff');
            ?>
                <div class="text-center flex-fill mx-1" style="padding:.3rem .4rem;border-radius:6px;background:<?= $bg; ?>;border:1px solid <?= $done?'#3F5C43':'#E2E8F0'; ?>;">
                    <div style="color:<?= $col; ?>;font-weight:600;text-transform:capitalize;"><i class="fas fa-<?= $done?'check-circle':'circle'; ?> me-1"></i><?= htmlspecialchars($label); ?></div>
                    <div class="text-muted" style="font-size:.6rem;"><?= $stamp !== '' ? htmlspecialchars(substr($stamp, 0, 16)) : ''; ?></div>
                </div>
                <?php if ($i < count($rungs) - 1): ?><i class="fas fa-chevron-right text-muted" style="font-size:.7rem;"></i><?php endif; ?>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<div class="row g-3">
    <div class="col-lg-8">
        <!-- PR lines -->
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header py-2 d-flex justify-content-between align-items-center" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;">
                <strong style="font-weight:600;color:#334155;font-size:.85rem;"><i class="fas fa-list me-1 text-muted"></i>Claimed against terms</strong>
                <span class="text-muted small">Total <strong style="color:#334155;"><?= $currency; ?> <?= number_format((float)$pr['requested_amount']); ?></strong></span>
            </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>Term</th><th style="width:120px;">Trigger</th><th class="text-end" style="width:120px;">Amount</th><th>Note</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($lines as $i => $ln): ?>
                            <tr>
                                <td class="text-muted small"><?= $i + 1; ?></td>
                                <td class="small">
                                    <strong><?= htmlspecialchars($ln['label']); ?></strong>
                                    <div class="text-muted" style="font-size:.62rem;">
                                        Term total: <?= $currency; ?> <?= number_format((float)$ln['computed_amount']); ?>
                                        <?php if ($ln['percent'] !== null): ?> &middot; <?= number_format((float)$ln['percent'], 0); ?>% of LPO<?php endif; ?>
                                    </div>
                                </td>
                                <td class="small text-muted" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ', (string)$ln['trigger_type']))); ?></td>
                                <td class="text-end small" style="font-weight:600;color:#334155;"><?= number_format((float)$ln['amount']); ?></td>
                                <td class="small text-muted" style="font-size:.65rem;"><?= htmlspecialchars((string)($ln['note'] ?? '')); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if (!empty($pr['notes'])): ?>
        <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;">Raiser notes</strong></div>
            <div class="card-body p-3 small"><?= nl2br(htmlspecialchars((string)$pr['notes'])); ?></div>
        </div>
        <?php endif; ?>

        <?php if ($pr['status'] === 'PAID'): ?>
        <div class="card border-0 shadow-sm mb-3" style="background:#F0F7F1;">
            <div class="card-header py-2 d-flex justify-content-between align-items-center" style="background:transparent;border-bottom:1px solid #C4DEC8;">
                <strong style="font-weight:600;font-size:.85rem;color:#3F5C43;"><i class="fas fa-check-circle me-2"></i>Payment posted</strong>
                <span class="text-muted small"><?= htmlspecialchars((string)$pr['acct_recorded_at']); ?></span>
            </div>
            <div class="card-body p-3">
                <div class="row g-3 small">
                    <div class="col-md-4"><div class="text-muted" style="font-size:.62rem;text-transform:capitalize;">Disbursement ref</div><div><code><?= htmlspecialchars((string)$pr['acct_disburse_ref']); ?></code></div></div>
                    <?php if (!empty($pr['acct_journal_entry_id'])): ?>
                        <div class="col-md-4"><div class="text-muted" style="font-size:.62rem;text-transform:capitalize;">Journal entry</div><div>#<?= (int)$pr['acct_journal_entry_id']; ?></div></div>
                    <?php else: ?>
                        <div class="col-md-4"><div class="text-muted" style="font-size:.62rem;text-transform:capitalize;">Journal entry</div><div class="text-muted"><em>skipped (COA setup)</em></div></div>
                    <?php endif; ?>
                    <?php if (!empty($pr['payment_schedule_id'])): ?>
                        <div class="col-md-4"><div class="text-muted" style="font-size:.62rem;text-transform:capitalize;">Payment schedule</div><div><a href="<?= PROOT; ?>PaymentSchedules/view/<?= (int)$pr['payment_schedule_id']; ?>">#<?= (int)$pr['payment_schedule_id']; ?></a></div></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Rung notes accordion -->
        <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;">Ladder audit</strong></div>
            <div class="card-body p-3 small">
                <?php $rows = [
                    ['PC confirm',       'pc_confirmed_at',  'pc_confirmed_by_name',  'pc_confirm_note'],
                    ['PM review',        'pm_reviewed_at',   'pm_reviewed_by_name',   'pm_review_note'],
                    ['FM schedule',      'fm_scheduled_at',  'fm_scheduled_by_name',  'fm_schedule_note'],
                    ['Accountant record','acct_recorded_at', 'acct_recorded_by_name', 'acct_record_note'],
                ]; ?>
                <?php foreach ($rows as [$lbl,$whenC,$whoC,$noteC]): ?>
                    <?php if (!empty($pr[$whenC])): ?>
                        <div class="mb-2 pb-2" style="border-bottom:1px solid #F1F5F9;">
                            <div style="font-weight:600;color:#334155;"><?= htmlspecialchars($lbl); ?></div>
                            <div class="text-muted" style="font-size:.65rem;"><?= htmlspecialchars((string)$pr[$whenC]); ?> &middot; <?= htmlspecialchars((string)$pr[$whoC]); ?></div>
                            <?php if (!empty($pr[$noteC])): ?><div style="font-size:.72rem;"><?= htmlspecialchars((string)$pr[$noteC]); ?></div><?php endif; ?>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
                <?php if (empty($pr['pc_confirmed_at'])): ?><div class="text-muted small">No rung actions yet.</div><?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Actions column -->
    <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 (!empty($pr['supplier_invoice_no'])): ?>
                    <div class="small text-muted" style="font-size:.65rem;">Supplier invoice: <strong><?= htmlspecialchars((string)$pr['supplier_invoice_no']); ?></strong><?= !empty($pr['supplier_invoice_date']) ? ' &middot; ' . htmlspecialchars((string)$pr['supplier_invoice_date']) : ''; ?></div>
                <?php endif; ?>
                <?php if ($canPc): ?>
                    <button type="button" class="btn btn-sm" data-rung="pc" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-check me-1"></i>PC confirm</button>
                <?php endif; ?>
                <?php if ($canPm): ?>
                    <button type="button" class="btn btn-sm" data-rung="pm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-check me-1"></i>PM review</button>
                <?php endif; ?>
                <?php if ($canFm): ?>
                    <button type="button" class="btn btn-sm" data-rung="fm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-calendar-plus me-1"></i>FM schedule</button>
                <?php endif; ?>
                <?php if ($canAcct): ?>
                    <button type="button" class="btn btn-sm" data-rung="acct" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-check-circle me-1"></i>Record disbursement</button>
                <?php endif; ?>
                <?php if ($canReject): ?>
                    <button type="button" class="btn btn-sm btn-outline-danger" id="btn_reject"><i class="fas fa-times me-1"></i>Reject</button>
                <?php endif; ?>
                <?php if ($canCancel): ?>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="btn_cancel"><i class="fas fa-ban me-1"></i>Cancel PR</button>
                <?php endif; ?>
                <?php if (!$canPc && !$canPm && !$canFm && !$canAcct && !$canReject && !$canCancel): ?>
                    <div class="text-muted small">No actions available at this state.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    var PR_ID = <?= (int)$pr['c0d']; ?>;
    var PROOT = '<?= PROOT; ?>';
    var STAGE = <?= json_encode((string)$pr['next_check_status']); ?>;

    function actWith(url, title, contentHtml, buildPayload) {
        $.confirm({
            title: title,
            columnClass: 'col-md-6',
            content: contentHtml,
            type: 'green',
            buttons: {
                yes: { text: 'Confirm', btnClass: 'btn-success', action: function () {
                    var payload = buildPayload();
                    payload.pr_id = PR_ID;
                    $.post(url, payload, function (r) {
                        if (r && r.ok) { rsToast('Advanced.', 'success'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
                }},
                cancel: function () {}
            }
        });
    }

    document.querySelectorAll('[data-rung]').forEach(function (b) {
        b.addEventListener('click', function () {
            var rung = b.getAttribute('data-rung');
            if (rung === 'pc') {
                actWith(PROOT + 'PaymentRequests/pcConfirmAj', 'PC confirm',
                    '<label class="form-label small">Note (optional)</label><textarea id="rung_note" rows="2" class="form-control form-control-sm"></textarea>',
                    function () { return { note: document.getElementById('rung_note').value || '' }; });
            } else if (rung === 'pm') {
                actWith(PROOT + 'PaymentRequests/pmReviewAj', 'PM review',
                    '<label class="form-label small">Note (optional)</label><textarea id="rung_note" rows="2" class="form-control form-control-sm"></textarea>',
                    function () { return { note: document.getElementById('rung_note').value || '' }; });
            } else if (rung === 'fm') {
                actWith(PROOT + 'PaymentRequests/fmScheduleAj', 'FM schedule',
                    '<div class="mb-2"><label class="form-label small">Payment schedule ID (optional)</label><input id="rung_sched" type="number" class="form-control form-control-sm" placeholder="Leave blank to skip"></div>' +
                    '<label class="form-label small">Note (optional)</label><textarea id="rung_note" rows="2" class="form-control form-control-sm"></textarea>',
                    function () { return {
                        payment_schedule_id: document.getElementById('rung_sched').value || '',
                        note: document.getElementById('rung_note').value || ''
                    }; });
            } else if (rung === 'acct') {
                actWith(PROOT + 'PaymentRequests/acctRecordAj', 'Record disbursement',
                    '<div class="mb-2"><label class="form-label small">Disbursement reference *</label><input id="rung_ref" class="form-control form-control-sm" placeholder="Cheque # / TIPS ID / M-Pesa txn" required></div>' +
                    '<div class="mb-2"><label class="form-label small">Journal entry # (optional)</label><input id="rung_je" type="number" class="form-control form-control-sm"></div>' +
                    '<label class="form-label small">Note (optional)</label><textarea id="rung_note" rows="2" class="form-control form-control-sm"></textarea>',
                    function () { return {
                        disburse_ref:     document.getElementById('rung_ref').value || '',
                        journal_entry_id: document.getElementById('rung_je').value || '',
                        note:             document.getElementById('rung_note').value || ''
                    }; });
            }
        });
    });

    var rj = document.getElementById('btn_reject');
    if (rj) rj.addEventListener('click', function () {
        $.confirm({
            title: 'Reject Payment Request',
            columnClass: 'col-md-6',
            content: '<div class="small mb-2 text-muted">Rejection sends the PR back for editing (or cancellation) by the raiser and restores term availability.</div>' +
                     '<label class="form-label small">Reason *</label><textarea id="rej_reason" rows="3" class="form-control form-control-sm" required></textarea>',
            type: 'red',
            buttons: {
                yes: { text: 'Reject', btnClass: 'btn-danger', action: function () {
                    var reason = document.getElementById('rej_reason').value || '';
                    if (!reason.trim()) { $.alert({title:'Reason required', type:'orange'}); return false; }
                    $.post(PROOT + 'PaymentRequests/rejectAj', { pr_id: PR_ID, stage: STAGE, reason: reason }, function (r) {
                        if (r && r.ok) { rsToast('Rejected.', 'warning'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }},
                cancel: function () {}
            }
        });
    });

    var cn = document.getElementById('btn_cancel');
    if (cn) cn.addEventListener('click', function () {
        $.confirm({
            title: 'Cancel this PR?', type: 'red',
            content: 'The Payment Request will be cancelled and term availability restored.',
            buttons: {
                yes: { text: 'Cancel PR', btnClass: 'btn-danger', action: function () {
                    $.post(PROOT + 'PaymentRequests/cancelAj', { pr_id: PR_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(); ?>
