<?php if (!$twilioConfigured): ?>
<div class="alert alert-warning mb-3"><i class="bi bi-exclamation-triangle me-1"></i>Twilio is not connected yet. <a href="<?= base_url('integrations') ?>">Configure it from Integrations</a> to enable calling.</div>
<?php endif; ?>

<div class="d-flex justify-content-end mb-3">
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abCallModal" <?= !$twilioConfigured ? 'disabled' : '' ?>><i class="bi bi-telephone-outbound me-1"></i>Start Outbound Call</button>
</div>

<div class="ab-table-card">
  <div class="table-responsive">
    <table class="table ab-table align-middle">
      <thead><tr><th>Date</th><th>Direction</th><th>Caller</th><th>Duration</th><th>Outcome</th><th></th></tr></thead>
      <tbody>
      <?php foreach ($calls as $c): ?>
        <tr>
          <td class="ab-cell-sub"><?= e(date('M j, g:i A', strtotime($c['started_at']))) ?></td>
          <td><span class="ab-badge <?= $c['direction']==='inbound'?'bg-primary-soft':'bg-secondary-soft' ?>"><i class="bi bi-telephone-<?= $c['direction']==='inbound'?'inbound':'outbound' ?> me-1"></i><?= e(ucfirst($c['direction'] ?? '—')) ?></span></td>
          <td><?= e($c['visitor_identifier'] ?? '—') ?><?= $c['lead_name'] ? ' — ' . e($c['lead_name']) : '' ?></td>
          <td class="ab-mono"><?= $c['duration_seconds'] ? gmdate('i:s', (int) $c['duration_seconds']) : '—' ?></td>
          <td><span class="ab-badge bg-secondary-soft"><?= e($c['outcome'] ? ucfirst(str_replace('_',' ',$c['outcome'])) : 'In progress') ?></span></td>
          <td>
            <?php if ($c['recording_url']): ?><a href="<?= e($c['recording_url']) ?>" target="_blank" class="btn btn-icon btn-light-soft btn-sm"><i class="bi bi-play-circle"></i></a><?php endif; ?>
            <button class="btn btn-icon btn-light-soft btn-sm ab-view-transcript" data-id="<?= (int) $c['id'] ?>"><i class="bi bi-file-text"></i></button>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (empty($calls)): ?><tr><td colspan="6" class="text-center p-4 ab-text-muted">No calls yet.</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="modal fade" id="abCallModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Start Outbound Call</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <form id="abCallForm">
      <div class="mb-2"><label class="form-label ab-req">Phone Number</label><input class="form-control" name="to_number" placeholder="+16195551234" required></div>
      <div class="mb-2"><label class="form-label ab-req">Business Line</label><select class="form-select" name="business_line_id" required><option value="1">Homecare</option><option value="2">Cleaner</option></select></div>
      <div class="mb-0"><label class="form-label">Related Lead ID (optional)</label><input type="number" class="form-control" name="lead_id"></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="abCallSaveBtn">Call Now</button></div>
</div></div></div>

<div class="modal fade" id="abTranscriptModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Call Transcript</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body"><pre class="small" id="abTranscriptBody" style="white-space:pre-wrap;"></pre></div>
</div></div></div>

<script>
document.getElementById('abCallSaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abCallForm');
  abFetch('<?= base_url('voice-agent/call') ?>', { method: 'POST', body: Object.fromEntries(new FormData(form).entries()) })
    .then(function (res) { abToast(res.message); bootstrap.Modal.getInstance(document.getElementById('abCallModal')).hide(); setTimeout(function () { window.location.reload(); }, 800); })
    .catch(function (err) { abToast(err.message, 'danger'); });
});

document.querySelectorAll('.ab-view-transcript').forEach(function (btn) {
  btn.addEventListener('click', function () {
    abFetch('<?= base_url('conversation-logs') ?>/' + btn.dataset.id).then(function (res) {
      var msgs = res.data.messages.map(function (m) { return m.sender.toUpperCase() + ': ' + m.message; }).join('\n\n');
      document.getElementById('abTranscriptBody').textContent = msgs || 'No transcript available.';
      new bootstrap.Modal(document.getElementById('abTranscriptModal')).show();
    });
  });
});
</script>
