<?php $this->start('body');
    $stat        = $this->v('status');
    $statuses    = ['DRAFT','CONFIRMED','SOURCING','INVOICING','CLOSED','CANCELLED'];
    $fProj       = (int)($this->data['filter_project']       ?? 0);
    $fProjLbl    = (string)($this->data['filter_project_label'] ?? '');
    $fAssignedMe = !empty($this->data['filter_assigned_me']);
    $search      = (string)($this->data['search'] ?? '');
    $page        = (int)($this->data['page']  ?? 1);
    $pages       = (int)($this->data['pages'] ?? 1);
    $total       = (int)($this->data['total'] ?? 0);
    $perPage     = (int)($this->data['per_page'] ?? 25);
    $hideRevenue = (bool)($this->data['hide_revenue'] ?? false);

    // Build a query-string helper that preserves the other filters
    $qs = function (array $overrides = []) use ($fProj, $fAssignedMe, $stat, $search) {
        $q = [];
        if ($fProj > 0)    $q['project_id'] = $fProj;
        if ($fAssignedMe)  $q['assigned']   = 'me';
        if ($stat !== '')  $q['status']     = $stat;
        if ($search !== '') $q['q']         = $search;
        foreach ($overrides as $k => $v) { if ($v === null || $v === '') unset($q[$k]); else $q[$k] = $v; }
        return $q ? ('?' . http_build_query($q)) : '';
    };
?>

<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-contract me-2 text-muted"></i>Client POs
            <span class="text-muted ms-2" style="font-weight:400;font-size:.7rem;"><?= number_format($total); ?> total</span>
        </h5>
        <?php if ($fProj > 0 || $fAssignedMe || $search !== ''): ?>
            <div class="mt-1 d-flex flex-wrap gap-1 align-items-center small">
                <span style="color:#94A3B8;">Filtered:</span>
                <?php if ($fProj > 0): ?>
                    <span class="badge" style="background:#EAF2E8;color:#3F5C43;border:1px solid #7A9E7E;font-size:.7rem;">
                        <i class="fas fa-project-diagram me-1"></i><?= htmlspecialchars($fProjLbl ?: ('Project #' . $fProj)); ?>
                        <a href="<?= PROOT . 'GoodsClientPos' . $qs(['project_id' => null, 'page' => null]); ?>" style="color:#3F5C43;margin-left:.4em;" title="Clear project filter"><i class="fas fa-times"></i></a>
                    </span>
                <?php endif; ?>
                <?php if ($fAssignedMe): ?>
                    <span class="badge" style="background:#FEF3E7;color:#8B6914;border:1px solid #D4A574;font-size:.7rem;">
                        <i class="fas fa-user-check me-1"></i>Assigned to me
                        <a href="<?= PROOT . 'GoodsClientPos' . $qs(['assigned' => null, 'page' => null]); ?>" style="color:#8B6914;margin-left:.4em;" title="Clear assignment filter"><i class="fas fa-times"></i></a>
                    </span>
                <?php endif; ?>
                <?php if ($search !== ''): ?>
                    <span class="badge" style="background:#EEF2F6;color:#334155;border:1px solid #7A8BA1;font-size:.7rem;">
                        <i class="fas fa-search me-1"></i><?= htmlspecialchars($search); ?>
                        <a href="<?= PROOT . 'GoodsClientPos' . $qs(['q' => null, 'page' => null]); ?>" style="color:#334155;margin-left:.4em;" title="Clear search"><i class="fas fa-times"></i></a>
                    </span>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    <div class="d-flex gap-1 align-items-center">
        <form method="get" action="<?= PROOT; ?>GoodsClientPos" class="d-flex" style="max-width:260px;">
            <?php if ($stat !== ''): ?><input type="hidden" name="status" value="<?= htmlspecialchars($stat); ?>"><?php endif; ?>
            <?php if ($fProj > 0): ?><input type="hidden" name="project_id" value="<?= $fProj; ?>"><?php endif; ?>
            <?php if ($fAssignedMe): ?><input type="hidden" name="assigned" value="me"><?php endif; ?>
            <input type="text" name="q" class="form-control form-control-sm" value="<?= htmlspecialchars($search); ?>" placeholder="Search PO / customer / project&hellip;" style="font-size:.75rem;">
            <button type="submit" class="btn btn-sm ms-1" style="background:#F8FAFC;border:1px solid #7A8BA1;color:#334155;"><i class="fas fa-search"></i></button>
        </form>
        <?php if (!$fAssignedMe): ?>
            <a href="<?= PROOT . 'GoodsClientPos' . $qs(['assigned' => 'me', 'page' => null]); ?>" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #D4A574;color:#8B6914;">
                <i class="fas fa-inbox me-1"></i> My handovers
            </a>
        <?php endif; ?>
        <a href="<?= PROOT; ?>GoodsClientPos/add" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;">
            <i class="fas fa-plus me-1"></i> New Client PO
        </a>
    </div>
</div>

