<?php $this->start('body');
    $rows      = $this->data['rows']      ?? [];
    $f         = $this->data['filter']    ?? [];
    $page      = (int)($this->data['page']      ?? 1);
    $pageSize  = (int)($this->data['page_size'] ?? 25);
    $total     = (int)($this->data['total']     ?? count($rows));
    $lastPage  = (int)($this->data['last_page'] ?? 1);
    // Query string preserving all filters (no page — pagination links append their own).
    $q  = 'stage='  . urlencode((string)($f['stage']        ?? ''))
        . '&status='. urlencode((string)($f['status']       ?? ''))
        . '&source='. urlencode((string)($f['source']       ?? ''))
        . '&type='  . urlencode((string)($f['project_type'] ?? ''))
        . '&q='     . urlencode((string)($f['q']            ?? ''));

    $stageChip = [
        'PREP'             => '#94A3B8', 'SUBMISSION' => '#7A8BA1', 'FOLLOW_UP' => '#D4A574',
        'OPENING'          => '#7A9E7E', 'NEGOTIATIONS' => '#D4A574', 'AWARDED' => '#166534',
        'CONTRACT_SIGNING' => '#166534', 'EXECUTION' => '#334155',
    ];
    $statusChip = [
        'OPEN' => '#7A8BA1', 'WON' => '#166534', 'LOST' => '#C48579', 'CANCELLED' => '#94A3B8', 'WITHDRAWN' => '#94A3B8',
    ];
    $sourceLabel = ['NEST_PUBLIC' => 'NeST · public', 'PRIVATE_CLIENT' => 'Private client', 'INVITATION' => 'Invitation', 'REFERRAL' => 'Referral', 'WALK_IN' => 'Walk-in'];
    $typeChip = [
        'goods'       => ['label' => 'Goods',       'color' => '#7A9E7E', 'bg' => '#EAF2E8'],
        'services'    => ['label' => 'Services',    'color' => '#7A8BA1', 'bg' => '#F1F5F9'],
        'works'       => ['label' => 'Works',       'color' => '#B87A5A', 'bg' => '#F5EAE1'],
        'consultancy' => ['label' => 'Consultancy', 'color' => '#D4A574', 'bg' => '#FEF3E7'],
    ];

    // KPI cards summarise this page only (the register footer surfaces the true total across all pages).
    $totalEst = 0; $totalSub = 0; $open = 0; $won = 0; $overdue = 0;
    foreach ($rows as $t) {
        $totalEst += (float)$t['estimated_value']; $totalSub += (float)$t['submission_amount'];
        if ($t['tender_status'] === 'OPEN') $open++;
        if ($t['tender_status'] === 'WON')  $won++;
        if (!empty($t['deadline_date']) && $t['deadline_date'] < date('Y-m-d') && $t['tender_status'] === 'OPEN') $overdue++;
    }
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <h5 class="mb-0" style="font-weight:600;color:#334155;"><i class="fas fa-file-signature me-2" style="color:#7A8BA1;"></i>Tender Register</h5>
    <div class="d-flex gap-2">
        <a href="<?= PROOT; ?>Tenders/xlsx?<?= $q; ?>" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;"><i class="fas fa-file-excel me-1" style="color:#7A9E7E;"></i>Excel</a>
        <a href="<?= PROOT; ?>Tenders/pdf?<?= $q; ?>"  class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;"><i class="fas fa-file-pdf   me-1" style="color:#C48579;"></i>PDF</a>
        <?php if (UserGroups::can('Tenders','add')): ?><a href="<?= PROOT; ?>Tenders/add" class="btn btn-sm" style="background:#7A8BA1;border-color:#7A8BA1;color:#fff;font-weight:600;"><i class="fas fa-plus me-1"></i>New tender</a><?php endif; ?>
    </div>
</div>

<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 #7A8BA1 !important;background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:capitalize;letter-spacing:.2px;font-size:.7rem;color:#64748B;font-weight:600;">Total tenders <span style="font-size:.6rem;color:#94A3B8;">(matching filters)</span></div>
        <div style="font-weight:700;font-size:1.4rem;color:#334155;"><?= $total; ?></div>
        <div class="text-muted small" style="color:#64748B;">page <?= $page; ?> of <?= $lastPage; ?> · <?= $open; ?> open, <?= $won; ?> won <span style="color:#94A3B8;">(this page)</span></div>
    </div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid #7A9E7E !important;background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:capitalize;letter-spacing:.2px;font-size:.7rem;color:#64748B;font-weight:600;">Estimated pipeline</div>
        <div style="font-weight:700;font-size:1.4rem;color:#334155;">TZS <?= number_format($totalEst); ?></div>
    </div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid #D4A574 !important;background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:capitalize;letter-spacing:.2px;font-size:.7rem;color:#64748B;font-weight:600;">Submitted (bid amount)</div>
        <div style="font-weight:700;font-size:1.4rem;color:#334155;">TZS <?= number_format($totalSub); ?></div>
    </div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid <?= $overdue > 0 ? '#C48579' : '#E2E8F0'; ?> !important;background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:capitalize;letter-spacing:.2px;font-size:.7rem;color:#64748B;font-weight:600;">Deadline overdue</div>
        <div style="font-weight:700;font-size:1.4rem;color:<?= $overdue > 0 ? '#C48579' : '#334155'; ?>;"><?= $overdue; ?></div>
    </div></div></div>
