<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;"><?= e(mb_strtoupper(mb_substr($customer['first_name'],0,1))) ?></div>
        <h3 class="mb-0"><?= e($customer['first_name'].' '.($customer['last_name'] ?? '')) ?></h3>
        <div class="ab-text-muted small mb-2">Customer #C-<?= (int) $customer['id'] ?></div>
        <span class="ab-badge <?= match($customer['status']){'active'=>'bg-success-soft','paused'=>'bg-warning-soft',default=>'bg-danger-soft'} ?>"><?= e(ucfirst($customer['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="abCustEditForm">
          <div class="row g-2">
            <div class="col-6"><label class="form-label small">First Name</label><input class="form-control form-control-sm" name="first_name" value="<?= e($customer['first_name']) ?>" required></div>
            <div class="col-6"><label class="form-label small">Last Name</label><input class="form-control form-control-sm" name="last_name" value="<?= e($customer['last_name'] ?? '') ?>"></div>
            <div class="col-12"><label class="form-label small">Email</label><input type="email" class="form-control form-control-sm" name="email" value="<?= e($customer['email'] ?? '') ?>"></div>
            <div class="col-12"><label class="form-label small">Phone</label><input class="form-control form-control-sm" name="phone" value="<?= e($customer['phone'] ?? '') ?>"></div>
            <div class="col-12">
              <label class="form-label small">Status</label>
              <select class="form-select form-select-sm" name="status" required>
                <option value="active" <?= $customer['status']=='active'?'selected':'' ?>>Active</option>
                <option value="paused" <?= $customer['status']=='paused'?'selected':'' ?>>Paused</option>
                <option value="churned" <?= $customer['status']=='churned'?'selected':'' ?>>Churned</option>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label small">Service Plan</label>
              <select class="form-select form-select-sm" name="service_plan_id">
                <option value="">None</option>
                <?php foreach ($lookups['service_plans'] as $sp): ?><option value="<?= (int) $sp['id'] ?>" <?= $sp['id']==($customer['service_plan_id'] ?? null)?'selected':'' ?>><?= e($sp['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label small">Assigned Staff</label>
              <select class="form-select form-select-sm" name="assigned_staff_id">
                <option value="">Unassigned</option>
                <?php foreach ($lookups['staff'] as $s): ?><option value="<?= (int) $s['id'] ?>" <?= $s['id']==($customer['assigned_staff_id'] ?? null)?'selected':'' ?>><?= e($s['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label small">Company</label>
              <select class="form-select form-select-sm" name="company_id">
                <option value="">None</option>
                <?php foreach ($lookups['companies'] as $c): ?><option value="<?= (int) $c['id'] ?>" <?= $c['id']==($customer['company_id'] ?? null)?'selected':'' ?>><?= e($c['name']) ?></option><?php endforeach; ?>
              </select>
            </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($customer['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($customer['city'] ?? '') ?>"></div>
            <div class="col-3"><label class="form-label small">Province</label><input class="form-control form-control-sm" name="province" value="<?= e($customer['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($customer['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="abDeleteCustBtn"><i class="bi bi-trash me-1"></i>Delete Customer</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($customer['business_line_name']) ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Plan</span><span class="small fw-semibold"><?= e($customer['plan_name'] ?? '—') ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Email</span><span class="small fw-semibold"><?= e($customer['email'] ?? '—') ?></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($customer['phone'] ?? '—') ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Staff</span><span class="small fw-semibold"><?= e($customer['staff_name'] ?? '—') ?></span></div>
        <div class="d-flex justify-content-between"><span class="ab-text-muted small">Customer Since</span><span class="small fw-semibold"><?= $customer['customer_since'] ? e(date('M Y', strtotime($customer['customer_since']))) : '—' ?></span></div>
      </div>
      <?php endif; ?>
    </div>

    <div class="ab-card mb-3">
      <div class="ab-card-header"><h2>Lifetime Value</h2></div>
      <div class="ab-card-body"><div class="ab-stat-value ab-mono"><?= e(money($customer['lifetime_value'])) ?></div></div>
    </div>
  </div>

  <div class="col-lg-8">
    <div class="ab-card mb-3">
      <div class="ab-card-header"><h2>Activity &amp; Communication 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>

    <div class="ab-card mb-3">
      <div class="ab-card-header"><h2>Service &amp; Appointment History</h2><a href="<?= base_url('appointments') ?>" class="small fw-semibold">Book New</a></div>
      <div class="table-responsive">
        <table class="table ab-table">
          <thead><tr><th>Date</th><th>Service</th><th>Staff</th><th>Status</th></tr></thead>
          <tbody>
          <?php foreach ($appointments as $a): ?>
            <tr><td><?= e(date('M j, Y g:i A', strtotime($a['scheduled_start']))) ?></td><td><?= e($a['service_name'] ?? '—') ?></td><td><?= e($a['staff_name'] ?? '—') ?></td>
            <td><span class="ab-badge <?= match($a['status']) { 'completed'=>'bg-success-soft','cancelled'=>'bg-danger-soft','no_show'=>'bg-warning-soft',default=>'bg-secondary-soft' } ?>"><?= e(ucfirst(str_replace('_',' ',$a['status']))) ?></span></td></tr>
          <?php endforeach; ?>
          <?php if (empty($appointments)): ?><tr><td colspan="4" class="text-center p-3 ab-text-muted">No appointments yet.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <div class="ab-card mb-3">
      <div class="ab-card-header"><h2>Invoices</h2></div>
      <div class="ab-card-body">
        <div class="alert alert-light border small mb-0" style="border-radius:12px;"><i class="bi bi-info-circle text-primary me-1"></i>Invoicing is "Ready" per the Phase 3 brief — the <code>invoices</code>/<code>invoice_items</code>/<code>payments</code> schema already exists from Phase 1 and <code>CustomerModel::recalculateLifetimeValue()</code> already reads from it. The Invoicing UI itself is scoped to Phase 4 (Marketing/Billing).</div>
      </div>
    </div>

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

<script>
document.getElementById('abDeleteCustBtn')?.addEventListener('click', function () {
  if (!confirm('Move this customer to trash? This can be undone from Customers > Trashed.')) return;
  abFetch('<?= base_url('customers/' . $customer['id']) ?>', { method: 'DELETE' })
    .then(function (res) {
      abToast(res.message);
      setTimeout(function () { window.location.href = '<?= base_url('customers') ?>'; }, 600);
    })
    .catch(function (err) { abToast(err.message, 'danger'); });
});

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