<?php
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/credentials.php';
dm_require_login(); if (!dm_is_admin()) { header("Location: index.php"); exit; }
$user    = dm_user();
$_is_adm = dm_is_admin();
$_sub_c  = function_exists('dm_get_subscription') ? (dm_get_subscription((int)$user['id']) ?? []) : [];
$_max_c  = $_sub_c['max_clients'] ?? ($_is_adm ? 999 : 0);
$msg = ''; $msgType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'create') {
        $name     = trim($_POST['name'] ?? '');
        $industry = trim($_POST['industry'] ?? '');
        $url      = trim($_POST['url'] ?? '');
        $color    = trim($_POST['color'] ?? '#4a9ef8');
        $services = implode(',', array_intersect($_POST['services'] ?? [], ['meta','google','seo','wp','shopify']));
        $notes    = trim($_POST['notes'] ?? '');
        $cur_count = (int)$pdo->prepare("SELECT COUNT(*) FROM dm_clients c" . (!$_is_adm ? " JOIN dm_user_clients uc ON uc.client_id=c.id WHERE uc.user_id=?" : " WHERE 1"))->execute($_is_adm ? [] : [(int)$user['id']]);
        if (!$name) { $msg='El nombre es obligatorio.'; $msgType='err'; }
        elseif (!$_is_adm && $_max_c > 0 && count($clients) >= $_max_c) {
            $msg="Límite del plan alcanzado ({$_max_c} clientes). Actualiza tu plan para agregar más."; $msgType='err';
        }
        else {
            $pdo->prepare('INSERT INTO dm_clients (name,industry,url,color,services,notes) VALUES (?,?,?,?,?,?)')->execute([$name,$industry,$url,$color,$services,$notes]);
            $new_cid = (int)$pdo->lastInsertId();
            if (!$_is_adm) {
                $pdo->prepare('INSERT IGNORE INTO dm_user_clients (user_id,client_id) VALUES (?,?)')->execute([(int)$user['id'], $new_cid]);
            }
            dm_log($user['id'], $new_cid, 'create_client', "Cliente creado: {$name}");
            $msg="Cliente {$name} creado."; $msgType='ok';
        }
    }
    if ($action === 'delete') {
        $cid = (int)($_POST['cid'] ?? 0);
        if ($cid) { $pdo->prepare('DELETE FROM dm_clients WHERE id=?')->execute([$cid]); $msg='Cliente eliminado.'; $msgType='ok'; }
    }
}

$clients = dm_get_clients();

$all_creds = [];
if ($pdo && $clients) {
    $ids = implode(',', array_column($clients, 'id'));
    if ($ids) {
        $rows = $pdo->query("SELECT client_id, service, key_name FROM dm_client_credentials WHERE client_id IN ({$ids})")->fetchAll();
        foreach ($rows as $r) {
            $all_creds[$r['client_id']][$r['service']][$r['key_name']] = true;
        }
    }
}

