<ul class="nav ab-tabs mb-3">
  <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tabTypes">Service Types</a></li>
  <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tabPlans">Service Plans</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane fade show active" id="tabTypes">
    <div class="d-flex justify-content-end mb-3"><button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abTypeModal">New Service Type</button></div>
    <div class="ab-table-card">
      <div class="table-responsive">
        <table class="table ab-table">
          <thead><tr><th>Name</th><th>Business</th><th>Duration</th><th>Price</th><th></th></tr></thead>
          <tbody>
          <?php foreach ($types as $t): ?>
            <tr><td class="ab-cell-primary"><?= e($t['name']) ?></td><td><?= e($t['business_line_name'] ?? '—') ?></td><td><?= (int) $t['default_duration_minutes'] ?> min</td><td class="ab-mono"><?= e(money($t['default_price'])) ?></td>
              <td class="text-end">
                <button class="btn btn-icon btn-light-soft btn-sm ab-edit-type" data-id="<?= (int) $t['id'] ?>" data-name="<?= e($t['name']) ?>" data-business-line-id="<?= (int) $t['business_line_id'] ?>" data-duration="<?= (int) $t['default_duration_minutes'] ?>" data-price="<?= e($t['default_price']) ?>"><i class="bi bi-pencil"></i></button>
                <button class="btn btn-icon btn-light-soft btn-sm ab-deactivate-type" data-id="<?= (int) $t['id'] ?>"><i class="bi bi-trash text-danger"></i></button>
              </td></tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="tab-pane fade" id="tabPlans">
    <div class="d-flex justify-content-end mb-3"><button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abPlanModal">New Service Plan</button></div>
    <div class="ab-table-card">
      <div class="table-responsive">
        <table class="table ab-table">
          <thead><tr><th>Name</th><th>Business</th><th>Frequency</th><th>Price</th><th></th></tr></thead>
          <tbody>
          <?php foreach ($plans as $p): ?>
            <tr><td class="ab-cell-primary"><?= e($p['name']) ?></td><td><?= e($p['business_line_name'] ?? '—') ?></td><td><?= e(ucfirst(str_replace('_',' ',$p['billing_frequency']))) ?></td><td class="ab-mono"><?= e(money($p['base_price'])) ?></td>
              <td class="text-end">
                <button class="btn btn-icon btn-light-soft btn-sm ab-edit-plan" data-id="<?= (int) $p['id'] ?>" data-name="<?= e($p['name']) ?>" data-business-line-id="<?= (int) $p['business_line_id'] ?>" data-frequency="<?= e($p['billing_frequency']) ?>" data-price="<?= e($p['base_price']) ?>"><i class="bi bi-pencil"></i></button>
                <button class="btn btn-icon btn-light-soft btn-sm ab-deactivate-plan" data-id="<?= (int) $p['id'] ?>"><i class="bi bi-trash text-danger"></i></button>
              </td></tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="abTypeModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">New Service Type</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body"><form id="abTypeForm">
    <div class="mb-2"><label class="form-label ab-req">Name</label><input class="form-control" name="name" required></div>
    <div class="mb-2"><label class="form-label ab-req">Business Line</label><select class="form-select" name="business_line_id" required><?php foreach ($businessLines as $bl): ?><option value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></option><?php endforeach; ?></select></div>
    <div class="mb-2"><label class="form-label ab-req">Default Duration (minutes)</label><input type="number" class="form-control" name="default_duration_minutes" value="60" required></div>
    <div class="mb-0"><label class="form-label ab-req">Default Price</label><input class="form-control" name="default_price" required></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="abTypeSaveBtn">Create</button></div>
</div></div></div>

<div class="modal fade" id="abPlanModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">New Service Plan</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body"><form id="abPlanForm">
    <div class="mb-2"><label class="form-label ab-req">Name</label><input class="form-control" name="name" required></div>
    <div class="mb-2"><label class="form-label ab-req">Business Line</label><select class="form-select" name="business_line_id" required><?php foreach ($businessLines as $bl): ?><option value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></option><?php endforeach; ?></select></div>
    <div class="mb-2"><label class="form-label ab-req">Billing Frequency</label><select class="form-select" name="billing_frequency" required>
      <option value="one_time">One Time</option><option value="weekly">Weekly</option><option value="biweekly">Bi-Weekly</option><option value="monthly">Monthly</option><option value="annually">Annually</option>
    </select></div>
    <div class="mb-0"><label class="form-label ab-req">Base Price</label><input class="form-control" name="base_price" required></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="abPlanSaveBtn">Create</button></div>
