<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <div class="d-flex gap-2">
    <div class="ab-search"><i class="bi bi-search"></i><input type="text" id="abCustSearch" placeholder="Search customers..." value="<?= e($_GET['search'] ?? '') ?>"></div>
    <select class="form-select form-select-sm" id="abCustFilterBl" style="width:auto;">
      <option value="">All Businesses</option>
      <?php foreach ($lookups['business_lines'] as $bl): ?><option value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></option><?php endforeach; ?>
    </select>
    <select class="form-select form-select-sm" id="abCustFilterStatus" style="width:auto;">
      <option value="">All Statuses</option>
      <option value="active">Active</option><option value="paused">Paused</option><option value="churned">Churned</option>
    </select>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= base_url('customers/export') ?>" class="btn btn-light-soft btn-sm"><i class="bi bi-download me-1"></i>Export</a>
    <?php if (\App\Core\Rbac::can('leads_customers.create')): ?>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abCustomerModal"><i class="bi bi-plus-lg me-1"></i>Add Customer</button>
    <?php endif; ?>
  </div>
</div>

<div class="ab-table-card">
  <div class="table-responsive">
    <table class="table ab-table align-middle">
      <thead><tr><th>Customer</th><th>Business</th><th>Plan</th><th>Status</th><th>Lifetime Value</th><th>Customer Since</th><th></th></tr></thead>
      <tbody>
      <?php foreach ($rows as $row): ?>
        <tr>
          <td><div class="d-flex align-items-center gap-2"><div class="ab-mini-avatar"><?= e(mb_strtoupper(mb_substr($row['first_name'],0,1))) ?></div>
            <div><a href="<?= base_url('customers/' . $row['id']) ?>" class="ab-cell-primary"><?= e($row['first_name'].' '.($row['last_name'] ?? '')) ?></a><div class="ab-cell-sub"><?= e($row['email'] ?? $row['phone'] ?? '') ?></div></div></div></td>
          <td><?= e($row['business_line_name'] ?? '—') ?></td>
          <td><?= e($row['plan_name'] ?? '—') ?></td>
          <td><span class="ab-badge <?= match($row['status']){'active'=>'bg-success-soft','paused'=>'bg-warning-soft',default=>'bg-danger-soft'} ?>"><?= e(ucfirst($row['status'])) ?></span></td>
          <td class="ab-mono"><?= e(money($row['lifetime_value'])) ?></td>
          <td class="ab-cell-sub"><?= $row['customer_since'] ? e(date('M Y', strtotime($row['customer_since']))) : '—' ?></td>
          <td><a href="<?= base_url('customers/' . $row['id']) ?>" class="btn btn-icon btn-light-soft btn-sm"><i class="bi bi-arrow-right"></i></a></td>
        </tr>
      <?php endforeach; ?>
      <?php if (empty($rows)): ?><tr><td colspan="7" class="text-center p-4 ab-text-muted">No customers found.</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
  <div class="ab-table-pagination">
    <div>Showing <strong><?= (int) $meta['from'] ?>–<?= (int) $meta['to'] ?></strong> of <strong><?= (int) $meta['total'] ?></strong> customers</div>
    <?php if ((int) $meta['total_pages'] > 1): ?>
    <nav aria-label="Customers pagination">
      <ul class="pagination pagination-sm mb-0">
        <?php
          $currentPage = (int) $meta['page'];
          $lastPage = (int) $meta['total_pages'];
          $pageUrl = function (int $page) {
              $params = $_GET;
              $params['page'] = $page;
              return base_url('customers') . '?' . http_build_query($params);
          };
          $pagesToShow = array_unique(array_filter(
              range(max(1, $currentPage - 2), min($lastPage, $currentPage + 2)) + [1, $lastPage],
              fn ($p) => $p >= 1 && $p <= $lastPage
          ));
          sort($pagesToShow);
        ?>
        <li class="page-item <?= !$meta['has_previous'] ? 'disabled' : '' ?>">
          <a class="page-link" href="<?= $meta['has_previous'] ? e($pageUrl($currentPage - 1)) : '#' ?>" aria-label="Previous">&laquo;</a>
        </li>
        <?php $previousPage = 0; foreach ($pagesToShow as $p): ?>
          <?php if ($p - $previousPage > 1): ?>
            <li class="page-item disabled"><span class="page-link">&hellip;</span></li>
          <?php endif; ?>
          <li class="page-item <?= $p === $currentPage ? 'active' : '' ?>">
            <a class="page-link" href="<?= e($pageUrl($p)) ?>"><?= $p ?></a>
          </li>
          <?php $previousPage = $p; ?>
        <?php endforeach; ?>
        <li class="page-item <?= !$meta['has_next'] ? 'disabled' : '' ?>">
          <a class="page-link" href="<?= $meta['has_next'] ? e($pageUrl($currentPage + 1)) : '#' ?>" aria-label="Next">&raquo;</a>
        </li>
      </ul>
    </nav>
    <?php endif; ?>
  </div>
