<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <div class="d-flex gap-2">
    <div class="ab-search"><i class="bi bi-search"></i><input type="text" id="abCampSearch" placeholder="Search campaigns..." value="<?= e($_GET['search'] ?? '') ?>"></div>
    <select class="form-select form-select-sm" id="abCampFilterStatus" style="width:auto;">
      <option value="">All statuses</option>
      <option value="draft">Draft</option><option value="scheduled">Scheduled</option>
      <option value="sending">Sending</option><option value="sent">Completed</option><option value="cancelled">Cancelled</option>
    </select>
  </div>
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abCampaignModal" id="abNewCampaignBtn"><i class="bi bi-plus-lg me-1"></i>New Campaign</button>
</div>

<div class="ab-table-card">
  <div class="table-responsive">
    <table class="table ab-table align-middle">
      <thead><tr><th>Campaign</th><th>Status</th><th>Recipients</th><th>Open Rate</th><th>Click Rate</th><th>Scheduled / Sent</th><th></th></tr></thead>
      <tbody>
      <?php foreach ($rows as $row): ?>
        <?php $openRate = $row['recipients_count'] > 0 ? round($row['opens_count']/$row['recipients_count']*100,1) : 0;
              $clickRate = $row['recipients_count'] > 0 ? round($row['clicks_count']/$row['recipients_count']*100,1) : 0; ?>
        <tr>
          <td><a href="<?= base_url('campaigns/' . $row['id']) ?>" class="ab-cell-primary"><?= e($row['name']) ?><?= $row['is_recurring_parent'] ? ' <i class="bi bi-arrow-repeat text-primary" title="Recurring"></i>' : '' ?></a><div class="ab-cell-sub"><?= e($row['business_line_name'] ?? 'Both brands') ?></div></td>
          <td><span class="ab-badge <?= match($row['status']){'sent'=>'bg-success-soft','sending'=>'bg-primary-soft','scheduled'=>'bg-secondary-soft','cancelled'=>'bg-danger-soft',default=>'bg-secondary-soft'} ?>"><?= e($row['status']==='sent'?'Completed':ucfirst($row['status'])) ?></span></td>
          <td><?= (int) $row['recipients_count'] ?></td>
          <td><?= $openRate ?>%</td>
          <td><?= $clickRate ?>%</td>
          <td class="ab-cell-sub"><?= e($row['sent_at'] ? date('M j, Y', strtotime($row['sent_at'])) : ($row['scheduled_at'] ? date('M j, Y g:i A', strtotime($row['scheduled_at'])) : '—')) ?></td>
          <td><a href="<?= base_url('campaigns/' . $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 campaigns yet.</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> campaigns</div>
  </div>
</div>