</div></div></div>

<script>
var typeModalEl = document.getElementById('abTypeModal');
var planModalEl = document.getElementById('abPlanModal');

// ---- Service Type modal: create + edit ----
document.querySelectorAll('.ab-edit-type').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var form = document.getElementById('abTypeForm');
    form.name.value = btn.dataset.name;
    form.business_line_id.value = btn.dataset.businessLineId;
    form.default_duration_minutes.value = btn.dataset.duration;
    form.default_price.value = btn.dataset.price;
    typeModalEl.dataset.editingId = btn.dataset.id;
    typeModalEl.querySelector('.modal-title').textContent = 'Edit Service Type';
    document.getElementById('abTypeSaveBtn').textContent = 'Save Changes';
    new bootstrap.Modal(typeModalEl).show();
  });
});
typeModalEl.addEventListener('hidden.bs.modal', function () {
  delete typeModalEl.dataset.editingId;
  typeModalEl.querySelector('.modal-title').textContent = 'New Service Type';
  document.getElementById('abTypeSaveBtn').textContent = 'Create';
  document.getElementById('abTypeForm').reset();
});
document.getElementById('abTypeSaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abTypeForm');
  var editingId = typeModalEl.dataset.editingId;
  var url = editingId ? '<?= base_url('services/types') ?>/' + editingId : '<?= base_url('services/types') ?>';
  var method = editingId ? 'PATCH' : 'POST';

  abFetch(url, { method: method, body: Object.fromEntries(new FormData(form).entries()) })
    .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 500); })
    .catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message, 'danger'); });
});

// ---- Service Plan modal: create + edit ----
document.querySelectorAll('.ab-edit-plan').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var form = document.getElementById('abPlanForm');
    form.name.value = btn.dataset.name;
    form.business_line_id.value = btn.dataset.businessLineId;
    form.billing_frequency.value = btn.dataset.frequency;
    form.base_price.value = btn.dataset.price;
    planModalEl.dataset.editingId = btn.dataset.id;
    planModalEl.querySelector('.modal-title').textContent = 'Edit Service Plan';
    document.getElementById('abPlanSaveBtn').textContent = 'Save Changes';
    new bootstrap.Modal(planModalEl).show();
  });
});
planModalEl.addEventListener('hidden.bs.modal', function () {
  delete planModalEl.dataset.editingId;
  planModalEl.querySelector('.modal-title').textContent = 'New Service Plan';
  document.getElementById('abPlanSaveBtn').textContent = 'Create';
  document.getElementById('abPlanForm').reset();
});
document.getElementById('abPlanSaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abPlanForm');
  var editingId = planModalEl.dataset.editingId;
  var url = editingId ? '<?= base_url('services/plans') ?>/' + editingId : '<?= base_url('services/plans') ?>';
  var method = editingId ? 'PATCH' : 'POST';

  abFetch(url, { method: method, body: Object.fromEntries(new FormData(form).entries()) })
    .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 500); })
    .catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message, 'danger'); });
});

document.querySelectorAll('.ab-deactivate-type').forEach(function (btn) {
  btn.addEventListener('click', function () {
    if (!confirm('Deactivate this service type?')) return;
    abFetch('<?= base_url('services/types') ?>/' + this.dataset.id, { method: 'DELETE' }).then(function () { window.location.reload(); });
  });
});
document.querySelectorAll('.ab-deactivate-plan').forEach(function (btn) {
  btn.addEventListener('click', function () {
    if (!confirm('Deactivate this service plan?')) return;
    abFetch('<?= base_url('services/plans') ?>/' + this.dataset.id, { method: 'DELETE' }).then(function () { window.location.reload(); });
  });
});
</script>