<?php $this->start('body');
    $c        = $this->data['customer'];
    $asAt     = $this->data['as_at'];
    $inv      = $this->data['invoices']   ?? [];
    $buckets  = $this->data['buckets']    ?? [];
    $rcp      = $this->data['receipts']   ?? [];
    $totInv   = (float)($this->data['total_invoiced']    ?? 0);
    $totPaid  = (float)($this->data['total_paid']        ?? 0);
    $totOut   = (float)($this->data['total_outstanding'] ?? 0);
    $totOver  = (float)($this->data['total_overpayment'] ?? 0);
    $oldest   = (int)  ($this->data['oldest_days']       ?? 0);
    $name     = trim(($c['fname'] ?? '') . ' ' . ($c['lname'] ?? ''));

    $bucketColor = function (string $bucket): string {
        return ['current'=>'#22c55e','1_30'=>'#3b82f6','31_60'=>'#f59e0b','61_90'=>'#f97316','90_plus'=>'#ef4444'][$bucket] ?? '#94a3b8';
    };
    $bucketLabel = ['current'=>'Current','1_30'=>'1-30 days','31_60'=>'31-60 days','61_90'=>'61-90 days','90_plus'=>'90+ days'];
?>

<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><?= htmlspecialchars($name); ?></h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($c['customer_no']); ?>
            <?php if ($c['customer_tier']): ?> · <?= htmlspecialchars(strtolower($c['customer_tier'])); ?><?php endif; ?>
            <?php if ($c['customer_tin']):  ?> · TIN <code class="text-body"><?= htmlspecialchars($c['customer_tin']); ?></code><?php endif; ?>
            · as at <strong><?= htmlspecialchars($asAt); ?></strong>
        </div>
    </div>
    <div>
        <a href="<?= PROOT; ?>CustomerStatement?as_at=<?= htmlspecialchars($asAt); ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> All customers</a>
        <a href="<?= PROOT; ?>Customers/view/<?= (int)$c['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-user me-1"></i> Customer profile</a>
    </div>
</div>

<form method="get" action="<?= PROOT; ?>CustomerStatement/view/<?= (int)$c['c0d']; ?>" 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-4"><label class="form-label">Statement date (as at)</label><input type="date" name="as_at" value="<?= htmlspecialchars($asAt); ?>" class="form-control form-control-sm"></div>
            <div class="col-md-8 text-end"><button type="submit" class="btn btn-sm btn-outline-secondary"><i class="fas fa-filter me-1"></i>Apply</button></div>
        </div>
    </div>
</form>

<div class="row g-3 mb-3">
    <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 invoiced</div><div style="font-weight:700;font-size:1.4rem;color:#3b82f6;">TZS <?= number_format($totInv); ?></div><div class="text-muted small mt-1"><?= count($inv); ?> 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 paid</div><div style="font-weight:700;font-size:1.4rem;color:#22c55e;">TZS <?= number_format($totPaid); ?></div><div class="text-muted small mt-1"><?= count($rcp); ?> receipt(s) shown</div></div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid <?= $totOut>0?'#f59e0b':'#22c55e'; ?> !important;"><div class="card-body p-3"><div class="text-muted small">Outstanding balance</div><div style="font-weight:700;font-size:1.6rem;color:<?= $totOut>0?'#f59e0b':'#22c55e'; ?>;">TZS <?= number_format($totOut); ?></div><?php if ($totOver > 0): ?><div class="text-muted small mt-1" style="color:#22c55e !important;">Credit (overpaid): TZS <?= number_format($totOver); ?></div><?php endif; ?></div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid <?= $oldest>90?'#ef4444':($oldest>0?'#f59e0b':'#22c55e'); ?> !important;"><div class="card-body p-3"><div class="text-muted small">Oldest days past due</div><div style="font-weight:700;font-size:1.6rem;color:<?= $oldest>90?'#ef4444':($oldest>0?'#f59e0b':'#22c55e'); ?>;"><?= $oldest > 0 ? $oldest . 'd' : '—'; ?></div><div class="text-muted small mt-1"><?= $oldest>90?'critical':($oldest>0?'past due':'current'); ?></div></div></div></div>
</div>