</div>

<form method="get" action="<?= PROOT; ?>Tenders" class="card border-0 shadow-sm mb-3" style="background:#F8FAFC;">
    <div class="card-body p-2">
        <div class="row g-2 align-items-end">
            <div class="col-md-3"><label class="form-label" style="color:#334155;">Search</label><input type="text" name="q" value="<?= htmlspecialchars((string)($f['q'] ?? '')); ?>" placeholder="no, title, buyer…" class="form-control form-control-sm"></div>
            <div class="col-md-2"><label class="form-label" style="color:#334155;">Type</label>
                <select name="type" class="form-select form-select-sm"><option value="">All</option>
                    <?php foreach (['goods','services','works','consultancy'] as $tp): ?>
                        <option value="<?= $tp; ?>" <?= ($f['project_type'] ?? '') === $tp ? 'selected' : ''; ?>><?= ucfirst($tp); ?></option>
                    <?php endforeach; ?>
                </select></div>
            <div class="col-md-2"><label class="form-label" style="color:#334155;">Source</label>
                <select name="source" class="form-select form-select-sm"><option value="">All</option>
                    <?php foreach (Tenders::SOURCES as $s): ?><option value="<?= $s; ?>" <?= ($f['source'] ?? '') === $s ? 'selected' : ''; ?>><?= $sourceLabel[$s] ?? $s; ?></option><?php endforeach; ?>
                </select></div>
            <div class="col-md-2"><label class="form-label" style="color:#334155;">Stage</label>
                <select name="stage" class="form-select form-select-sm"><option value="">All</option>
                    <?php foreach (Tenders::STAGES as $s): ?><option value="<?= $s; ?>" <?= ($f['stage'] ?? '') === $s ? 'selected' : ''; ?>><?= ucfirst(strtolower(str_replace('_',' ',$s))); ?></option><?php endforeach; ?>
                </select></div>
            <div class="col-md-1"><label class="form-label" style="color:#334155;">Status</label>
                <select name="status" class="form-select form-select-sm"><option value="">All</option>
                    <?php foreach (['OPEN','WON','LOST','CANCELLED','WITHDRAWN'] as $s): ?><option value="<?= $s; ?>" <?= ($f['status'] ?? '') === $s ? 'selected' : ''; ?>><?= $s; ?></option><?php endforeach; ?>
                </select></div>
            <div class="col-md-2 text-end"><button type="submit" class="btn btn-sm" style="background:#7A8BA1;border-color:#7A8BA1;color:#fff;font-weight:600;"><i class="fas fa-filter me-1"></i>Filter</button>
                <a href="<?= PROOT; ?>Tenders" class="btn btn-sm ms-1" style="background:#F1F5F9;border:1px solid #E2E8F0;color:#64748B;" title="Clear all filters"><i class="fas fa-times"></i></a>
            </div>
        </div>
    </div>
</form>