<div class="mb-2 d-flex flex-wrap gap-1">
    <a href="<?= PROOT . 'GoodsClientPos' . $qs(['status' => null, 'page' => null]); ?>" class="badge <?= $stat===''?'bg-dark':'bg-light text-muted'; ?>" style="text-decoration:none;padding:.35em .6em;">All</a>
    <?php foreach ($statuses as $s): ?>
        <a href="<?= PROOT . 'GoodsClientPos' . $qs(['status' => $s, 'page' => null]); ?>" class="badge <?= $stat===$s?'bg-dark':'bg-light text-muted'; ?>" style="text-decoration:none;padding:.35em .6em;text-transform:capitalize;">
            <?= htmlspecialchars(strtolower($s)); ?>
        </a>
    <?php endforeach; ?>
</div>

<div class="card border-0 shadow-sm">
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>PO #</th><th>Customer Ref</th><th>Date</th><th>Project</th><th>Customer</th><th>Module</th>
                    <?php if (!$hideRevenue): ?>
                        <th class="text-end">Sell</th>
                    <?php endif; ?>
                    <th class="text-end">Cog</th>
                    <?php if (!$hideRevenue): ?>
                        <th class="text-end">Margin %</th>
                        <th class="text-end">Invoiced</th>
                    <?php endif; ?>
                    <th>Status</th><th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($this->data['rows'] as $r):
                    $sc = ['DRAFT'=>'bg-light text-muted','CONFIRMED'=>'bg-info text-white','SOURCING'=>'bg-primary','INVOICING'=>'bg-warning text-dark','CLOSED'=>'bg-success','CANCELLED'=>'bg-secondary'][$r['status']] ?? 'bg-light text-muted';
                    $mgn = (float)$r['subtotal_sell'] > 0 ? (((float)$r['subtotal_sell'] - (float)$r['subtotal_cog']) / (float)$r['subtotal_sell']) * 100 : 0;
                ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>GoodsClientPos/view/<?= (int)$r['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($r['client_po_no']); ?></strong></a></td>
                        <td class="text-muted small"><?= htmlspecialchars($r['customer_po_ref'] ?: '—'); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($r['po_date']); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($r['project_no'] ?: '—'); ?></td>
                        <td><?= htmlspecialchars($r['customer_name']); ?></td>
                        <td><span class="badge bg-light text-muted" style="text-transform:capitalize;"><?= htmlspecialchars($r['source_module']); ?></span></td>
                        <?php if (!$hideRevenue): ?>
                            <td class="text-end"><?= number_format((float)$r['subtotal_sell']); ?></td>
                        <?php endif; ?>
                        <td class="text-end text-muted"><?= number_format((float)$r['subtotal_cog']); ?></td>
                        <?php if (!$hideRevenue): ?>
                            <td class="text-end" style="color:<?= $mgn<20?'#ef4444':($mgn<25?'#f59e0b':'#22c55e'); ?>;font-weight:600;"><?= number_format($mgn, 1); ?>%</td>
                            <td class="text-end text-muted"><?= number_format((float)$r['invoiced_total']); ?></td>
                        <?php endif; ?>
                        <td><span class="badge <?= $sc; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower($r['status'])); ?></span></td>
                        <td class="text-end"><a href="<?= PROOT; ?>GoodsClientPos/view/<?= (int)$r['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                    </tr>
                <?php endforeach; ?>
                <?php $colspan = $hideRevenue ? 9 : 12; ?>
                <?php if (empty($this->data['rows'])): ?>
                    <tr><td colspan="<?= $colspan; ?>" class="text-center text-muted py-4">
                        <?php if ($search !== '' || $stat !== '' || $fProj > 0 || $fAssignedMe): ?>
                            No Client POs match your filters.
                        <?php else: ?>
                            No Client POs yet &mdash; <a href="<?= PROOT; ?>GoodsClientPos/add">add the first one</a>.
                        <?php endif; ?>
                    </td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($pages > 1): ?>
        <div class="card-footer d-flex justify-content-between align-items-center py-2" style="background:#F8FAFC;font-size:.72rem;">
            <div class="text-muted">
                Page <strong><?= $page; ?></strong> of <?= $pages; ?>
                &middot; showing <?= number_format(min($perPage, count($this->data['rows']))); ?> of <?= number_format($total); ?>
            </div>
            <div class="d-flex align-items-center gap-1">
                <?php
                    $prev = max(1, $page - 1);
                    $next = min($pages, $page + 1);
                    $mkLink = function ($p, $label, $disabled = false, $active = false) use ($qs) {
                        $style = 'padding:.25rem .55rem;border:1px solid #E2E8F0;background:' . ($active ? '#334155' : '#fff') . ';color:' . ($active ? '#fff' : '#334155') . ';text-decoration:none;font-weight:' . ($active ? '600' : '400') . ';';
                        if ($disabled) $style .= 'opacity:.4;pointer-events:none;';
                        return '<a href="' . PROOT . 'GoodsClientPos' . htmlspecialchars($qs(['page' => $p])) . '" style="' . $style . '">' . $label . '</a>';
                    };
                    echo $mkLink(1,     '&laquo;', $page === 1);
                    echo $mkLink($prev, '&lsaquo;', $page === 1);
                    // window of 5 around current
                    $lo = max(1, $page - 2); $hi = min($pages, $page + 2);
                    for ($p = $lo; $p <= $hi; $p++) echo $mkLink($p, (string)$p, false, $p === $page);
                    echo $mkLink($next,  '&rsaquo;', $page === $pages);
                    echo $mkLink($pages, '&raquo;', $page === $pages);
                ?>
            </div>
        </div>
    <?php endif; ?>
</div>

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