<!-- Ageing distribution -->
<?php $sumBuckets = max(array_sum($buckets), 0.01); ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Ageing distribution</strong></div>
    <div class="card-body p-3">
        <div class="d-flex" style="height:24px;border-radius:3px;overflow:hidden;">
            <?php foreach (['current','1_30','31_60','61_90','90_plus'] as $b):
                $val = (float)$buckets[$b];
                if ($val <= 0) continue;
                $pct = ($val / $sumBuckets) * 100;
            ?>
                <div style="width:<?= $pct; ?>%;background:<?= $bucketColor($b); ?>;" title="<?= $bucketLabel[$b]; ?>: <?= number_format($val); ?>"></div>
            <?php endforeach; ?>
        </div>
        <div class="row g-2 mt-3">
            <?php foreach (['current','1_30','31_60','61_90','90_plus'] as $b):
                $val = (float)$buckets[$b];
                $pct = ($val / $sumBuckets) * 100;
            ?>
                <div class="col">
                    <div style="border-left:3px solid <?= $bucketColor($b); ?>;padding-left:8px;">
                        <div class="text-muted small"><?= $bucketLabel[$b]; ?></div>
                        <div style="font-weight:600;"><?= $val > 0 ? number_format($val) : '—'; ?></div>
                        <?php if ($val > 0): ?><div class="text-muted small"><?= number_format($pct, 1); ?>% of outstanding</div><?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Invoices</strong></div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Invoice #</th><th>Date</th><th>Due</th><th>Project</th>
                    <th class="text-end">Total</th><th class="text-end">Paid</th><th class="text-end">Outstanding</th>
                    <th class="text-end">Days past due</th><th>Bucket</th><th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($inv as $i):
                    $bucket = $i['bucket'];
                    $displayNo = $i['sale_no'] ?: $i['invoice_ref'];
                    $days = (int)$i['days_past_due'];
                    $outVal = (float)$i['outstanding'];
                ?>
                    <tr style="<?= $bucket==='90_plus' && $outVal>0 ? 'background:#fef2f2;' : ($bucket==='61_90' && $outVal>0 ? 'background:#fff7ed;' : ''); ?>">
                        <td><a href="<?= PROOT; ?>Sales/view/<?= (int)$i['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($displayNo); ?></strong></a></td>
                        <td class="text-muted small"><?= htmlspecialchars($i['invoice_date']); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($i['effective_due']); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($i['project_no'] ?: '—'); ?></td>
                        <td class="text-end"><?= number_format((float)$i['total']); ?></td>
                        <td class="text-end text-muted"><?= number_format((float)$i['amount_paid']); ?></td>
                        <td class="text-end" style="font-weight:600;color:<?= $outVal>0?'#f59e0b':'#22c55e'; ?>;"><?= number_format($outVal); ?></td>
                        <td class="text-end"><?= $outVal > 0 && $days > 0 ? '<strong>' . $days . 'd</strong>' : ($outVal > 0 ? 'current' : '—'); ?></td>
                        <td>
                            <?php if ($outVal > 0): ?>
                                <span class="badge" style="background:<?= $bucketColor($bucket); ?>;color:#fff;"><?= $bucketLabel[$bucket]; ?></span>
                            <?php else: ?>
                                <span class="badge bg-success"><i class="fas fa-check me-1"></i>Paid</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end"><a href="<?= PROOT; ?>Sales/view/<?= (int)$i['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($inv)): ?>
                    <tr><td colspan="10" class="text-center text-muted py-3">No issued invoices for this customer.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if (!empty($rcp)): ?>
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white"><strong><i class="fas fa-receipt me-2 text-muted"></i>Recent receipts</strong></div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>Receipt #</th><th>Date</th><th>Type</th><th>EFD #</th><th>Method</th><th>Applied to</th><th class="text-end">Amount</th><th></th></tr>
            </thead>
            <tbody>
                <?php foreach ($rcp as $r):
                    $tc = ['EFD_VAT'=>'bg-success','EFD_NON_VAT'=>'bg-info text-white','NORMAL'=>'bg-light text-muted'][$r['receipt_type']] ?? 'bg-light text-muted';
                ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>Receipts/view/<?= (int)$r['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($r['receipt_no']); ?></strong></a></td>
                        <td class="text-muted small"><?= htmlspecialchars($r['receipt_date']); ?></td>
                        <td><span class="badge <?= $tc; ?>"><?= htmlspecialchars(strtolower(str_replace('_',' ',$r['receipt_type']))); ?></span></td>
                        <td class="text-muted small"><?= htmlspecialchars($r['efd_receipt_number'] ?: '—'); ?></td>
                        <td class="text-muted"><?= htmlspecialchars(ucwords(strtolower(str_replace('_',' ',$r['payment_method'])))); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($r['sale_no'] ?: $r['invoice_ref'] ?: '—'); ?></td>
                        <td class="text-end" style="font-weight:600;"><?= number_format((float)$r['amount']); ?></td>
                        <td class="text-end"><a href="<?= PROOT; ?>Receipts/view/<?= (int)$r['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

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