<div class="card border-0 shadow-sm">
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead style="background:#F1F5F9;">
                <tr>
                    <th style="color:#334155;">Tender #</th>
                    <th style="color:#334155;">Title</th>
                    <th style="color:#334155;">Buyer / customer</th>
                    <th style="color:#334155;">Source</th>
                    <th style="color:#334155;">Type</th>
                    <th class="text-end" style="color:#334155;">Estimated</th>
                    <th style="color:#334155;">Deadline</th>
                    <th style="color:#334155;">Stage</th>
                    <th style="color:#334155;">Status</th>
                    <th style="color:#334155;">Project</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $t):
                    $sChip = $stageChip[$t['tender_stage']] ?? '#94A3B8';
                    $stChip = $statusChip[$t['tender_status']] ?? '#94A3B8';
                    $overdueRow = !empty($t['deadline_date']) && $t['deadline_date'] < date('Y-m-d') && $t['tender_status'] === 'OPEN';
                ?>
                    <tr>
                        <td style="color:#334155;font-weight:500;"><?= htmlspecialchars($t['tender_no']); ?></td>
                        <td style="color:#334155;"><?= htmlspecialchars($t['tender_title']); ?>
                            <?php if (!empty($t['source_ref'])): ?><div class="small" style="color:#94A3B8;font-size:.66rem;"><?= htmlspecialchars((string)$t['source_ref']); ?></div><?php endif; ?>
                        </td>
                        <td class="text-muted small" style="color:#64748B;"><?= htmlspecialchars((string)$t['buyer_name']); ?>
                            <?php if (!empty($t['customer_display'])): ?><div style="color:#94A3B8;font-size:.66rem;">customer: <?= htmlspecialchars((string)$t['customer_display']); ?></div><?php endif; ?>
                        </td>
                        <td class="text-muted small" style="color:#64748B;"><span class="badge" style="background:#F1F5F9;color:#334155;font-size:.62rem;text-transform:capitalize;"><?= $sourceLabel[$t['source_type']] ?? $t['source_type']; ?></span></td>
                        <td><?php $tc = $typeChip[$t['project_type']] ?? ['label' => ucfirst((string)$t['project_type']), 'color' => '#94A3B8', 'bg' => '#F1F5F9']; ?>
                            <span class="badge" style="background:<?= $tc['bg']; ?>;color:<?= $tc['color']; ?>;border:1px solid <?= $tc['color']; ?>;font-size:.62rem;text-transform:capitalize;"><?= $tc['label']; ?></span>
                        </td>
                        <td class="text-end" style="color:#334155;font-weight:500;"><?= number_format((float)$t['estimated_value']); ?></td>
                        <td class="text-muted small" style="color:<?= $overdueRow ? '#C48579' : '#64748B'; ?>;"><?= htmlspecialchars((string)($t['deadline_date'] ?? '—')); ?></td>
                        <td><span class="badge" style="background:<?= $sChip; ?>;color:#fff;font-size:.62rem;"><?= str_replace('_',' ',$t['tender_stage']); ?></span></td>
                        <td><span class="badge" style="background:<?= $stChip; ?>;color:#fff;font-size:.62rem;text-transform:capitalize;"><?= strtolower($t['tender_status']); ?></span></td>
                        <td class="text-muted small">
                            <?php if (!empty($t['project_no'])): ?><a href="<?= PROOT; ?>Projects" style="color:#166534;font-weight:500;"><?= htmlspecialchars($t['project_no']); ?></a><?php else: ?>—<?php endif; ?>
                        </td>
                        <td class="text-end"><a href="<?= PROOT; ?>Tenders/view/<?= (int)$t['c0d']; ?>" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;"><i class="fas fa-eye me-1" style="color:#7A8BA1;"></i>View</a></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="11" class="text-center py-4" style="color:#94A3B8;">No tenders. <?php if (UserGroups::can('Tenders','add')): ?><a href="<?= PROOT; ?>Tenders/add" style="color:#7A8BA1;font-weight:600;">Add one</a>.<?php endif; ?></td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($lastPage > 1):
        $firstIdx = ($page - 1) * $pageSize + 1;
        $lastIdx  = min($total, $page * $pageSize);
        $baseHref = PROOT . 'Tenders?' . $q . '&page=';
        // Windowed page list: first, last, and window of 2 around current.
        $window = 2;
        $pages = [];
        for ($i = 1; $i <= $lastPage; $i++) {
            if ($i === 1 || $i === $lastPage || abs($i - $page) <= $window) $pages[] = $i;
        }
    ?>
    <div class="card-footer bg-white d-flex align-items-center justify-content-between p-2" style="border-top:1px solid #E2E8F0;">
        <div class="small" style="color:#64748B;">Showing <strong style="color:#334155;"><?= $firstIdx; ?></strong>–<strong style="color:#334155;"><?= $lastIdx; ?></strong> of <strong style="color:#334155;"><?= $total; ?></strong></div>
        <nav aria-label="Tender pagination">
            <ul class="pagination pagination-sm mb-0">
                <li class="page-item <?= $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="<?= $baseHref . max(1, $page - 1); ?>" style="color:#7A8BA1;"><i class="fas fa-chevron-left"></i></a>
                </li>
                <?php $prev = 0; foreach ($pages as $p): ?>
                    <?php if ($prev && $p - $prev > 1): ?>
                        <li class="page-item disabled"><span class="page-link" style="color:#94A3B8;">…</span></li>
                    <?php endif; ?>
                    <li class="page-item <?= $p === $page ? 'active' : ''; ?>">
                        <?php if ($p === $page): ?>
                            <span class="page-link" style="background:#7A8BA1;border-color:#7A8BA1;color:#fff;"><?= $p; ?></span>
                        <?php else: ?>
                            <a class="page-link" href="<?= $baseHref . $p; ?>" style="color:#334155;"><?= $p; ?></a>
                        <?php endif; ?>
                    </li>
                    <?php $prev = $p; ?>
                <?php endforeach; ?>
                <li class="page-item <?= $page >= $lastPage ? 'disabled' : ''; ?>">
                    <a class="page-link" href="<?= $baseHref . min($lastPage, $page + 1); ?>" style="color:#7A8BA1;"><i class="fas fa-chevron-right"></i></a>
                </li>
            </ul>
        </nav>
    </div>
    <?php elseif (!empty($rows)): ?>
    <div class="card-footer bg-white p-2" style="border-top:1px solid #E2E8F0;">
        <div class="small" style="color:#64748B;">Showing all <strong style="color:#334155;"><?= $total; ?></strong> tender(s).</div>
    </div>
    <?php endif; ?>
</div>

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