<?php
$filterOptions = [
    'all'         => 'All Customers',
    'active'      => 'Active',
    'inactive'    => 'Inactive',
    'blacklisted' => 'Blacklisted',
    'vip'         => 'VIP (Gold+)',
];
$sortOptions = [
    'spent'  => 'Top Spenders',
    'orders' => 'Most Orders',
    'joined' => 'Recently Joined',
    'name'   => 'Name A–Z',
];

function tierBadgeHtml(int $n): string {
    $t = customer_tier($n);
    return '<span class="tier-badge ' . $t['class'] . '">' . $t['icon'] . ' ' . $t['label'] . '</span>';
}
?>

<style>
.tier-badge{display:inline-flex;align-items:center;gap:4px;font-size:.7rem;font-weight:700;
    padding:2px 8px;border-radius:20px;white-space:nowrap;}
.badge-platinum{background:#e0f7fa;color:#006064;}
.badge-gold    {background:#fff8e1;color:#f57f17;}
.badge-silver  {background:#f5f5f5;color:#424242;}
.badge-bronze  {background:#fbe9e7;color:#bf360c;}
.badge-new     {background:#f3f4f6;color:#6b7280;}
.avatar-circle{width:36px;height:36px;border-radius:50%;display:flex;align-items:center;
    justify-content:center;font-weight:700;font-size:.95rem;flex-shrink:0;}
</style>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
    <h4 class="mb-0 fw-bold"><i class="bi bi-people-fill me-2 text-primary"></i>Customers
        <span class="badge bg-secondary ms-2" style="font-size:.8rem;"><?= number_format($total) ?></span>
    </h4>
    <a href="<?= url('customers/export') ?>" class="btn btn-sm btn-outline-success">
        <i class="bi bi-download me-1"></i> Export CSV
    </a>
</div>

<?= flash_alert() ?>

<!-- Filter tabs -->
<ul class="nav nav-tabs mb-3">
    <?php foreach ($filterOptions as $key => $label): ?>
    <li class="nav-item">
        <a class="nav-link <?= $filter === $key ? 'active fw-semibold' : '' ?>"
           href="<?= url('customers') ?>?filter=<?= $key ?>&sort=<?= $sort ?>&search=<?= urlencode($search) ?>">
            <?= $label ?>
        </a>
    </li>
    <?php endforeach ?>
</ul>

<!-- Search + Sort -->
<form method="GET" action="<?= url('customers') ?>" class="row g-2 mb-3">
    <input type="hidden" name="filter" value="<?= e($filter) ?>">
    <div class="col-md-6">
        <div class="input-group">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control" placeholder="Search name, email, phone…"
                   value="<?= e($search) ?>">
            <?php if ($search): ?>
            <a href="<?= url('customers') ?>?filter=<?= $filter ?>" class="btn btn-outline-secondary">×</a>
            <?php endif ?>
        </div>
    </div>
    <div class="col-md-3">
        <select name="sort" class="form-select" onchange="this.form.submit()">
            <?php foreach ($sortOptions as $k => $v): ?>
            <option value="<?= $k ?>" <?= $sort === $k ? 'selected' : '' ?>><?= $v ?></option>
            <?php endforeach ?>
        </select>
    </div>
    <div class="col-auto">
        <button class="btn btn-primary"><i class="bi bi-search me-1"></i> Search</button>
    </div>
</form>

<!-- Table -->
<div class="card border-0 shadow-sm">
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead class="table-light">
    <tr>
        <th>Customer</th>
        <th>Contact</th>
        <th class="text-center">Tier</th>
        <th class="text-center">Orders</th>
        <th class="text-end">Spent</th>
        <th class="text-center">Status</th>
        <th class="text-center">Joined</th>
        <th class="text-center">Actions</th>
    </tr>
</thead>
<tbody>
<?php if (empty($rows)): ?>
<tr><td colspan="8" class="text-center py-5 text-muted">No customers found.</td></tr>
<?php endif ?>
<?php foreach ($rows as $r):
    $tier    = customer_tier((int)$r['delivered_orders']);
    $initials = strtoupper(mb_substr($r['name'], 0, 1));
    $colors  = ['bg-primary','bg-success','bg-warning','bg-info','bg-danger','bg-secondary'];
    $color   = $colors[abs(crc32($r['email'])) % count($colors)];
?>
<tr class="<?= $r['blacklisted'] ? 'table-danger' : '' ?>">
    <td>
        <div class="d-flex align-items-center gap-2">
            <div class="avatar-circle text-white <?= $color ?>"><?= $initials ?></div>
            <div>
                <a href="<?= url('customers/'.$r['id']) ?>" class="fw-semibold text-decoration-none text-dark">
                    <?= e($r['name']) ?>
                </a>
                <?php if ($r['blacklisted']): ?>
                <span class="badge bg-danger ms-1" style="font-size:.6rem;">BLACKLISTED</span>
                <?php endif ?>
            </div>
        </div>
    </td>
    <td>
        <div class="small"><?= e($r['email']) ?></div>
        <div class="small text-muted"><?= e($r['phone']) ?></div>
    </td>
    <td class="text-center"><?= tierBadgeHtml((int)$r['delivered_orders']) ?></td>
    <td class="text-center fw-semibold"><?= $r['total_orders'] ?></td>
    <td class="text-end fw-bold"><?= money((float)$r['total_spent']) ?></td>
    <td class="text-center">
        <?php if ($r['blacklisted']): ?>
            <span class="badge bg-danger">Blacklisted</span>
        <?php elseif ($r['is_active']): ?>
            <span class="badge bg-success">Active</span>
        <?php else: ?>
            <span class="badge bg-secondary">Inactive</span>
        <?php endif ?>
    </td>
    <td class="text-center small text-muted"><?= date('d M Y', strtotime($r['created_at'])) ?></td>
    <td class="text-center">
        <div class="d-flex justify-content-center gap-1">
            <a href="<?= url('customers/'.$r['id']) ?>" class="btn btn-sm btn-outline-primary" title="View">
                <i class="bi bi-eye"></i>
            </a>
            <a href="<?= url('customers/'.$r['id'].'/edit') ?>" class="btn btn-sm btn-outline-secondary" title="Edit">
                <i class="bi bi-pencil"></i>
            </a>
            <form method="POST" action="<?= url('customers/'.$r['id'].'/toggle') ?>">
                <?= csrf_field() ?>
                <button class="btn btn-sm <?= $r['is_active'] ? 'btn-outline-warning' : 'btn-outline-success' ?>"
                        title="<?= $r['is_active'] ? 'Deactivate' : 'Activate' ?>">
                    <i class="bi bi-<?= $r['is_active'] ? 'pause-circle' : 'play-circle' ?>"></i>
                </button>
            </form>
        </div>
    </td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</div>
</div>

<?php if ($pagination ?? ''): ?>
<div class="mt-3"><?= $pagination ?></div>
<?php endif ?>
