<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($lead['first_name'],0,1))) ?></div>
        <h3 class="mb-0"><?= e($lead['first_name'].' '.($lead['last_name'] ?? '')) ?></h3>
        <div class="ab-text-muted small mb-2">Lead #L-<?= (int) $lead['id'] ?></div>
        <span class="ab-badge bg-secondary-soft mb-3"><?= e($lead['stage_name']) ?></span>
        <div class="d-flex gap-2 justify-content-center flex-wrap">
          <?php if ($lead['email']): ?><a href="mailto:<?= e($lead['email']) ?>" class="btn btn-light-soft btn-sm"><i class="bi bi-envelope"></i></a><?php endif; ?>
          <?php if ($lead['phone']): ?><a href="tel:<?= e($lead['phone']) ?>" class="btn btn-light-soft btn-sm"><i class="bi bi-telephone"></i></a><?php endif; ?>
          <?php if (empty($lead['is_won']) && empty($lead['converted_customer_id'])): ?>
          <button class="btn btn-primary btn-sm" id="abConvertBtn"><i class="bi bi-arrow-right-circle me-1"></i>Convert to Customer</button>
          <?php endif; ?>
        </div>
        <?php if ($lead['converted_customer_id']): ?>
        <a href="<?= base_url('customers/' . $lead['converted_customer_id']) ?>" class="ab-badge bg-success-soft mt-3 d-inline-block"><i class="bi bi-check-circle me-1"></i>Converted — View Customer</a>
        <?php endif; ?>
      </div>
      <hr class="m-0 ab-divider">
      <?php if (\App\Core\Rbac::can('leads_customers.update')): ?>
      <div class="ab-card-body">
        <form id="abLeadUpdateForm">
          <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($lead['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($lead['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($lead['email'] ?? '') ?>"></div>
            <div class="col-12"><label class="form-label small">Phone</label><input class="form-control form-control-sm" name="phone" value="<?= e($lead['phone'] ?? '') ?>"></div>
            <div class="col-12">
              <label class="form-label small">Business Line</label>
              <select class="form-select form-select-sm" name="business_line_id" required>
                <?php foreach ($lookups['business_lines'] as $bl): ?><option value="<?= (int) $bl['id'] ?>" <?= $bl['id']==$lead['business_line_id']?'selected':'' ?>><?= e($bl['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label small">Source</label>
              <select class="form-select form-select-sm" name="lead_source_id">
                <option value="">None</option>
                <?php foreach ($lookups['sources'] as $s): ?><option value="<?= (int) $s['id'] ?>" <?= $s['id']==($lead['lead_source_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']==($lead['company_id'] ?? null)?'selected':'' ?>><?= e($c['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-12"><label class="form-label small">Estimated Value</label><input type="number" step="0.01" class="form-control form-control-sm" name="estimated_value" value="<?= e($lead['estimated_value']) ?>"></div>
            <div class="col-12"><hr class="my-1 ab-divider"></div>
            <div class="col-12">
              <label class="form-label small">Stage</label>
              <select class="form-select form-select-sm" name="lead_stage_id" id="abStageSelect" data-original="<?= (int) $lead['lead_stage_id'] ?>">
                <?php foreach ($lookups['stages'] as $s): ?><option value="<?= (int) $s['id'] ?>" <?= $s['id']==$lead['lead_stage_id']?'selected':'' ?>><?= e($s['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label small">Priority</label>
              <select class="form-select form-select-sm" name="priority">
                <?php foreach (['low','medium','high','urgent'] as $p): ?><option value="<?= $p ?>" <?= $p==$lead['priority']?'selected':'' ?>><?= ucfirst($p) ?></option><?php endforeach; ?>
              </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']==$lead['owner_id']?'selected':'' ?>><?= e($o['name']) ?></option><?php endforeach; ?>
              </select>
            </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="abDeleteLeadBtn"><i class="bi bi-trash me-1"></i>Delete Lead</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($lead['business_line_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($lead['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($lead['phone'] ?? '—') ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Source</span><span class="small fw-semibold"><?= e($lead['source_name'] ?? '—') ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Company</span><span class="small fw-semibold"><?= $lead['company_name'] ? e($lead['company_name']) : '—' ?></span></div>
        <div class="d-flex justify-content-between mb-3"><span class="ab-text-muted small">Est. Value</span><span class="small fw-semibold ab-mono"><?= e(money($lead['estimated_value'])) ?></span></div>
        <div class="d-flex justify-content-between"><span class="ab-text-muted small">Created</span><span class="small fw-semibold"><?= e(date('M j, Y', strtotime($lead['created_at']))) ?></span></div>
      </div>
      <?php endif; ?>
    </div>

    <?php if (!empty($duplicates)): ?>
    <div class="ab-card border-warning">
      <div class="ab-card-header"><h2 class="text-warning"><i class="bi bi-exclamation-triangle me-1"></i>Possible Duplicates</h2></div>
      <div class="ab-card-body">
        <?php foreach ($duplicates as $d): ?>
        <div class="d-flex justify-content-between align-items-center mb-2 p-2 border rounded-3 ab-hairline">
          <div><a href="<?= base_url('leads/' . $d['id']) ?>" class="small fw-semibold"><?= e($d['first_name'].' '.($d['last_name'] ?? '')) ?></a><div class="ab-cell-sub"><?= e($d['email'] ?? $d['phone']) ?></div></div>
          <?php if (\App\Core\Rbac::can('leads_customers.manage')): ?>
          <button class="btn btn-sm btn-outline-primary ab-merge-btn" data-dup-id="<?= (int) $d['id'] ?>">Merge Into This</button>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>

  <div class="col-lg-8">
    <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>

    <div class="ab-card mb-3">
      <div class="ab-card-header"><h2>Appointment History</h2></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>

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

<!-- Convert Modal -->
<div class="modal fade" id="abConvertModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Convert to Customer</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <p class="ab-cell-sub">This will create a new customer record using this lead's contact info.</p>
        <label class="form-label">Address</label><input class="form-control mb-2" id="abConvertAddress" placeholder="Street address">
        <div class="row g-2">
          <div class="col-6"><input class="form-control" id="abConvertCity" placeholder="City"></div>
          <div class="col-3"><input class="form-control" id="abConvertProvince" placeholder="Province"></div>
          <div class="col-3"><input class="form-control" id="abConvertPostal" placeholder="Postal"></div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-light-soft" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="abConfirmConvertBtn">Convert</button></div>
    </div>
  </div>
</div>

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

document.getElementById('abLeadUpdateForm')?.addEventListener('submit', function (e) {
  e.preventDefault();
  var form = e.target;
  var fd = new FormData(form);
  var data = Object.fromEntries(fd.entries());

  var stageSelect = document.getElementById('abStageSelect');
  var stageChanged = stageSelect && String(stageSelect.value) !== String(stageSelect.dataset.original);
  delete data.lead_stage_id; // handled separately below, via the dedicated stage-change endpoint

  var saveBtn = form.querySelector('button[type="submit"]');
  saveBtn.disabled = true;

  var requests = [abFetch('<?= base_url('leads/' . $lead['id']) ?>', { method: 'PATCH', body: data })];
  if (stageChanged) {
    requests.push(abFetch('<?= base_url('leads/' . $lead['id'] . '/stage') ?>', { method: 'POST', body: { lead_stage_id: stageSelect.value } }));
  }

  Promise.all(requests)
    .then(function () {
      abToast('Lead updated.');
      setTimeout(function () { window.location.reload(); }, 600);
    })
    .catch(function (err) {
      saveBtn.disabled = false;
      abShowFormErrors(form, err.errors);
      abToast(err.message || 'Update failed.', 'danger');
    });
});

var convertBtn = document.getElementById('abConvertBtn');
if (convertBtn) {
  convertBtn.addEventListener('click', function () { new bootstrap.Modal(document.getElementById('abConvertModal')).show(); });
  document.getElementById('abConfirmConvertBtn').addEventListener('click', function () {
    abFetch('<?= base_url('leads/' . $lead['id'] . '/convert') ?>', {
      method: 'POST',
      body: {
        address_line1: document.getElementById('abConvertAddress').value,
        city: document.getElementById('abConvertCity').value,
        province: document.getElementById('abConvertProvince').value,
        postal_code: document.getElementById('abConvertPostal').value
      }
    }).then(function (res) {
      abToast(res.message);
      setTimeout(function () { window.location.href = '<?= base_url('customers') ?>/' + res.data.customer_id; }, 800);
    }).catch(function (err) { abToast(err.message, 'danger'); });
  });
}

document.querySelectorAll('.ab-merge-btn').forEach(function (btn) {
  btn.addEventListener('click', function () {
    if (!confirm('Merge this duplicate into the current lead? All its notes, tasks, and appointments will be moved here, and the duplicate will be archived.')) return;
    abFetch('<?= base_url('leads/' . $lead['id'] . '/merge') ?>', { method: 'POST', body: { duplicate_lead_id: this.dataset.dupId } })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 800); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
});
</script>