function has_cred(array $all_creds, int $cid, string $service): bool {
    return !empty($all_creds[$cid][$service]);
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="dm-csrf" content="<?= dm_csrf_token() ?>">
<title>DIMARK Brain · Clientes</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700&family=DM+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{--red:#E8272A;--red-l:rgba(232,39,42,.1);--red-b:rgba(232,39,42,.2);--bg:#0f0f0f;--bg2:#181818;--bg3:#222;--bg4:#2a2a2a;--border:rgba(255,255,255,.07);--border2:rgba(255,255,255,.13);--text:#f0f0f0;--muted:rgba(240,240,240,.42);--green:#22c97a;--yellow:#f5c543;--blue:#4a9ef8;--purple:#9b7ff4;--fh:'Syne',sans-serif;--fb:'DM Sans',sans-serif}
html,body{min-height:100%;background:var(--bg);color:var(--text);font-family:var(--fb);font-size:14px}
nav{display:flex;align-items:center;justify-content:space-between;padding:0 22px;height:54px;background:var(--bg);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:100}
.logo{display:flex;align-items:center;gap:10px;text-decoration:none;color:inherit}
.lm{width:30px;height:30px;background:var(--red);border-radius:7px;display:flex;align-items:center;justify-content:center;font-family:var(--fh);font-weight:700;font-size:14px;color:#fff}
.ln{font-family:var(--fh);font-weight:700;font-size:15px}
.ls{font-size:10px;letter-spacing:1.6px;text-transform:uppercase;color:var(--red)}
.nav-r{display:flex;align-items:center;gap:10px}
.nl{padding:5px 12px;border-radius:6px;font-size:13px;color:var(--muted);text-decoration:none;border:1px solid transparent;transition:all .15s}
.nl:hover{color:var(--text);background:var(--bg3)}
.nl.active{color:var(--text);background:var(--bg3);border-color:var(--border2)}
.av{width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:500}
main{max-width:980px;margin:0 auto;padding:28px 22px}
.ph{display:flex;align-items:center;justify-content:space-between;margin-bottom:24px}
.pt{font-family:var(--fh);font-size:20px;font-weight:700}
.ps{font-size:12px;color:var(--muted);margin-top:2px}
.btn{padding:8px 16px;border-radius:7px;font-size:13px;cursor:pointer;font-family:var(--fb);transition:all .15s;border:1px solid}
.btn-primary{background:var(--red);border-color:var(--red);color:#fff}.btn-primary:hover{opacity:.85}
.btn-ghost{background:none;border-color:var(--border2);color:var(--text)}.btn-ghost:hover{background:var(--bg3)}
.btn-sm{padding:5px 10px;font-size:12px}
.btn-blue{background:rgba(74,158,248,.15);border-color:rgba(74,158,248,.3);color:var(--blue)}.btn-blue:hover{background:rgba(74,158,248,.25)}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px}
.client-card{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:18px;transition:all .15s}
.client-card:hover{border-color:var(--red-b)}
.cc-top{display:flex;align-items:center;gap:11px;margin-bottom:12px}
.cc-av{width:38px;height:38px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-family:var(--fh);font-weight:700;font-size:15px;flex-shrink:0}
.cc-name{font-family:var(--fh);font-size:14px;font-weight:700}
.cc-ind{font-size:11px;color:var(--muted);margin-top:1px}
.cc-url{font-size:11px;color:var(--blue);margin-bottom:10px}
.cc-tags{display:flex;gap:4px;flex-wrap:wrap;margin-bottom:12px}
.ctag{font-size:10px;padding:2px 6px;border-radius:3px;font-weight:500}
.t-meta{background:rgba(74,158,248,.15);color:var(--blue)}.t-google{background:rgba(232,39,42,.15);color:#f87171}.t-seo{background:rgba(34,201,122,.15);color:var(--green)}.t-wp{background:rgba(245,197,67,.15);color:var(--yellow)}.t-shopify{background:rgba(150,191,77,.15);color:#96bf4d}
.cc-actions{display:flex;gap:6px;flex-wrap:wrap}
.conn-dots{display:flex;gap:5px;margin-bottom:10px;flex-wrap:wrap}
.conn-dot{display:flex;align-items:center;gap:4px;font-size:10px;padding:2px 7px;border-radius:10px}
.cd-ok{background:rgba(34,201,122,.12);color:var(--green)}
.cd-no{background:rgba(255,255,255,.05);color:var(--muted)}
.alert{padding:10px 14px;border-radius:8px;font-size:13px;margin-bottom:16px}
.alert-ok{background:rgba(34,201,122,.1);border:1px solid rgba(34,201,122,.25);color:var(--green)}
.alert-err{background:rgba(232,39,42,.1);border:1px solid rgba(232,39,42,.25);color:#f87171}
.modal-bg{position:fixed;inset:0;background:rgba(0,0,0,.75);z-index:500;display:none;align-items:center;justify-content:center}
.modal-bg.open{display:flex}
.modal{background:var(--bg2);border:1px solid var(--border2);border-radius:14px;padding:0;width:560px;max-width:96vw;max-height:92vh;overflow-y:auto}
.modal-hd{padding:20px 24px 0;position:sticky;top:0;background:var(--bg2);z-index:10;border-bottom:1px solid var(--border)}
.modal-title{font-family:var(--fh);font-size:16px;font-weight:700;margin-bottom:14px}
.mtabs{display:flex;gap:2px;padding-bottom:0;overflow-x:auto}
.mtab{padding:7px 14px;font-size:12px;color:var(--muted);cursor:pointer;border:none;background:none;font-family:var(--fb);border-bottom:2px solid transparent;white-space:nowrap;transition:all .15s}
.mtab:hover{color:var(--text)}
.mtab.active{color:var(--text);border-bottom-color:var(--red)}
.modal-body{padding:20px 24px}
.tab-panel{display:none}.tab-panel.active{display:block}
.mf{display:flex;flex-direction:column;gap:5px;margin-bottom:14px}
.mf label{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.7px}
.mf input,.mf textarea{background:var(--bg3);border:1px solid var(--border2);border-radius:7px;padding:8px 11px;font-size:13px;color:var(--text);font-family:var(--fb);outline:none;width:100%}
.mf input:focus,.mf textarea:focus{border-color:rgba(232,39,42,.5)}
.mf .hint{font-size:11px;color:var(--muted);margin-top:3px}
.svc-check{display:flex;gap:7px;flex-wrap:wrap;margin-top:4px}
.sc{padding:5px 10px;border-radius:5px;border:1px solid var(--border2);cursor:pointer;font-size:12px;transition:all .15s}
.sc:hover{border-color:var(--border)}.sc.checked{border-color:var(--red-b);background:var(--red-l)}
.color-row{display:flex;gap:7px;margin-top:4px}
.co{width:22px;height:22px;border-radius:50%;cursor:pointer;border:2px solid transparent;transition:border-color .15s}
.modal-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:16px;padding-top:14px;border-top:1px solid var(--border)}
.save-msg{font-size:12px;margin-left:8px}
.section-title{font-family:var(--fh);font-size:13px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.7px;margin-bottom:14px;display:flex;align-items:center;gap:8px}
.cred-status{font-size:11px;padding:2px 7px;border-radius:8px}
.cs-ok{background:rgba(34,201,122,.12);color:var(--green)}
.cs-no{background:rgba(255,255,255,.05);color:var(--muted)}
.info-box{background:rgba(74,158,248,.08);border:1px solid rgba(74,158,248,.2);border-radius:8px;padding:10px 12px;font-size:12px;color:var(--blue);margin-bottom:14px;line-height:1.6}
::-webkit-scrollbar{width:4px}::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px}
</style>
</head>
<body>
<nav>
  <a class="logo" href="index.php"><div class="lm">D</div><div><div class="ln">DIMARK</div><div class="ls">Super Cerebro</div></div></a>
  <div class="nav-r">
    <a href="index.php"   class="nl">Dashboard</a>
    <a href="users.php"   class="nl">Usuarios</a>
    <a href="clients.php" class="nl active">Clientes</a>
    <a href="logout.php"  class="nl">Salir</a>
    <div class="av" style="background:<?= htmlspecialchars($user['color']) ?>"><?= strtoupper(substr($user['name'],0,2)) ?></div>
  </div>
</nav>
<main>
  <div class="ph">
    <div><div class="pt">Gestión de clientes</div><div class="ps"><?= count($clients) ?> clientes registrados</div></div>
    <button class="btn btn-primary" onclick="openNewModal()">+ Nuevo cliente</button>
  </div>
  <?php if($msg): ?><div class="alert alert-<?= $msgType ?>"><?= htmlspecialchars($msg) ?></div><?php endif ?>
  <?php if(!$pdo): ?><div class="alert alert-err">Sin conexión a BD.</div>
  <?php else: ?>
  <div class="grid">
    <?php foreach($clients as $c):
      $svcs = array_filter(explode(',',$c['services']));
      $cid  = (int)$c['id'];
    ?>
    <div class="client-card">
      <div class="cc-top">
        <div class="cc-av" style="background:<?= htmlspecialchars($c['color']) ?>18;color:<?= htmlspecialchars($c['color']) ?>"><?= strtoupper(substr($c['name'],0,2)) ?></div>
        <div><div class="cc-name"><?= htmlspecialchars($c['name']) ?></div><div class="cc-ind"><?= htmlspecialchars($c['industry']) ?></div></div>
      </div>
      <?php if($c['url']): ?><div class="cc-url"><?= htmlspecialchars($c['url']) ?></div><?php endif ?>
      <div class="cc-tags"><?php foreach($svcs as $s) echo '<span class="ctag t-'.$s.'">'.strtoupper($s).'</span>'; ?></div>
      <div class="conn-dots">
        <?php
        $services_map = ['meta'=>'Meta','google'=>'Google','gsc'=>'GSC','wordpress'=>'WP','shopify'=>'Shopify'];
        foreach($services_map as $svc=>$label):
          $connected = has_cred($all_creds, $cid, $svc);
        ?>
        <span class="conn-dot <?= $connected?'cd-ok':'cd-no' ?>">
          <?= $connected?'●':'○' ?> <?= $label ?>
        </span>
        <?php endforeach ?>
      </div>
      <div class="cc-actions">
        <button class="btn btn-blue btn-sm" onclick="openCredModal(<?= $cid ?>, '<?= htmlspecialchars(addslashes($c['name'])) ?>')">⚙ Credenciales</button>
        <form method="POST" onsubmit="return confirm('¿Eliminar <?= htmlspecialchars(addslashes($c['name'])) ?>?')" style="display:inline">
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="cid" value="<?= $cid ?>">
          <button type="submit" class="btn btn-ghost btn-sm" style="color:#f87171">Eliminar</button>
        </form>
      </div>
    </div>
    <?php endforeach ?>
  </div>
  <?php endif ?>
</main>

<!-- ===== MODAL NUEVO CLIENTE ===== -->
<div class="modal-bg" id="modalNew" onclick="if(event.target===this)this.classList.remove('open')">
  <div class="modal">
    <div class="modal-hd"><div class="modal-title">Nuevo cliente</div></div>
    <div class="modal-body">
    <form method="POST">
      <input type="hidden" name="action" value="create">
      <div class="mf"><label>Nombre *</label><input type="text" name="name" required placeholder="Ej: Clínica Dental MDE"></div>
      <div class="mf"><label>Industria</label><input type="text" name="industry" placeholder="Salud, Inmobiliaria, Ecommerce..."></div>
      <div class="mf"><label>Sitio web</label><input type="text" name="url" placeholder="cliente.com"></div>
      <div class="mf"><label>Servicios activos</label>
        <div class="svc-check">
          <?php foreach(['meta'=>'Meta Ads','google'=>'Google Ads','seo'=>'SEO','wp'=>'WordPress','shopify'=>'Shopify'] as $val=>$label): ?>
          <div class="sc" data-val="<?= $val ?>" onclick="toggleSvc(this)"><?= $label ?></div>
          <?php endforeach ?>
        </div>
        <div id="svc-inputs"></div>
      </div>
      <div class="mf"><label>Color</label>
        <div class="color-row">
          <?php foreach(['#4a9ef8','#22c97a','#f5c543','#9b7ff4','#f97316','#E8272A'] as $c): ?>
          <div class="co" data-color="<?= $c ?>" style="background:<?= $c ?>" onclick="pickColor(this,'<?= $c ?>')"></div>
          <?php endforeach ?>
        </div>
        <input type="hidden" name="color" id="colorVal" value="#4a9ef8">
      </div>
      <div class="mf"><label>Notas internas</label><textarea name="notes" rows="2" placeholder="Información adicional..."></textarea></div>
      <div class="modal-actions">
        <button type="button" class="btn btn-ghost" onclick="document.getElementById('modalNew').classList.remove('open')">Cancelar</button>
        <button type="submit" class="btn btn-primary">Crear cliente</button>
      </div>
    </form>
    </div>
  </div>
</div>

<!-- ===== MODAL CREDENCIALES ===== -->
<div class="modal-bg" id="modalCred" onclick="if(event.target===this)this.classList.remove('open')">
  <div class="modal">
    <div class="modal-hd">
      <div class="modal-title" id="cred-title">Credenciales del cliente</div>
      <div class="mtabs">
        <button class="mtab active" onclick="switchCredTab('meta')">📘 Meta Ads</button>
        <button class="mtab" onclick="switchCredTab('google')">🔴 Google Ads</button>
        <button class="mtab" onclick="switchCredTab('gsc')">🔍 Search Console</button>
        <button class="mtab" onclick="switchCredTab('wordpress')">⚡ WordPress</button>
        <button class="mtab" onclick="switchCredTab('shopify')">🛍 Shopify</button>
        <button class="mtab" onclick="switchCredTab('reportes')">📊 Reportes</button>
      </div>
    </div>
    <div class="modal-body">
      <input type="hidden" id="cred-client-id" value="">

      <!-- META ADS -->
      <div class="tab-panel active" id="tab-meta">
        <div class="section-title">📘 Meta Ads API <span class="cred-status cs-no" id="status-meta">No configurado</span></div>
        <div class="mf">
          <label>Ad Account ID</label>
          <input type="text" id="meta-account-id" placeholder="act_123456789">
          <div class="hint">Formato: act_XXXXXXXXX — encuéntralo en Business Manager → Cuentas publicitarias</div>
        </div>
        <div class="mf">
          <label>Access Token</label>
          <input type="password" id="meta-access-token" placeholder="EAAxxxxx...">
          <div class="hint">System User Token con permisos ads_read, ads_management</div>
        </div>
        <div class="modal-actions" style="border:none;padding:0">
          <span class="save-msg" id="msg-meta"></span>
          <button class="btn btn-primary btn-sm" onclick="saveCreds('meta')">Guardar Meta</button>
        </div>
      </div>

      <!-- GOOGLE ADS -->
      <div class="tab-panel" id="tab-google">
        <div class="section-title">🔴 Google Ads API <span class="cred-status cs-no" id="status-google">No configurado</span></div>
        <div class="info-box">
          El refresh token y developer token son globales y están configurados en el sistema. Solo necesitas ingresar el Customer ID de este cliente.
        </div>
        <div class="mf">
          <label>Customer ID</label>
          <input type="text" id="google-customer-id" placeholder="123-456-7890">
          <div class="hint">ID de la cuenta Google Ads del cliente — lo encuentras arriba a la derecha dentro de Google Ads</div>
        </div>
        <div class="modal-actions" style="border:none;padding:0">
          <span class="save-msg" id="msg-google"></span>
          <button class="btn btn-primary btn-sm" onclick="saveGoogleCreds()">Guardar Google</button>
        </div>
      </div>

      <!-- SEARCH CONSOLE -->
      <div class="tab-panel" id="tab-gsc">
        <div class="section-title">🔍 Google Search Console <span class="cred-status cs-no" id="status-gsc">No configurado</span></div>
        <div class="mf">
          <label>Dominio del sitio</label>
          <input type="text" id="gsc-domain" placeholder="ejemplo.com">
          <div class="hint">Solo el dominio sin https://</div>
        </div>
        <div class="mf">
          <label>Access Token OAuth</label>
          <input type="password" id="gsc-access-token" placeholder="ya29.xxxxxxxx">
          <div class="hint">Mismo OAuth de Google si usas la misma cuenta de servicio</div>
        </div>
        <div class="modal-actions" style="border:none;padding:0">
          <span class="save-msg" id="msg-gsc"></span>
          <button class="btn btn-primary btn-sm" onclick="saveCreds('gsc')">Guardar GSC</button>
        </div>
      </div>

      <!-- WORDPRESS -->
      <div class="tab-panel" id="tab-wordpress">
        <div class="section-title">⚡ WordPress REST API <span class="cred-status cs-no" id="status-wordpress">No configurado</span></div>
        <div class="mf">
          <label>URL del sitio</label>
          <input type="text" id="wp-url" placeholder="https://cliente.com">
          <div class="hint">URL completa con https://</div>
        </div>
        <div class="mf">
          <label>Usuario administrador</label>
          <input type="text" id="wp-username" placeholder="admin">
        </div>
        <div class="mf">
          <label>Application Password</label>
          <input type="password" id="wp-app-password" placeholder="xxxx xxxx xxxx xxxx xxxx xxxx">
          <div class="hint">WordPress Admin → Usuarios → Tu perfil → Application Passwords</div>
        </div>
        <div class="modal-actions" style="border:none;padding:0">
          <span class="save-msg" id="msg-wordpress"></span>
          <button class="btn btn-primary btn-sm" onclick="saveCreds('wordpress')">Guardar WordPress</button>
        </div>
      </div>

      <!-- SHOPIFY -->
      <div class="tab-panel" id="tab-shopify">
        <div class="section-title">🛍 Shopify Admin API <span class="cred-status cs-no" id="status-shopify">No configurado</span></div>
        <div class="mf">
          <label>Dominio de la tienda</label>
          <input type="text" id="shopify-domain" placeholder="mitienda.myshopify.com">
        </div>
        <div class="mf">
          <label>Admin API Access Token</label>
          <input type="password" id="shopify-token" placeholder="shpat_xxxxxxxxxxxxxxxx">
          <div class="hint">Shopify Admin → Apps → Desarrollar apps → Admin API Access Token</div>
        </div>
        <div class="modal-actions" style="border:none;padding:0">
          <span class="save-msg" id="msg-shopify"></span>
          <button class="btn btn-primary btn-sm" onclick="saveCreds('shopify')">Guardar Shopify</button>
        </div>
      </div>

      <!-- REPORTES -->
      <div class="tab-panel" id="tab-reportes">
        <div class="section-title">📊 Reportes Mensuales</div>
        <div class="mf">
          <label>Email del cliente (para envío de reportes)</label>
          <input type="email" id="rpt-contact-email" placeholder="contacto@cliente.com">
          <div class="hint">El reporte mensual se enviará automáticamente a esta dirección el día 1 de cada mes si activás el auto-envío.</div>
        </div>
        <div class="mf" style="display:flex;align-items:center;gap:12px;margin-top:4px">
          <label style="cursor:pointer;display:flex;align-items:center;gap:8px;font-size:13px">
            <input type="checkbox" id="rpt-auto-send" style="width:16px;height:16px;accent-color:var(--red);cursor:pointer">
            Activar envío automático mensual (cron día 1 del mes)
          </label>
        </div>
        <div class="modal-actions" style="border:none;padding:0;margin-top:16px">
          <span class="save-msg" id="msg-reportes"></span>
          <button class="btn btn-primary btn-sm" onclick="saveRptClientSettings()">Guardar configuración</button>
        </div>
      </div>

    </div>
  </div>
</div>

<script>
function csrfHeaders() {
    const t = document.querySelector('meta[name="dm-csrf"]')?.content || '';
    return {'Content-Type':'application/json','X-CSRF-TOKEN':t};
}

const selSvcs=[];
function openNewModal(){ document.getElementById('modalNew').classList.add('open'); }
function toggleSvc(el){const v=el.dataset.val;const i=selSvcs.indexOf(v);if(i>-1){selSvcs.splice(i,1);el.classList.remove('checked')}else{selSvcs.push(v);el.classList.add('checked')}renderSvcInputs();}
function renderSvcInputs(){document.getElementById('svc-inputs').innerHTML=selSvcs.map(s=>`<input type="hidden" name="services[]" value="${s}">`).join('');}
function pickColor(el,c){document.querySelectorAll('.co').forEach(e=>e.style.outline='none');el.style.outline='2px solid #fff';document.getElementById('colorVal').value=c;}
document.querySelector('.co')?.setAttribute('style', document.querySelector('.co').getAttribute('style') + ';outline:2px solid #fff');

let currentCredClientId = 0;

function openCredModal(clientId, clientName) {
    currentCredClientId = clientId;
    document.getElementById('cred-client-id').value = clientId;
    document.getElementById('cred-title').textContent = '⚙ Credenciales — ' + clientName;
    switchCredTab('meta');
    loadCredStatus(clientId);
    document.getElementById('modalCred').classList.add('open');
}

function loadCredStatus(clientId) {
    fetch(`api/get-credentials.php?client_id=${clientId}`)
        .then(r=>r.json())
        .then(data=>{
            if(!data.ok) return;
            const services = ['meta','google','gsc','wordpress','shopify'];
            services.forEach(svc=>{
                const el = document.getElementById('status-'+svc);
                if(!el) return;
                if(data.has[svc]){
                    el.className='cred-status cs-ok';
                    el.textContent='✓ Configurado';
                } else {
                    el.className='cred-status cs-no';
                    el.textContent='No configurado';
                }
            });
        }).catch(()=>{});
}

function switchCredTab(svc) {
    document.querySelectorAll('.mtab').forEach(t=>t.classList.remove('active'));
    document.querySelectorAll('.tab-panel').forEach(p=>p.classList.remove('active'));
    document.getElementById('tab-'+svc)?.classList.add('active');
    const tabs = ['meta','google','gsc','wordpress','shopify','reportes'];
    const idx = tabs.indexOf(svc);
    document.querySelectorAll('.mtab')[idx]?.classList.add('active');
    if (svc === 'reportes') loadRptClientSettings(currentCredClientId);
}

// Guardar Google Ads — solo customer_id, el resto es global
function saveGoogleCreds() {
    const clientId = currentCredClientId;
    if(!clientId){ alert('Error: no hay cliente seleccionado'); return; }
    const customerId = document.getElementById('google-customer-id')?.value?.trim();
    if(!customerId){ showMsg('google','⚠ Ingresa el Customer ID','var(--yellow)'); return; }

    showMsg('google','Guardando...','var(--muted)');

    fetch('api/save-google-credentials.php', {
        method: 'POST',
        headers: csrfHeaders(),
        body: JSON.stringify({
            client_id: clientId,
            credentials: {
                customer_id: customerId,
                developer_token: 'zz8sYP3BLpCvUhjrypR8mg',
                mcc_id: '3775987654'
            }
        })
    })
    .then(r=>r.json())
    .then(res=>{
        if(res.ok){
            showMsg('google','✓ Guardado','var(--green)');
            const el = document.getElementById('status-google');
            if(el){ el.className='cred-status cs-ok'; el.textContent='✓ Configurado'; }
            setTimeout(()=>location.reload(), 1200);
        } else {
            showMsg('google','✗ ' + (res.error||'Error'),'var(--red)');
        }
    })
    .catch(()=>showMsg('google','✗ Error de conexión','var(--red)'));
}

// Guardar otros servicios
function saveCreds(service) {
    const clientId = currentCredClientId;
    if(!clientId){ alert('Error: no hay cliente seleccionado'); return; }

    const fieldsMap = {
        meta:      {ad_account_id: 'meta-account-id', access_token: 'meta-access-token'},
        gsc:       {domain: 'gsc-domain', access_token: 'gsc-access-token'},
        wordpress: {url: 'wp-url', username: 'wp-username', app_password: 'wp-app-password'},
        shopify:   {shop_domain: 'shopify-domain', access_token: 'shopify-token'},
    };

    const fields = {};
    Object.entries(fieldsMap[service] || {}).forEach(([key, elemId])=>{
        const val = document.getElementById(elemId)?.value?.trim();
        if(val) fields[key] = val;
    });

    if(Object.keys(fields).length === 0){
        showMsg(service,'⚠ Ingresa al menos un campo','var(--yellow)');
        return;
    }

    showMsg(service,'Guardando...','var(--muted)');

    fetch('api/save-credentials.php', {
        method: 'POST',
        headers: csrfHeaders(),
        body: JSON.stringify({client_id: clientId, service, fields})
    })
    .then(r=>r.json())
    .then(res=>{
        if(res.ok){
            showMsg(service,'✓ Guardado','var(--green)');
            const el = document.getElementById('status-'+service);
            if(el){ el.className='cred-status cs-ok'; el.textContent='✓ Configurado'; }
            setTimeout(()=>location.reload(), 1200);
        } else {
            showMsg(service,'✗ ' + (res.error||'Error'),'var(--red)');
        }
    })
    .catch(()=>showMsg(service,'✗ Error de conexión','var(--red)'));
}

function showMsg(service, text, color){
    const el = document.getElementById('msg-'+service);
    if(!el) return;
    el.textContent = text;
    el.style.color = color;
    if(text !== 'Guardando...') setTimeout(()=>el.textContent='', 3000);
}
</script>
</body>
</html>