</div>

<div class="modal fade" id="abCustomerModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Add Customer</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <form id="abCustomerForm">
          <div class="row g-3">
            <div class="col-md-6"><label class="form-label ab-req">First Name</label><input class="form-control" name="first_name" required></div>
            <div class="col-md-6"><label class="form-label">Last Name</label><input class="form-control" name="last_name"></div>
            <div class="col-md-6"><label class="form-label">Email</label><input type="email" class="form-control" name="email"></div>
            <div class="col-md-6"><label class="form-label">Phone</label><input class="form-control" name="phone"></div>
            <div class="col-md-6"><label class="form-label ab-req">Business Line</label>
              <select class="form-select" name="business_line_id" required><?php foreach ($lookups['business_lines'] as $bl): ?><option value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></option><?php endforeach; ?></select>
            </div>
            <div class="col-md-6"><label class="form-label">Service Plan</label>
              <select class="form-select" name="service_plan_id"><option value="">—</option><?php foreach ($lookups['service_plans'] as $p): ?><option value="<?= (int) $p['id'] ?>"><?= e($p['name']) ?></option><?php endforeach; ?></select>
            </div>
            <div class="col-md-6"><label class="form-label">Assigned Staff</label>
              <select class="form-select" name="assigned_staff_id"><option value="">—</option><?php foreach ($lookups['staff'] as $s): ?><option value="<?= (int) $s['id'] ?>"><?= e($s['name']) ?></option><?php endforeach; ?></select>
            </div>
            <div class="col-md-6"><label class="form-label">Address</label><input class="form-control" name="address_line1"></div>
            <div class="col-md-4"><label class="form-label">City</label><input class="form-control" name="city"></div>
            <div class="col-md-2"><label class="form-label">Province</label><input class="form-control" name="province"></div>
            <div class="col-md-2"><label class="form-label">Postal</label><input class="form-control" name="postal_code"></div>
          </div>
        </form>
      </div>
      <div class="modal-footer"><button class="btn btn-light-soft" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="abCustomerSaveBtn">Create Customer</button></div>
    </div>
  </div>
</div>

<script>
function abBuildCustParams() {
  return new URLSearchParams({
    search: document.getElementById('abCustSearch').value,
    business_line_id: document.getElementById('abCustFilterBl').value,
    status: document.getElementById('abCustFilterStatus').value
  });
}
document.getElementById('abCustSearch').addEventListener('keydown', function (e) { if (e.key === 'Enter') window.location.href = '<?= base_url('customers') ?>?' + abBuildCustParams().toString(); });
['abCustFilterBl', 'abCustFilterStatus'].forEach(function (id) {
  document.getElementById(id).addEventListener('change', function () { window.location.href = '<?= base_url('customers') ?>?' + abBuildCustParams().toString(); });
});

document.getElementById('abCustomerSaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abCustomerForm');
  var fd = new FormData(form);
  abFetch('<?= base_url('customers') ?>', { method: 'POST', body: Object.fromEntries(fd.entries()) }).then(function (res) {
    abToast(res.message);
    bootstrap.Modal.getInstance(document.getElementById('abCustomerModal')).hide();
    setTimeout(function () { window.location.reload(); }, 600);
  }).catch(function (err) {
    abShowFormErrors(form, err.errors);
    abToast(err.message || 'Save failed.', 'danger');
  });
});
</script>
