<?php $this->start('body');
    $asAt        = $this->v('as_at');
    $opening     = (float)($this->data['opening_cash']  ?? 0);
    $closing     = (float)($this->data['closing_cash']  ?? 0);
    $totIn       = (float)($this->data['total_inflow']  ?? 0);
    $totOut      = (float)($this->data['total_outflow'] ?? 0);
    $projection  = $this->data['projection']    ?? [];
    $inflowLns   = $this->data['inflow_lines']  ?? [];
    $outflowLns  = $this->data['outflow_lines'] ?? [];
    $bucketColor = function (string $b): string {
        return ['0_30'=>'#22c55e','31_60'=>'#3b82f6','61_90'=>'#f59e0b','90_plus'=>'#ef4444'][$b] ?? '#94a3b8';
    };
    $lineBucket = function (int $days): string {
        if ($days <= 30) return '0_30';
        if ($days <= 60) return '31_60';
        if ($days <= 90) return '61_90';
        return '90_plus';
    };
?>

<?php $q = 'as_at=' . urlencode($asAt); ?>
<div class="d-flex align-items-center justify-content-between mb-3">
    <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-chart-line me-2 text-muted"></i>Cashflow Forecast</h5>
    <div class="btn-group">
        <a href="<?= PROOT; ?>CashflowForecast/xlsx?<?= $q; ?>" class="btn btn-sm" style="background:#faf6f0;border:1px solid #eae0d0;color:#4a3f36;"><i class="fas fa-file-excel me-1" style="color:#4a6b3f;"></i>Excel</a>
        <a href="<?= PROOT; ?>CashflowForecast/pdf?<?= $q; ?>"  class="btn btn-sm" style="background:#faf6f0;border:1px solid #eae0d0;color:#4a3f36;"><i class="fas fa-file-pdf   me-1" style="color:#8a4a3a;"></i>PDF</a>
    </div>
</div>

<form method="get" action="<?= PROOT; ?>CashflowForecast" class="card border-0 shadow-sm mb-3">
    <div class="card-body p-2">
        <div class="row g-2 align-items-end">
            <div class="col-md-3"><label class="form-label">As at</label><input type="date" name="as_at" value="<?= htmlspecialchars($asAt); ?>" class="form-control form-control-sm"></div>
            <div class="col-md-9 text-end">
                <button type="submit" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;"><i class="fas fa-filter me-1"></i>Refresh</button>
            </div>
        </div>
    </div>
</form>

<!-- Opening / Closing summary -->
<div class="row g-3 mb-3">
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid <?= $opening>=0?'#22c55e':'#ef4444'; ?> !important;"><div class="card-body p-3"><div class="text-muted small">Opening bank balance</div><div style="font-weight:700;font-size:1.5rem;color:<?= $opening>=0?'#22c55e':'#ef4444'; ?>;">TZS <?= number_format($opening); ?></div><div class="text-muted small mt-1">as at <?= htmlspecialchars($asAt); ?></div></div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body p-3"><div class="text-muted small">Total expected inflows</div><div style="font-weight:700;font-size:1.5rem;color:#22c55e;">+ TZS <?= number_format($totIn); ?></div><div class="text-muted small mt-1"><?= count($inflowLns); ?> open invoice(s)</div></div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body p-3"><div class="text-muted small">Total expected outflows</div><div style="font-weight:700;font-size:1.5rem;color:#ef4444;">− TZS <?= number_format($totOut); ?></div><div class="text-muted small mt-1"><?= count($outflowLns); ?> open LPO(s)</div></div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid <?= $closing>=0?'#22c55e':'#ef4444'; ?> !important;"><div class="card-body p-3"><div class="text-muted small">Projected closing balance</div><div style="font-weight:700;font-size:1.6rem;color:<?= $closing>=0?'#22c55e':'#ef4444'; ?>;">TZS <?= number_format($closing); ?></div><div class="text-muted small mt-1">after all AR + AP settled</div></div></div></div>
</div>

<!-- Per-bucket projection -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong><i class="fas fa-hourglass-half me-2 text-muted"></i>Projection by period · running balance</strong></div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Period</th>
                    <th class="text-end">Expected inflows</th>
                    <th class="text-end">Expected outflows</th>
                    <th class="text-end">Net movement</th>
                    <th class="text-end">Running balance</th>
                </tr>
            </thead>
            <tbody>
                <tr style="background:#f8fafc;">
                    <td><strong>Opening</strong> <span class="text-muted small">(today)</span></td>
                    <td class="text-end text-muted">—</td>
                    <td class="text-end text-muted">—</td>
                    <td class="text-end text-muted">—</td>
                    <td class="text-end" style="font-weight:700;color:<?= $opening>=0?'#22c55e':'#ef4444'; ?>;"><?= number_format($opening); ?></td>
                </tr>
                <?php foreach ($projection as $k => $p): ?>
                    <tr>
                        <td>
                            <span class="badge" style="background:<?= $bucketColor($k); ?>;color:#fff;"><?= htmlspecialchars($p['label']); ?></span>
                        </td>
                        <td class="text-end" style="color:<?= $p['inflow']>0?'#22c55e':'#94a3b8'; ?>;"><?= $p['inflow']>0 ? '+ ' . number_format($p['inflow']) : '—'; ?></td>
                        <td class="text-end" style="color:<?= $p['outflow']>0?'#ef4444':'#94a3b8'; ?>;"><?= $p['outflow']>0 ? '− ' . number_format($p['outflow']) : '—'; ?></td>
                        <td class="text-end" style="font-weight:600;color:<?= $p['net']>=0?'#22c55e':'#ef4444'; ?>;"><?= $p['net']>=0?'+ ':'− '; ?><?= number_format(abs($p['net'])); ?></td>
                        <td class="text-end" style="font-weight:700;color:<?= $p['running']>=0?'#22c55e':'#ef4444'; ?>;"><?= number_format($p['running']); ?></td>
                    </tr>
                <?php endforeach; ?>
                <tr style="background:#f8fafc;">
                    <td><strong>Closing</strong> <span class="text-muted small">(all AR + AP settled)</span></td>
                    <td class="text-end" style="color:#22c55e;">+ <?= number_format($totIn); ?></td>
                    <td class="text-end" style="color:#ef4444;">− <?= number_format($totOut); ?></td>
                    <td class="text-end" style="font-weight:600;color:<?= ($totIn-$totOut)>=0?'#22c55e':'#ef4444'; ?>;"><?= ($totIn-$totOut)>=0?'+ ':'− '; ?><?= number_format(abs($totIn-$totOut)); ?></td>
                    <td class="text-end" style="font-weight:700;color:<?= $closing>=0?'#22c55e':'#ef4444'; ?>;"><?= number_format($closing); ?></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<!-- Warning if any period ends negative -->
