<?php
$apiKeyFields = [
    'openai' => [['api_key', 'API Key', 'password'], ['model', 'Model (optional, default gpt-4o-mini)', 'text']],
    'elevenlabs' => [['api_key', 'API Key', 'password'], ['voice_id', 'Default Voice ID (optional)', 'text']],
    'twilio' => [['account_sid', 'Account SID', 'text'], ['auth_token', 'Auth Token', 'password'], ['from_number', 'From Number (+1...)', 'text']],
    'whatsapp' => [['account_sid', 'Twilio Account SID', 'text'], ['auth_token', 'Twilio Auth Token', 'password'], ['whatsapp_number', 'WhatsApp Number (+1...)', 'text']],
    'meta_pixel' => [['pixel_id', 'Pixel ID', 'text']],
    'google_analytics' => [['measurement_id', 'Measurement ID (G-XXXXXXX)', 'text']],
];
?>
<div class="row g-3">
  <?php foreach ($rows as $r): ?>
  <div class="col-md-4">
    <div class="ab-card h-100">
      <div class="ab-card-body">
        <div class="d-flex justify-content-between align-items-start mb-2">
          <h3 class="fs-6 mb-0"><?= e($r['name']) ?></h3>
          <span class="ab-badge <?= match($r['status']){'connected'=>'bg-success-soft','error'=>'bg-danger-soft',default=>'bg-secondary-soft'} ?>"><span class="dot"></span><?= e(ucfirst(str_replace('_',' ',$r['status']))) ?></span>
        </div>
        <?php if (in_array($r['slug'], array_keys($apiKeyFields), true)): ?>
          <button class="btn btn-<?= $r['status']==='connected'?'outline-danger':'primary' ?> btn-sm ab-open-apikey" data-slug="<?= e($r['slug']) ?>" data-name="<?= e($r['name']) ?>" data-connected="<?= $r['status']==='connected'?'1':'0' ?>">
            <?= $r['status']==='connected' ? 'Reconfigure / Disconnect' : 'Configure' ?>
          </button>
        <?php else: ?>
          <?php if ($r['status'] === 'connected'): ?>
            <button class="btn btn-outline-danger btn-sm ab-disconnect" data-slug="<?= e($r['slug']) ?>">Disconnect</button>
          <?php else: ?>
            <button class="btn btn-primary btn-sm ab-open-oauth" data-slug="<?= e($r['slug']) ?>" data-name="<?= e($r['name']) ?>">Set Up &amp; Connect</button>
          <?php endif; ?>
        <?php endif; ?>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- API-key style config modal -->
<div class="modal fade" id="abApiKeyModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title" id="abApiKeyModalTitle">Configure</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body"><form id="abApiKeyForm"></form></div>
  <div class="modal-footer">
    <button class="btn btn-outline-danger d-none" id="abDisconnectBtn">Disconnect</button>
    <button class="btn btn-light-soft" data-bs-dismiss="modal">Cancel</button>
    <button class="btn btn-primary" id="abApiKeySaveBtn">Save &amp; Connect</button>
  </div>
</div></div></div>

<!-- OAuth client config modal (before redirecting to Google/Meta/etc) -->
<div class="modal fade" id="abOauthModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title" id="abOauthModalTitle">Set Up OAuth</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
  <div class="modal-body">
    <p class="ab-cell-sub">Enter the Client ID/Secret from this provider's developer console. Redirect URI to register there: <code id="abRedirectUriDisplay"></code></p>
    <form id="abOauthForm">
      <div class="mb-2"><label class="form-label ab-req">Client ID</label><input class="form-control" name="client_id" required></div>
      <div class="mb-0"><label class="form-label ab-req">Client Secret</label><input type="password" class="form-control" name="client_secret" 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="abOauthSaveBtn">Save &amp; Connect</button></div>
</div></div></div>

<script>
var apiKeyFields = <?= json_encode($apiKeyFields) ?>;

document.querySelectorAll('.ab-open-apikey').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var slug = btn.dataset.slug;
    document.getElementById('abApiKeyModalTitle').textContent = 'Configure ' + btn.dataset.name;
    var form = document.getElementById('abApiKeyForm');
    form.innerHTML = apiKeyFields[slug].map(function (f) {
      return '<div class="mb-2"><label class="form-label">' + f[1] + '</label><input type="' + f[2] + '" class="form-control" name="' + f[0] + '"></div>';
    }).join('');
    form.dataset.slug = slug;

    var disconnectBtn = document.getElementById('abDisconnectBtn');
    disconnectBtn.classList.toggle('d-none', btn.dataset.connected !== '1');
    disconnectBtn.onclick = function () {
      abFetch('<?= base_url('integrations') ?>/' + slug + '/disconnect', { method: 'POST' })
        .then(function (res) { abToast(res.message); bootstrap.Modal.getInstance(document.getElementById('abApiKeyModal')).hide(); setTimeout(function () { window.location.reload(); }, 600); });
    };

    new bootstrap.Modal(document.getElementById('abApiKeyModal')).show();
  });
});

document.getElementById('abApiKeySaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abApiKeyForm');
  var slug = form.dataset.slug;
  var credentials = Object.fromEntries(new FormData(form).entries());

  abFetch('<?= base_url('integrations') ?>/' + slug + '/connect', { method: 'POST', body: { credentials: credentials } })
    .then(function (res) { abToast(res.message); bootstrap.Modal.getInstance(document.getElementById('abApiKeyModal')).hide(); setTimeout(function () { window.location.reload(); }, 600); })
    .catch(function (err) { abToast(err.message || 'Save failed.', 'danger'); });
});

document.querySelectorAll('.ab-disconnect').forEach(function (btn) {
  btn.addEventListener('click', function () {
    if (!confirm('Disconnect this integration?')) return;
    abFetch('<?= base_url('integrations') ?>/' + btn.dataset.slug + '/disconnect', { method: 'POST' })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); });
  });
});

document.querySelectorAll('.ab-open-oauth').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var slug = btn.dataset.slug;
    document.getElementById('abOauthModalTitle').textContent = 'Set Up ' + btn.dataset.name;
    document.getElementById('abRedirectUriDisplay').textContent = '<?= base_url('integrations') ?>/' + slug + '/callback';
    document.getElementById('abOauthForm').dataset.slug = slug;
    new bootstrap.Modal(document.getElementById('abOauthModal')).show();
  });
});

document.getElementById('abOauthSaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abOauthForm');
  var slug = form.dataset.slug;

  abFetch('<?= base_url('integrations') ?>/' + slug + '/oauth-config', { method: 'POST', body: Object.fromEntries(new FormData(form).entries()) })
    .then(function () { window.location.href = '<?= base_url('integrations') ?>/' + slug + '/redirect'; })
    .catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message || 'Save failed.', 'danger'); });
});
</script>