<!-- Campaign Builder Modal -->
<div class="modal fade" id="abCampaignModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">New Campaign</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <form id="abCampaignForm">
          <div class="row g-3">
            <div class="col-md-8"><label class="form-label ab-req">Campaign Name</label><input class="form-control" name="name" required></div>
            <div class="col-md-4"><label class="form-label">Business Line</label>
              <select class="form-select" name="business_line_id"><option value="">Both brands</option><?php foreach ($lookups['business_lines'] as $bl): ?><option value="<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></option><?php endforeach; ?></select>
            </div>
            <div class="col-12"><label class="form-label">Start From a Template (optional)</label>
              <select class="form-select" id="abTemplatePicker">
                <option value="">Blank</option>
                <?php foreach ($lookups['templates'] as $t): ?><option value="<?= (int) $t['id'] ?>" data-subject="<?= e($t['subject']) ?>" data-body="<?= e($t['body_html']) ?>"><?= e($t['name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-12"><label class="form-label ab-req">Subject Line</label><input class="form-control" name="subject" required></div>
            <div class="col-12"><label class="form-label ab-req">Message (HTML) — use <code>{{first_name}}</code>, <code>{{last_name}}</code> as merge fields</label>
              <textarea class="form-control" name="body_html" rows="6" required></textarea>
            </div>

            <div class="col-12">
              <label class="form-label ab-req">Send To</label>
              <div class="d-flex gap-2 flex-wrap mb-2">
                <span class="ab-chip active" data-audience="all-leads">All Leads</span>
                <span class="ab-chip" data-audience="homecare-leads">Homecare Leads</span>
                <span class="ab-chip" data-audience="cleaner-leads">Cleaner Leads</span>
                <span class="ab-chip" data-audience="customers">Customers</span>
                <span class="ab-chip" data-audience="saved">Saved Segment</span>
                <span class="ab-chip" data-audience="custom">Filtered Audience</span>
              </div>

              <select class="form-select d-none mb-2" id="abSegmentPicker" name="audience_segment_id">
                <option value="">Choose a saved segment...</option>
                <?php foreach ($lookups['segments'] as $s): ?><option value="<?= (int) $s['id'] ?>"><?= e($s['name']) ?></option><?php endforeach; ?>
              </select>

              <div class="d-none row g-2 mb-2" id="abCustomFilterRow">
                <div class="col-4"><select class="form-select form-select-sm" id="abFilterType"><option value="leads">Leads</option><option value="customers">Customers</option></select></div>
                <div class="col-4"><select class="form-select form-select-sm" id="abFilterBl"><option value="both">Both brands</option><option value="homecare">Homecare</option><option value="janitorial">Cleaner</option></select></div>
                <div class="col-4"><select class="form-select form-select-sm" id="abFilterPriority"><option value="">Any priority</option><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option><option value="urgent">Urgent</option></select></div>
              </div>

              <div class="small ab-text-muted" id="abAudiencePreview">Calculating audience…</div>
            </div>

            <div class="col-12">
              <div class="form-check"><input class="form-check-input" type="checkbox" id="abCampRecurring"><label class="form-check-label small" for="abCampRecurring">Make this a recurring campaign (Newsletter)</label></div>
              <div id="abCampRecurOptions" class="d-none row g-2 mt-1">
                <div class="col-5"><select class="form-select form-select-sm" id="abCampRecurFreq"><option value="weekly">Weekly</option><option value="biweekly">Every 2 weeks</option><option value="monthly">Monthly</option></select></div>
                <div class="col-7"><input type="date" class="form-control form-control-sm" id="abCampRecurUntil" placeholder="Repeat until"></div>
              </div>
            </div>

            <div class="col-12 d-none" id="abCampScheduleRow">
              <label class="form-label ab-req">Send At</label>
              <div class="d-flex gap-2">
                <input type="datetime-local" class="form-control" id="abCampScheduleAt">
                <button type="button" class="btn btn-primary text-nowrap" id="abConfirmScheduleBtn">Confirm Schedule</button>
              </div>
            </div>
          </div>
        </form>
        <div class="alert alert-light border small mt-3 mb-0" style="border-radius:10px;">
          <i class="bi bi-info-circle me-1"></i>
          <strong>Save as Draft</strong> saves this without sending anything — you can come back and send or schedule it later from the campaign's page.
          <strong>Schedule</strong> and <strong>Send Now</strong> below queue the actual emails to go out.
        </div>
      </div>
      <div class="modal-footer flex-wrap">
        <button class="btn btn-light-soft" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-outline-primary" id="abSaveDraftBtn">Save as Draft</button>
        <button class="btn btn-outline-primary" id="abScheduleToggleBtn"><i class="bi bi-clock me-1"></i>Schedule</button>
        <button class="btn btn-primary" id="abSendNowBtn"><i class="bi bi-send me-1"></i>Send Now</button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
  // ---- Defensive shim: never let a missing/broken shared helper fail silently ----
  // abToast/abFetch/abShowFormErrors normally come from main.js/app-data.js,
  // which load via <script src> at the very bottom of the page (after this
  // view's own content). Waiting for DOMContentLoaded guarantees those
  // scripts have already run before this check executes — checking any
  // earlier (e.g. immediately, at parse time) would report them as
  // "missing" on every single page load, even when everything is working
  // correctly, since the browser simply hasn't reached those <script> tags
  // yet. This still catches the real failure case (a 404, a stale cached
  // copy, a version mismatch after a partial deploy) — it just checks at
  // the right time instead of too early.
  if (typeof window.abToast !== 'function') {
    window.abToast = function (message) { window.alert(message); };
  }
  if (typeof window.abFetch !== 'function') {
    window.abToast('This page is missing a required script (abFetch) — please hard-refresh this page (Ctrl+Shift+R / Cmd+Shift+R) and try again. If it keeps happening, the deployed app-data.js file may be out of date.');
    return;
  }

  document.getElementById('abCampSearch').addEventListener('keydown', function (e) {
    if (e.key !== 'Enter') return;
    var p = new URLSearchParams({ search: this.value, status: document.getElementById('abCampFilterStatus').value });
    window.location.href = '<?= base_url('campaigns') ?>?' + p.toString();
  });
  document.getElementById('abCampFilterStatus').addEventListener('change', function () {
    var p = new URLSearchParams({ search: document.getElementById('abCampSearch').value, status: this.value });
    window.location.href = '<?= base_url('campaigns') ?>?' + p.toString();
  });

  document.getElementById('abTemplatePicker').addEventListener('change', function () {
    var opt = this.options[this.selectedIndex];
    var form = document.getElementById('abCampaignForm');
    if (opt.dataset.subject) form.subject.value = opt.dataset.subject;
    if (opt.dataset.body) form.body_html.value = opt.dataset.body;
  });

  var currentAudienceMode = 'all-leads';
  document.querySelectorAll('[data-audience]').forEach(function (chip) {
    chip.addEventListener('click', function () {
      document.querySelectorAll('[data-audience]').forEach(function (c) { c.classList.remove('active'); });
      chip.classList.add('active');
      currentAudienceMode = chip.dataset.audience;
      document.getElementById('abSegmentPicker').classList.toggle('d-none', currentAudienceMode !== 'saved');
      document.getElementById('abCustomFilterRow').classList.toggle('d-none', currentAudienceMode !== 'custom');
      updateAudiencePreview();
    });
  });
  ['abFilterType', 'abFilterBl', 'abFilterPriority'].forEach(function (id) {
    document.getElementById(id).addEventListener('change', updateAudiencePreview);
  });
  document.getElementById('abSegmentPicker').addEventListener('change', updateAudiencePreview);

  function currentFilterDefinition() {
    switch (currentAudienceMode) {
      case 'all-leads': return { type: 'leads', business_line: 'both' };
      case 'homecare-leads': return { type: 'leads', business_line: 'homecare' };
      case 'cleaner-leads': return { type: 'leads', business_line: 'janitorial' };
      case 'customers': return { type: 'customers', business_line: 'both' };
      case 'custom':
        var def = { type: document.getElementById('abFilterType').value, business_line: document.getElementById('abFilterBl').value };
        if (document.getElementById('abFilterPriority').value) def.priority = document.getElementById('abFilterPriority').value;
        return def;
      default: return null;
    }
  }

  function updateAudiencePreview() {
    var preview = document.getElementById('abAudiencePreview');
    if (currentAudienceMode === 'saved') {
      var opt = document.getElementById('abSegmentPicker');
      if (!opt.value) { preview.textContent = 'Choose a saved segment above.'; return; }
      preview.textContent = 'Using saved segment: ' + opt.options[opt.selectedIndex].text;
      return;
    }
    preview.textContent = 'Calculating audience…';
    abFetch('<?= base_url('campaigns/preview-audience') ?>?' + new URLSearchParams({ filter: JSON.stringify(currentFilterDefinition()) }))
      .then(function (res) { preview.textContent = res.data.count + ' recipient(s) match this audience.'; })
      .catch(function () { preview.textContent = 'Could not calculate audience.'; });
  }
  updateAudiencePreview();

  document.getElementById('abCampRecurring').addEventListener('change', function () {
    document.getElementById('abCampRecurOptions').classList.toggle('d-none', !this.checked);
  });

  document.getElementById('abScheduleToggleBtn').addEventListener('click', function () {
    document.getElementById('abCampScheduleRow').classList.toggle('d-none');
  });

  // Every submit path shares one payload builder and one bulletproof
  // error handler, so "click a button and nothing visibly happens" can
  // no longer occur silently — any failure (validation, network, or a
  // genuinely unexpected server error) always surfaces a toast.
  function buildCampaignPayload() {
    var form = document.getElementById('abCampaignForm');
    var fd = new FormData(form);
    var data = Object.fromEntries(fd.entries());

    if (!data.name || !data.subject || !data.body_html) {
      return { error: 'Name, Subject, and Message are all required.' };
    }

    if (currentAudienceMode === 'saved') {
      if (!data.audience_segment_id) {
        return { error: 'Choose a saved segment, or switch to a different audience option.' };
      }
    } else {
      data.audience_filter = currentFilterDefinition();
      delete data.audience_segment_id;
    }

    if (document.getElementById('abCampRecurring').checked) {
      data.recurrence_rule = { frequency: document.getElementById('abCampRecurFreq').value, interval: 1, until: document.getElementById('abCampRecurUntil').value };
    }

    return { data: data };
  }

  function handleSubmitFailure(err) {
    var form = document.getElementById('abCampaignForm');
    if (err && err.errors) { abShowFormErrors(form, err.errors); }
    var message = (err && err.message) ? err.message
      : 'Something went wrong reaching the server. Please check your connection and try again.';
    abToast(message, 'danger');
  }

  function setButtonsBusy(busy) {
    ['abSaveDraftBtn', 'abScheduleToggleBtn', 'abSendNowBtn', 'abConfirmScheduleBtn'].forEach(function (id) {
      document.getElementById(id).disabled = busy;
    });
  }

  document.getElementById('abSaveDraftBtn').addEventListener('click', function () {
    try {
      var built = buildCampaignPayload();
      if (built.error) { abToast(built.error, 'danger'); return; }

      setButtonsBusy(true);
      abFetch('<?= base_url('campaigns') ?>', { method: 'POST', body: built.data })
        .then(function (res) {
          abToast(res.message);
          setTimeout(function () { window.location.href = '<?= base_url('campaigns') ?>/' + res.data.id; }, 600);
        })
        .catch(handleSubmitFailure)
        .finally(function () { setButtonsBusy(false); });
    } catch (ex) {
      console.error('Save as Draft failed unexpectedly:', ex);
      abToast('Something unexpected went wrong (' + ex.message + '). Please hard-refresh and try again.', 'danger');
      setButtonsBusy(false);
    }
  });

  document.getElementById('abSendNowBtn').addEventListener('click', function () {
    try {
      var built = buildCampaignPayload();
      if (built.error) { abToast(built.error, 'danger'); return; }
      if (!confirm('Send this campaign now to every matching recipient? This cannot be undone.')) return;

      setButtonsBusy(true);
      abFetch('<?= base_url('campaigns') ?>', { method: 'POST', body: built.data })
        .then(function (res) {
          return abFetch('<?= base_url('campaigns') ?>/' + res.data.id + '/send-now', { method: 'POST' })
            .then(function (sendRes) {
              abToast(sendRes.message);
              setTimeout(function () { window.location.href = '<?= base_url('campaigns') ?>/' + res.data.id; }, 800);
            });
        })
        .catch(handleSubmitFailure)
        .finally(function () { setButtonsBusy(false); });
    } catch (ex) {
      console.error('Send Now failed unexpectedly:', ex);
      abToast('Something unexpected went wrong (' + ex.message + '). Please hard-refresh and try again.', 'danger');
      setButtonsBusy(false);
    }
  });

  document.getElementById('abConfirmScheduleBtn').addEventListener('click', function () {
    try {
      var sendAtInput = document.getElementById('abCampScheduleAt');
      if (!sendAtInput.value) { abToast('Choose a date and time first.', 'danger'); return; }

      var built = buildCampaignPayload();
      if (built.error) { abToast(built.error, 'danger'); return; }

      setButtonsBusy(true);
      var sendAt = sendAtInput.value.replace('T', ' ') + ':00';

      abFetch('<?= base_url('campaigns') ?>', { method: 'POST', body: built.data })
        .then(function (res) {
          return abFetch('<?= base_url('campaigns') ?>/' + res.data.id + '/schedule', { method: 'POST', body: { send_at: sendAt } })
            .then(function (schedRes) {
              abToast(schedRes.message);
              setTimeout(function () { window.location.href = '<?= base_url('campaigns') ?>/' + res.data.id; }, 800);
            });
        })
        .catch(handleSubmitFailure)
        .finally(function () { setButtonsBusy(false); });
    } catch (ex) {
      console.error('Schedule failed unexpectedly:', ex);
      abToast('Something unexpected went wrong (' + ex.message + '). Please hard-refresh and try again.', 'danger');
      setButtonsBusy(false);
    }
  });
});
</script>