<?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);
    $customers = $this->data['customers']   ?? [];

    // Query string preserving all filters (page appended by pagination links).
    $q  = 'q='          . urlencode((string)($f['q']            ?? ''))
        . '&type='      . urlencode((string)($f['project_type'] ?? ''))
        . '&customer_id=' . urlencode((string)($f['customer_id']?? ''))
        . '&origin='    . urlencode((string)($f['origin']       ?? ''))
        . '&crm_status='. urlencode((string)($f['crm_status']   ?? ''))
        . '&stage='     . urlencode((string)($f['stage']        ?? ''));

    $crmClass = [
        'APPROVED'    => 'bg-success',
        'SUBMITTED'   => 'bg-info text-white',
        'IN_PROGRESS' => 'bg-warning text-dark',
        'MIGRATED'    => 'bg-secondary',
        'NOT_STARTED' => 'bg-light text-muted',
        'DECLINED'    => 'bg-danger',
        'PENDING'     => 'bg-warning text-dark',
    ];
    $typeIco = ['goods'=>'fa-boxes','services'=>'fa-tools','works'=>'fa-hard-hat'];
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-project-diagram me-2 text-muted"></i>Projects</h5>
    <a href="<?= PROOT; ?>Projects/add" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;">
        <i class="fas fa-plus me-1"></i> New Project
    </a>
</div>

<!-- Filters -->
<form method="get" action="<?= PROOT; ?>Projects" 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;font-size:.72rem;">Search</label>
                <input type="text" name="q" value="<?= htmlspecialchars((string)($f['q'] ?? '')); ?>" placeholder="no, name, customer, tender ref…" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="color:#334155;font-size:.72rem;">Type</label>
                <select name="type" class="form-select form-select-sm">
                    <option value="">All</option>
                    <?php foreach (['goods','services','works'] 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;font-size:.72rem;">Customer</label>
                <select name="customer_id" class="form-select form-select-sm">
                    <option value="">All</option>
                    <?php foreach ($customers as $c): ?>
                        <option value="<?= (int)$c['c0d']; ?>" <?= (int)($f['customer_id'] ?? 0) === (int)$c['c0d'] ? 'selected' : ''; ?>><?= htmlspecialchars((string)$c['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label" style="color:#334155;font-size:.72rem;">Origin</label>
                <select name="origin" class="form-select form-select-sm">
                    <option value="">All</option>
                    <?php foreach (['TENDER_BDM','TENDER_PUBLIC','DIRECT_AWARD','MIGRATED'] as $o): ?>
                        <option value="<?= $o; ?>" <?= ($f['origin'] ?? '') === $o ? 'selected' : ''; ?>><?= htmlspecialchars(ucwords(strtolower(str_replace('_',' ', $o)))); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label" style="color:#334155;font-size:.72rem;">CRM status</label>
                <select name="crm_status" class="form-select form-select-sm">
                    <option value="">All</option>
                    <?php foreach (['NOT_STARTED','IN_PROGRESS','PENDING','SUBMITTED','APPROVED','DECLINED','MIGRATED'] as $st): ?>
                        <option value="<?= $st; ?>" <?= ($f['crm_status'] ?? '') === $st ? 'selected' : ''; ?>><?= htmlspecialchars(ucwords(strtolower(str_replace('_',' ', $st)))); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-1">
                <label class="form-label" style="color:#334155;font-size:.72rem;">&nbsp;</label>
                <div class="d-flex gap-1">
                    <button type="submit" class="btn btn-sm flex-fill" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;color:#fff;" title="Apply filters"><i class="fas fa-filter"></i></button>
                    <a href="<?= PROOT; ?>Projects" class="btn btn-sm btn-outline-secondary flex-fill" title="Reset filters"><i class="fas fa-times"></i></a>
                </div>
            </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 class="table-light">
                <tr>
                    <th>Project #</th><th>Name</th><th>Type</th><th>Customer</th>
                    <th>Origin</th><th>CRM Status</th><th>Stage</th><th class="text-end">Value</th><th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $r):
                    $badgeClass = $crmClass[$r['crm_status']] ?? 'bg-light text-muted';
                    $ico = $typeIco[$r['project_type']] ?? 'fa-project-diagram';
                ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>Projects/view/<?= (int)$r['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($r['project_no']); ?></strong></a></td>
                        <td><?= htmlspecialchars($r['project_name']); ?>
                            <?php if (!empty($r['project_tender_reference'])): ?><div class="small text-muted"><?= htmlspecialchars($r['project_tender_reference']); ?></div><?php endif; ?>
                        </td>
                        <td><i class="fas <?= $ico; ?> me-1 text-muted"></i><span style="text-transform:capitalize;"><?= htmlspecialchars($r['project_type']); ?></span></td>
                        <td class="text-muted"><?= htmlspecialchars($r['project_customer']); ?></td>
                        <td><span class="badge bg-light text-muted" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$r['origin']))); ?></span></td>
                        <td>
                            <span class="badge <?= $badgeClass; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$r['crm_status']))); ?></span>
                            <?php if ((int)$r['migrated_flag'] === 1): ?><span class="badge bg-warning text-dark ms-1" title="Legacy project — bypassed onboarding chain">&#9888; Migrated</span><?php endif; ?>
                        </td>
                        <td class="text-muted" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower($r['project_lifecycle_stage'])); ?></td>
                        <td class="text-end"><?= htmlspecialchars($r['currency']); ?> <?= number_format((float)$r['contract_value']); ?></td>
                        <td class="text-end"><a href="<?= PROOT; ?>Projects/view/<?= (int)$r['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-eye"></i></a></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="9" class="text-center text-muted py-4">
                        No projects match these filters.
                        <?php if (($f['q'] ?? '') !== '' || !empty($f['project_type']) || !empty($f['customer_id']) || !empty($f['origin']) || !empty($f['crm_status'])): ?>
                            <a href="<?= PROOT; ?>Projects">Reset filters</a>
                        <?php else: ?>
                            <a href="<?= PROOT; ?>Projects/add">Create the first one</a>.
                        <?php endif; ?>
                    </td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($lastPage > 1):
        $firstIdx = $total === 0 ? 0 : ($page - 1) * $pageSize + 1;
        $lastIdx  = min($page * $pageSize, $total);
        $baseHref = PROOT . 'Projects?' . $q . '&page=';
        $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>&ndash;<strong style="color:#334155;"><?= $lastIdx; ?></strong> of <strong style="color:#334155;"><?= $total; ?></strong></div>
        <nav aria-label="Project 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;">&hellip;</span></li>
                    <?php endif; ?>
                    <li class="page-item <?= $p === $page ? 'active' : ''; ?>">
                        <?php if ($p === $page): ?>
                            <span class="page-link" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;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> project(s).</div>
    </div>
    <?php endif; ?>
</div>

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