<?php $anyNegative = false; foreach ($projection as $p) if ($p['running'] < 0) { $anyNegative = true; break; } ?>
<?php if ($anyNegative || $closing < 0): ?>
<div class="alert alert-danger py-2 mb-3">
    <i class="fas fa-exclamation-triangle me-1"></i>
    <strong>Liquidity warning:</strong> projected running balance turns negative in at least one period. Action required — accelerate AR collection or delay AP payments.
</div>
<?php elseif (($closing - $opening) < 0): ?>
<div class="alert alert-warning py-2 mb-3">
    <i class="fas fa-info-circle me-1"></i>
    Cash position declining over the horizon (opening <?= number_format($opening); ?> → closing <?= number_format($closing); ?>). Review AR chase priorities.
</div>
<?php else: ?>
<div class="alert alert-success py-2 mb-3">
    <i class="fas fa-check-circle me-1"></i>
    Healthy trajectory — cash builds by <?= number_format($closing - $opening); ?> over the horizon (all AR settled &gt; all AP due).
</div>
<?php endif; ?>

<div class="row g-3">
    <!-- Inflows detail -->
    <div class="col-md-6">
        <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-arrow-down text-success me-2"></i>Expected inflows</strong>
                <span class="text-muted small">Σ <strong style="color:#22c55e;">+ <?= number_format($totIn); ?></strong></span>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0 align-middle">
                    <thead class="table-light">
                        <tr><th>Invoice #</th><th>Customer</th><th>Due</th><th>Days</th><th>Bucket</th><th class="text-end">Amount</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($inflowLns as $l):
                            $days = (int)$l['days_until_due']; $eff = max(0, $days);
                            $b = $lineBucket($eff);
                            $displayNo = $l['sale_no'] ?: $l['invoice_ref'];
                        ?>
                            <tr>
                                <td><a href="<?= PROOT; ?>Sales/view/<?= (int)$l['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($displayNo); ?></strong></a></td>
                                <td class="text-muted small"><?= htmlspecialchars($l['customer_name']); ?></td>
                                <td class="text-muted small"><?= htmlspecialchars($l['effective_due']); ?></td>
                                <td class="text-muted small"><?= $days < 0 ? '<span class="text-danger">' . abs($days) . 'd overdue</span>' : $days . 'd'; ?></td>
                                <td><span class="badge" style="background:<?= $bucketColor($b); ?>;color:#fff;font-size:.62rem;"><?= $days < 0 ? '0-30 (chase)' : $projection[$b]['label']; ?></span></td>
                                <td class="text-end" style="font-weight:600;color:#22c55e;">+ <?= number_format((float)$l['outstanding']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($inflowLns)): ?><tr><td colspan="6" class="text-center text-muted py-3">No open invoices.</td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Outflows detail -->
    <div class="col-md-6">
        <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-arrow-up text-danger me-2"></i>Expected outflows</strong>
                <span class="text-muted small">Σ <strong style="color:#ef4444;">− <?= number_format($totOut); ?></strong></span>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0 align-middle">
                    <thead class="table-light">
                        <tr><th>LPO #</th><th>Supplier</th><th>Due</th><th>Days</th><th>Bucket</th><th class="text-end">Amount</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($outflowLns as $l):
                            $days = (int)$l['days_until_due']; $eff = max(0, $days);
                            $b = $lineBucket($eff);
                        ?>
                            <tr>
                                <td><a href="<?= PROOT; ?>Lpos/view/<?= (int)$l['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($l['lpo_no']); ?></strong></a></td>
                                <td class="text-muted small"><?= htmlspecialchars($l['payee_name']); ?></td>
                                <td class="text-muted small"><?= htmlspecialchars($l['effective_due']); ?></td>
                                <td class="text-muted small"><?= $days < 0 ? '<span class="text-danger">' . abs($days) . 'd overdue</span>' : $days . 'd'; ?></td>
                                <td><span class="badge" style="background:<?= $bucketColor($b); ?>;color:#fff;font-size:.62rem;"><?= $days < 0 ? '0-30 (due)' : $projection[$b]['label']; ?></span></td>
                                <td class="text-end" style="font-weight:600;color:#ef4444;">− <?= number_format((float)$l['outstanding']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($outflowLns)): ?><tr><td colspan="6" class="text-center text-muted py-3">No open LPOs.</td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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