<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <div class="ab-search"><i class="bi bi-search"></i><input type="text" id="abCoSearch" placeholder="Search companies..." value="<?= e($_GET['search'] ?? '') ?>"></div>
  <div class="d-flex gap-2">
    <a href="<?= base_url('companies/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="#abCompanyModal"><i class="bi bi-plus-lg me-1"></i>Add Company</button>
    <?php endif; ?>
  </div>
</div>

<div class="ab-table-card">
  <div class="table-responsive">
    <table class="table ab-table align-middle">
      <thead><tr><th>Company</th><th>Industry</th><th>Business</th><th>Contract</th><th>Sites</th><th>Annual Value</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" style="border-radius:8px;"><i class="bi bi-building"></i></div>
            <div><a href="<?= base_url('companies/' . $row['id']) ?>" class="ab-cell-primary"><?= e($row['name']) ?></a><div class="ab-cell-sub"><?= e($row['owner_name'] ?? '') ?></div></div></div></td>
          <td><?= e($row['industry'] ?? '—') ?></td>
          <td><?= e($row['business_line_name'] ?? '—') ?></td>
          <td><span class="ab-badge <?= match($row['contract_status']){'active'=>'bg-success-soft','prospect'=>'bg-secondary-soft',default=>'bg-danger-soft'} ?>"><?= e(ucfirst($row['contract_status'])) ?></span></td>
          <td><?= (int) $row['site_count'] ?></td>
          <td class="ab-mono"><?= e(money($row['annual_value'])) ?></td>
          <td><a href="<?= base_url('companies/' . $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 companies 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> companies</div>
    <?php if ((int) $meta['total_pages'] > 1): ?>
    <nav aria-label="Companies 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('companies') . '?' . 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="abCompanyModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Add Company</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <form id="abCompanyForm">
          <div class="row g-3">
            <div class="col-md-8"><label class="form-label ab-req">Company Name</label><input class="form-control" name="name" required></div>
            <div class="col-md-4"><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">Industry</label><input class="form-control" name="industry"></div>
            <div class="col-md-6"><label class="form-label">Website</label><input class="form-control" name="website" placeholder="https://"></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">Owner</label>
              <select class="form-select" name="owner_id"><option value="">—</option><?php foreach ($lookups['owners'] as $o): ?><option value="<?= (int) $o['id'] ?>"><?= e($o['name']) ?></option><?php endforeach; ?></select>
            </div>
            <div class="col-md-4"><label class="form-label">Sites</label><input type="number" class="form-control" name="site_count" value="1"></div>
            <div class="col-md-8"><label class="form-label">Annual Value</label><input class="form-control" name="annual_value" placeholder="0.00"></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="abCompanySaveBtn">Create Company</button></div>
    </div>
  </div>
</div>

<script>
document.getElementById('abCoSearch').addEventListener('keydown', function (e) {
  if (e.key !== 'Enter') return;
  window.location.href = '<?= base_url('companies') ?>?search=' + encodeURIComponent(this.value);
});
document.getElementById('abCompanySaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abCompanyForm');
  var fd = new FormData(form);
  abFetch('<?= base_url('companies') ?>', { method: 'POST', body: Object.fromEntries(fd.entries()) }).then(function (res) {
    abToast(res.message);
    bootstrap.Modal.getInstance(document.getElementById('abCompanyModal')).hide();
    setTimeout(function () { window.location.reload(); }, 600);
  }).catch(function (err) {
    abShowFormErrors(form, err.errors);
    abToast(err.message || 'Save failed.', 'danger');
  });
});
</script>
