<div class="row g-3">
  <div class="col-lg-4">
    <div class="ab-card mb-3">
      <div class="ab-card-body text-center">
        <div class="ab-mini-avatar mx-auto mb-3" style="width:64px; height:64px; font-size:1.3rem; border-radius:16px;"><i class="bi bi-building"></i></div>
        <h3 class="mb-0"><?= e($company['name']) ?></h3>
        <div class="ab-text-muted small mb-2"><?= e($company['industry'] ?? 'No industry set') ?></div>
        <span class="ab-badge <?= match($company['contract_status']){'active'=>'bg-success-soft','prospect'=>'bg-secondary-soft',default=>'bg-danger-soft'} ?>"><?= e(ucfirst($company['contract_status'])) ?></span>
      </div>
      <hr class="m-0 ab-divider">
      <?php if (\App\Core\Rbac::can('leads_customers.update')): ?>
      <div class="ab-card-body">
        <form id="abCoEditForm">
          <div class="row g-2">
            <div class="col-12"><label class="form-label small">Name</label><input class="form-control form-control-sm" name="name" value="<?= e($company['name']) ?>" required></div>
            <div class="col-12"><label class="form-label small">Industry</label><input class="form-control form-control-sm" name="industry" value="<?= e($company['industry'] ?? '') ?>"></div>
            <div class="col-12"><label class="form-label small">Website</label><input type="url" class="form-control form-control-sm" name="website" value="<?= e($company['website'] ?? '') ?>" placeholder="https://"></div>
            <div class="col-12"><label class="form-label small">Phone</label><input class="form-control form-control-sm" name="phone" value="<?= e($company['phone'] ?? '') ?>"></div>
            <div class="col-12">
              <label class="form-label small">Contract Status</label>
              <select class="form-select form-select-sm" name="contract_status" required>
                <option value="prospect" <?= $company['contract_status']=='prospect'?'selected':'' ?>>Prospect</option>
                <option value="active" <?= $company['contract_status']=='active'?'selected':'' ?>>Active</option>
                <option value="lapsed" <?= $company['contract_status']=='lapsed'?'selected':'' ?>>Lapsed</option>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label small">Owner</label>
              <select class="form-select form-select-sm" name="owner_id">
                <option value="">Unassigned</option>
                <?php foreach ($lookups['owners'] as $o): ?><option value="<?= (int) $o['id'] ?>" <?= $o['id']==($company['owner_id'] ?? null)?'selected':'' ?>><?= e($o['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-6"><label class="form-label small">Sites</label><input type="number" class="form-control form-control-sm" name="site_count" value="<?= e($company['site_count'] ?? 0) ?>"></div>
            <div class="col-6"><label class="form-label small">Annual Value</label><input type="number" step="0.01" class="form-control form-control-sm" name="annual_value" value="<?= e($company['annual_value']) ?>"></div>
            <div class="col-12"><hr class="my-1 ab-divider"></div>
            <div class="col-12"><label class="form-label small">Address</label><input class="form-control form-control-sm" name="address_line1" value="<?= e($company['address_line1'] ?? '') ?>" placeholder="Street address"></div>
            <div class="col-6"><label class="form-label small">City</label><input class="form-control form-control-sm" name="city" value="<?= e($company['city'] ?? '') ?>"></div>
            <div class="col-3"><label class="form-label small">Province</label><input class="form-control form-control-sm" name="province" value="<?= e($company['province'] ?? '') ?>"></div>
            <div class="col-3"><label class="form-label small">Postal</label><input class="form-control form-control-sm" name="postal_code" value="<?= e($company['postal_code'] ?? '') ?>"></div>
          </div>
          <button type="submit" class="btn btn-primary w-100 mt-3">Save Changes</button>
        </form>
        <?php if (\App\Core\Rbac::can('leads_customers.delete')): ?>
        <button type="button" class="btn btn-outline-danger w-100 mt-2" id="abDeleteCoBtn"><i class="bi bi-trash me-1"></i>Delete Company</button>
        <?php endif; ?>
      </div>
      <?php else: ?>
      <div class="ab-card-body">
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Business Line</span><span class="ab-badge bg-primary-soft"><?= e($company['business_line_name'] ?? '—') ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Website</span><span class="small fw-semibold"><?= $company['website'] ? '<a href="'.e($company['website']).'" target="_blank">'.e($company['website']).'</a>' : '—' ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Phone</span><span class="small fw-semibold ab-mono"><?= e($company['phone'] ?? '—') ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Owner</span><span class="small fw-semibold"><?= e($company['owner_name'] ?? '—') ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Sites</span><span class="small fw-semibold"><?= (int) $company['site_count'] ?></span></div>
        <div class="d-flex justify-content-between"><span class="ab-text-muted small">Annual Value</span><span class="small fw-semibold ab-mono"><?= e(money($company['annual_value'])) ?></span></div>
      </div>
      <?php endif; ?>
    </div>
  </div>

  <div class="col-lg-8">
    <div class="row g-3 mb-3">
      <div class="col-md-6">
        <div class="ab-card">
          <div class="ab-card-header"><h2>Related Leads</h2></div>
          <div class="ab-card-body p-0">
            <?php foreach ($relatedLeads as $l): ?>
            <a href="<?= base_url('leads/' . $l['id']) ?>" class="d-block p-3 border-bottom ab-hairline text-decoration-none text-dark small"><?= e($l['first_name'].' '.($l['last_name'] ?? '')) ?><div class="ab-cell-sub"><?= e($l['email'] ?? '') ?></div></a>
            <?php endforeach; ?>
            <?php if (empty($relatedLeads)): ?><div class="ab-empty small py-3">No leads yet.</div><?php endif; ?>
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <div class="ab-card">
          <div class="ab-card-header"><h2>Related Customers</h2></div>
          <div class="ab-card-body p-0">
            <?php foreach ($relatedCustomers as $c): ?>
            <a href="<?= base_url('customers/' . $c['id']) ?>" class="d-block p-3 border-bottom ab-hairline text-decoration-none text-dark small"><?= e($c['first_name'].' '.($c['last_name'] ?? '')) ?><div class="ab-cell-sub"><?= e($c['email'] ?? '') ?></div></a>
            <?php endforeach; ?>
            <?php if (empty($relatedCustomers)): ?><div class="ab-empty small py-3">No customers yet.</div><?php endif; ?>
          </div>
        </div>
      </div>
    </div>

    <div class="ab-card mb-3">
      <div class="ab-card-header"><h2>Activity Timeline</h2></div>
      <div class="ab-card-body">
        <ul class="ab-timeline">
          <?php foreach ($timeline as $t): ?>
          <li><span class="ab-tl-dot"><i class="bi bi-clock-history"></i></span><div class="ab-tl-time"><?= e(date('M j, Y — g:i A', strtotime($t['created_at']))) ?></div><strong><?= e($t['caused_by_name'] ?? 'System') ?></strong> — <?= e($t['description']) ?></li>
          <?php endforeach; ?>
          <?php if (empty($timeline)): ?><div class="ab-empty small">No activity recorded yet.</div><?php endif; ?>
        </ul>
      </div>
    </div>

    <?php require __DIR__ . '/../partials/entity-panels.php'; ?>
  </div>
</div>

<script>
document.getElementById('abDeleteCoBtn')?.addEventListener('click', function () {
  if (!confirm('Move this company to trash? An admin can restore it later if needed.')) return;
  abFetch('<?= base_url('companies/' . $company['id']) ?>', { method: 'DELETE' })
    .then(function (res) {
      abToast(res.message);
      setTimeout(function () { window.location.href = '<?= base_url('companies') ?>'; }, 600);
    })
    .catch(function (err) { abToast(err.message, 'danger'); });
});

document.getElementById('abCoEditForm')?.addEventListener('submit', function (e) {
  e.preventDefault();
  var fd = new FormData(e.target);
  abFetch('<?= base_url('companies/' . $company['id']) ?>', { method: 'PATCH', body: Object.fromEntries(fd.entries()) })
    .then(function (res) { abToast(res.message); })
    .catch(function (err) { abToast(err.message, 'danger'); });
});
</script>