<?php
/**
 * helpers/connection_card.php
 * Renders a consistent "connection status" card for each module.
 * Usage: dm_connection_card($client_id, 'meta', [...config...])
 */
if (function_exists('dm_render_connection_card')) return;

function dm_render_connection_card(int $client_id, string $service, array $cfg): void {
    // $cfg keys:
    //   label       string  — "Meta Ads"
    //   icon        string  — "◉"
    //   color       string  — "#1877f2"
    //   required    array   — ['ad_account_id'] keys that must exist
    //   action      string  — 'form' | 'oauth'
    //   oauth_url   string  — URL for OAuth (action=oauth)
    //   fields      array   — [['key'=>'ad_account_id','label'=>'Ad Account ID','placeholder'=>'act_...','hint'=>'']]
    //   card_id     string  — unique HTML id prefix

    $creds    = function_exists('dm_get_credentials') ? dm_get_credentials($client_id, $service) : [];
    $required = $cfg['required'] ?? [];
    $missing  = [];
    foreach ($required as $k) {
        if (empty($creds[$k])) $missing[] = $k;
    }
    $connected = empty($missing);
    $cid       = htmlspecialchars($cfg['card_id'] ?? $service);
    $label     = htmlspecialchars($cfg['label'] ?? $service);
    $icon      = $cfg['icon'] ?? '🔗';
    $color     = $cfg['color'] ?? 'var(--red)';
    $isAdmin   = function_exists('dm_is_admin') ? dm_is_admin() : false;

    if ($connected):
?>
<div id="conn-card-<?= $cid ?>" style="display:flex;align-items:center;gap:10px;background:rgba(34,201,122,.07);border:1px solid rgba(34,201,122,.25);border-radius:8px;padding:10px 14px;margin-bottom:14px">
  <span style="font-size:18px"><?= $icon ?></span>
  <div style="flex:1;font-size:12px;color:var(--m)"><?= $label ?> <span style="color:#22c97a;font-weight:600">conectado</span></div>
  <?php if ($isAdmin): ?>
  <button onclick="document.getElementById('conn-form-<?= $cid ?>').style.display=document.getElementById('conn-form-<?= $cid ?>').style.display==='none'?'block':'none'" style="padding:4px 10px;border-radius:6px;font-size:11px;background:var(--bg3);border:1px solid var(--br2);color:var(--m);cursor:pointer;font-family:var(--fb)">✎ Editar</button>
  <?php endif ?>
</div>
<?php else: ?>
<div id="conn-card-<?= $cid ?>" style="background:rgba(232,39,42,.06);border:1px solid rgba(232,39,42,.2);border-radius:8px;padding:14px 16px;margin-bottom:14px">
  <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px">
    <span style="font-size:20px"><?= $icon ?></span>
    <div>
      <div style="font-size:13px;font-weight:600;color:var(--t)"><?= $label ?> no conectado</div>
      <div style="font-size:11px;color:var(--m)">Configura las credenciales para ver datos en este módulo</div>
    </div>
  </div>
<?php endif; ?>

<?php if (!$connected || $isAdmin): ?>
  <div id="conn-form-<?= $cid ?>" style="<?= $connected ? 'display:none' : '' ?>">
  <?php if (($cfg['action'] ?? 'form') === 'oauth'): ?>
    <a href="<?= htmlspecialchars($cfg['oauth_url'] ?? '#') ?>&client_id=<?= $client_id ?>" target="_blank"
       style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:7px;font-size:13px;font-weight:600;color:#fff;text-decoration:none;background:<?= $color ?>;border:none;cursor:pointer;font-family:var(--fb)">
      🔗 Conectar <?= $label ?>
    </a>
  <?php else: ?>
    <div style="display:grid;grid-template-columns:<?= count($cfg['fields'] ?? []) > 1 ? '1fr 1fr' : '1fr' ?>;gap:8px">
    <?php foreach ($cfg['fields'] ?? [] as $field): ?>
      <div>
        <label style="font-size:11px;color:var(--m);display:block;margin-bottom:3px"><?= htmlspecialchars($field['label']) ?><?= !empty($field['required']) ? ' *' : '' ?></label>
        <input type="<?= ($field['type'] ?? 'text') === 'password' ? 'password' : 'text' ?>"
               id="conn-<?= $cid ?>-<?= htmlspecialchars($field['key']) ?>"
               placeholder="<?= htmlspecialchars($field['placeholder'] ?? '') ?>"
               value="<?= htmlspecialchars($creds[$field['key']] ?? '') ?>"
               style="width:100%;background:var(--bg3);border:1px solid var(--br2);border-radius:7px;padding:7px 10px;font-size:12px;color:var(--t);font-family:var(--fb);outline:none;box-sizing:border-box">
        <?php if (!empty($field['hint'])): ?>
        <div style="font-size:10px;color:var(--m);margin-top:2px"><?= htmlspecialchars($field['hint']) ?></div>
        <?php endif ?>
      </div>
    <?php endforeach ?>
    </div>
    <div style="display:flex;align-items:center;gap:8px;margin-top:8px">
      <button onclick="dmSaveConnCreds('<?= $cid ?>','<?= $service ?>',<?= $client_id ?>,[<?= implode(',', array_map(fn($f) => "'".htmlspecialchars($f['key'])."'", $cfg['fields'] ?? [])) ?>])"
              style="padding:7px 16px;border-radius:7px;font-size:12px;font-weight:600;background:<?= $color ?>;border:none;color:#fff;cursor:pointer;font-family:var(--fb)">
        Guardar conexión
      </button>
      <span id="conn-msg-<?= $cid ?>" style="font-size:12px;color:var(--teal)"></span>
    </div>
  <?php endif ?>
  </div>
<?php endif ?>

<?php if (!$connected): ?>
</div>
<?php endif ?>
<?php
}
