<!-- ===================== WHATSAPP CONNECT TAB ===================== -->
<div class="tab-pane <?= (isset($_GET['tab']) && $_GET['tab'] == 'whatsapp') ? 'active' : '' ?>" id="tab-whatsapp">
  <div style="max-width:700px">

    <!-- Header -->
    <div class="card" style="margin-bottom:20px;background:linear-gradient(135deg,#25D366 0%,#128C7E 100%);border:none;">
      <div class="card-body" style="display:flex;align-items:center;gap:16px;padding:24px;">
        <div style="width:56px;height:56px;background:rgba(255,255,255,0.2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:28px;flex-shrink:0;">💬</div>
        <div>
          <div style="font-size:20px;font-weight:700;color:#fff;">WhatsApp Connect</div>
          <div style="color:rgba(255,255,255,0.85);font-size:14px;margin-top:2px;">Link your WhatsApp number to send messages directly from the CRM</div>
        </div>
      </div>
    </div>

    <?php if ($wa_connected): ?>
    <!-- ══════════ ALREADY CONNECTED ══════════ -->
    <div class="card" style="margin-bottom:20px;border:2px solid #25D366;">
      <div class="card-body" style="padding:24px;">
        <div style="display:flex;align-items:center;gap:16px;">
          <div style="width:52px;height:52px;background:#DCFCE7;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:26px;flex-shrink:0;">✅</div>
          <div style="flex:1;">
            <div style="font-weight:700;font-size:16px;color:#166534;">WhatsApp Connected</div>
            <div class="text-sm text-muted" style="margin-top:4px;">
              Phone: <strong><?= htmlspecialchars($wa_connected['phone_number'] ?: '—') ?></strong>
            </div>
            <div class="text-xs text-muted" style="margin-top:2px;">Client ID: <?= htmlspecialchars($wa_connected['client_id']) ?></div>
          </div>
          <button class="btn btn-danger btn-sm" onclick="disconnectAndReset('<?= htmlspecialchars($wa_connected['client_id']) ?>')">🔌 Disconnect</button>
        </div>
      </div>
    </div>

    <?php else: ?>
    <!-- ══════════ NOT CONNECTED — Connect Flow ══════════ -->

    <!-- Step 1: Create Client -->
    <div class="card" id="wa-step-create" style="margin-bottom:20px;">
      <div class="card-header">
        <span class="card-title">
          <span style="display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;background:var(--primary,#3B82F6);color:#fff;border-radius:50%;font-size:12px;font-weight:700;margin-right:8px;">1</span>
          Create WhatsApp Client
        </span>
      </div>
      <div class="card-body">
        <p class="text-muted text-sm" style="margin-bottom:16px;">Give your WhatsApp connection a name, then scan the QR code with your phone.</p>
        <div style="display:flex;gap:12px;align-items:flex-end;">
          <div class="form-group" style="flex:1;margin-bottom:0;">
            <label class="form-label">Connection Name *</label>
            <input type="text" id="wa_client_name" class="form-control" placeholder="e.g. Sales Line">
          </div>
          <button class="btn btn-primary" onclick="createWaClient()" id="wa_create_btn" style="white-space:nowrap;">
            🔗 Connect WhatsApp
          </button>
        </div>
      </div>
    </div>

    <!-- Step 2: QR Code -->
    <div class="card" id="wa-step-qr" style="margin-bottom:20px;display:none;">
      <div class="card-header">
        <span class="card-title">
          <span style="display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;background:var(--primary,#3B82F6);color:#fff;border-radius:50%;font-size:12px;font-weight:700;margin-right:8px;">2</span>
          Scan QR Code with WhatsApp
        </span>
      </div>
      <div class="card-body">
        <div style="display:flex;gap:32px;align-items:flex-start;flex-wrap:wrap;">

          <!-- QR Image -->
          <div style="text-align:center;flex-shrink:0;">
            <div id="wa_qr_wrapper" style="width:224px;height:224px;border:3px solid #25D366;border-radius:16px;overflow:hidden;background:#fff;display:flex;align-items:center;justify-content:center;">
              <div id="wa_qr_loading" style="text-align:center;color:#888;padding:16px;">
                <div style="font-size:32px;margin-bottom:8px;">⏳</div>
                <div style="font-size:13px;">Loading QR...</div>
              </div>
              <img id="wa_qr_img"
     src=""
     alt="QR Code"
     style="width:100%;height:100%;object-fit:contain;display:none;"
     onload="
        document.getElementById('wa_qr_loading').style.display='none';
        this.style.display='block';
     "
     onerror="
        document.getElementById('wa_qr_loading').innerHTML='❌ Failed loading QR';
     "
>
                   
            </div>
            <div style="margin-top:10px;">
              <span id="wa_status_badge" class="badge badge-gray">Initializing...</span>
            </div>
            <button class="btn btn-secondary btn-sm" style="margin-top:10px;" onclick="refreshQR()" id="wa_refresh_btn">🔄 Refresh QR</button>
          </div>

          <!-- Instructions -->
          <div style="flex:1;min-width:200px;">
            <p class="text-sm font-bold" style="margin-bottom:12px;">How to scan:</p>
            <ol style="padding-left:20px;color:var(--text-muted,#6B7280);font-size:14px;line-height:2.2;">
              <li>Open WhatsApp on your phone</li>
              <li>Tap <strong>⋮ Menu</strong> (Android) or <strong>Settings</strong> (iPhone)</li>
              <li>Tap <strong>Linked Devices</strong></li>
              <li>Tap <strong>Link a Device</strong></li>
              <li>Point your phone at the QR code</li>
            </ol>
            <div id="wa_connected_msg" style="display:none;margin-top:16px;padding:14px;background:#F0FDF4;border:1px solid #86EFAC;border-radius:10px;">
              <div style="font-size:20px;margin-bottom:4px;">✅</div>
              <div style="font-weight:700;color:#166534;">Connected!</div>
              <div style="font-size:13px;color:#166534;margin-top:4px;">Saving to database...</div>
            </div>
          </div>
        </div>

        <div style="margin-top:20px;">
          <button class="btn btn-secondary btn-sm" onclick="resetWaStep()">← Start Over</button>
        </div>
      </div>
    </div>

    <?php endif; ?>
  </div>
</div>
<script>
// ──────────────────────────────────────────────
// WhatsApp Connect JS
// ──────────────────────────────────────────────
const WA_API_BASE = 'https://amctag-whats.38f0fz.easypanel.host/api';
const WA_TOKEN    = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI3MzFiMTlhNDdlZDg2MjUxZDg2YjYyYTYiLCJ0eXBlIjoidXNlciIsImlhdCI6MTc3OTE3NzE1Nn0.NaszEOLCnWT59oXBCdi7WKwXT-QbZWpFF3G_64fsTDs';

let waClientId   = null;  // "client_xxxx"
let waInternalId = null;  // MongoDB _id
let waImageUrl   = null;  // QR PNG url
let waPollTimer  = null;
let waPollActive = false;

async function waFetch(path, method = 'GET', body = null) {
    const opts = {
        method,
        headers: { 'Authorization': `Bearer ${WA_TOKEN}`, 'Content-Type': 'application/json' }
    };
    if (body) opts.body = JSON.stringify(body);
    const res = await fetch(WA_API_BASE + path, opts);
    return res.json();
}

// ── 1. Create Client ──────────────────────────────────────────
async function createWaClient() {
    const name = document.getElementById('wa_client_name').value.trim();
    if (!name) { showToast('Enter a connection name', 'warning'); return; }

    const btn = document.getElementById('wa_create_btn');
    btn.disabled = true;
    btn.innerHTML = '⏳ Creating...';

    try {
        const data = await waFetch('/clients', 'POST', { name });

        if (data.client && data.qrShare) {
            waClientId   = data.client.clientId;
            waInternalId = data.client._id;
            waImageUrl   = data.qrShare.imageUrl;
            if (waImageUrl.startsWith('http://')) {
    waImageUrl = waImageUrl.replace('http://', 'https://');
}

            // بنبين الـ QR step وبنحمل الصورة فورًا
            document.getElementById('wa-step-create').style.display = 'none';
            document.getElementById('wa-step-qr').style.display     = 'block';
            loadQRImage();
            startStatusPoll();
            showToast('Client created! Scan the QR.', 'success');
        } else {
            showToast(data.message || 'Failed to create client', 'error');
            btn.disabled = false;
            btn.innerHTML = '🔗 Connect WhatsApp';
        }
    } catch(e) {
        showToast('Network error: ' + e.message, 'error');
        btn.disabled = false;
        btn.innerHTML = '🔗 Connect WhatsApp';
    }
}

// ── 2. Load QR Image (فوري من الـ imageUrl) ──────────────────
// function loadQRImage() {
//     if (!waImageUrl) return;

//     const img     = document.getElementById('wa_qr_img');
//     const loading = document.getElementById('wa_qr_loading');

//     // نخبي الصورة القديمة ونبين الـ spinner
//     img.style.display     = 'none';
//     loading.style.display = 'block';
//     loading.innerHTML     = '<div style="font-size:28px">⏳</div><div style="font-size:13px;margin-top:6px">Loading QR...</div>';

//     // cache-buster
//     const sep = waImageUrl.includes('?') ? '&' : '?';
//     img.src = waImageUrl ;
//     // img.src = "https://www.amctag.com/assets/images/logo-blue-2.png";
//     // الـ onload بالـ HTML راح يخبي الـ spinner وبيبين الصورة
// }


let qrRetryCount = 0;
let qrRetryTimer = null;

function loadQRImage() {
    if (!waImageUrl) return;

    const img = document.getElementById('wa_qr_img');
    const loading = document.getElementById('wa_qr_loading');

    qrRetryCount = 0;
    clearTimeout(qrRetryTimer);

    function tryLoadQR() {
        qrRetryCount++;

        img.style.display = 'none';
        loading.style.display = 'block';
        loading.innerHTML =
            '<div style="font-size:28px">⏳</div>' +
            '<div style="font-size:13px;margin-top:6px">Loading QR... attempt ' + qrRetryCount + '</div>';

        const url = waImageUrl.replace('http://', 'https://');
        const sep = url.includes('?') ? '&' : '?';

        img.onload = function () {
            clearTimeout(qrRetryTimer);
            loading.style.display = 'none';
            img.style.display = 'block';
        };

        img.onerror = function () {
            console.log('QR not ready, retry...', img.src);

            if (qrRetryCount < 15) {
                qrRetryTimer = setTimeout(tryLoadQR, 1000);
            } else {
                loading.innerHTML =
                    '<div style="font-size:20px">❌</div>' +
                    '<div style="font-size:12px;margin-top:6px">QR not ready. Click Refresh</div>';
            }
        };

        img.src = url + sep + '_t=' + Date.now();
    }

    tryLoadQR();
}



// ── 3. Refresh QR ─────────────────────────────────────────────
function refreshQR() {
    const btn = document.getElementById('wa_refresh_btn');
    btn.disabled = true;
    btn.textContent = '⏳';
    loadQRImage();
    setTimeout(() => { btn.disabled = false; btn.textContent = '🔄 Refresh QR'; }, 1800);
}

// ── 4. Poll Status — بيوقف فور connected ─────────────────────
function startStatusPoll() {
    clearInterval(waPollTimer);
    waPollActive = true;

    waPollTimer = setInterval(async () => {
        if (!waPollActive || !waClientId) {
            clearInterval(waPollTimer);
            return;
        }

        try {
            const data    = await waFetch('/clients');
            const clients = Array.isArray(data) ? data : (data.clients || []);
            const client  = clients.find(c => c.clientId === waClientId);
            if (!client) return;

            const status = client.status || '';
            updateStatusBadge(status);

            if (status === 'connected' || status === 'ready') {
                // ✅ وقف الـ poll فورًا
                waPollActive = false;
                clearInterval(waPollTimer);
                onWaConnected(client.phone || null);
            }
        } catch(e) { /* silent */ }
    }, 3000);
}

// ── 5. On Connected — بيحفظ بالـ DB وبـ reload ───────────────
async function onWaConnected(phone) {
    document.getElementById('wa_connected_msg').style.display = 'block';
    document.getElementById('wa_qr_wrapper').style.borderColor = '#25D366';
    updateStatusBadge('connected');
    showToast('WhatsApp connected! 🎉', 'success');

    try {
        const res = await apiCall('handlers/settings.php', {
            action:       'save_wa_client',
            client_id:    waInternalId,
            phone_number: phone || ''
        });
        if (res.success) {
            showToast('Saved! Reloading...', 'success');
            setTimeout(() => location.reload(), 1500);
        } else {
            showToast('Connected but DB error: ' + (res.message || ''), 'warning');
        }
    } catch(e) {
        showToast('Connected but could not save to DB', 'warning');
    }
}

// ── Status Badge ──────────────────────────────────────────────
function updateStatusBadge(status) {
    const badge = document.getElementById('wa_status_badge');
    if (!badge) return;
    const map = {
        'initializing': { cls:'badge-gray',  txt:'Initializing...' },
        'qr_ready':     { cls:'badge-blue',  txt:'Waiting for scan...' },
        'connecting':   { cls:'badge-blue',  txt:'Connecting...' },
        'connected':    { cls:'badge-green', txt:'Connected ✓' },
        'ready':        { cls:'badge-green', txt:'Connected ✓' },
        'disconnected': { cls:'badge-red',   txt:'Disconnected' },
    };
    const info = map[status] || { cls:'badge-gray', txt: status || '—' };
    badge.className   = 'badge ' + info.cls;
    badge.textContent = info.txt;
}

// ── Disconnect من الـ connected card ─────────────────────────
async function disconnectAndReset(clientId) {
    if (!confirm('Disconnect WhatsApp and remove from CRM?')) return;
    try { await waFetch('/clients/' + clientId + '/disconnect', 'POST'); } catch(e) {}
    const res = await apiCall('handlers/settings.php', { action: 'delete_wa_client' });
    if (res.success) {
        showToast('Disconnected', 'success');
        setTimeout(() => location.reload(), 800);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

// ── Start Over ────────────────────────────────────────────────
function resetWaStep() {
    waPollActive = false;
    clearInterval(waPollTimer);
    waClientId = waInternalId = waImageUrl = null;

    document.getElementById('wa-step-create').style.display = 'block';
    document.getElementById('wa-step-qr').style.display     = 'none';
    document.getElementById('wa_client_name').value         = '';

    const btn = document.getElementById('wa_create_btn');
    if (btn) { btn.disabled = false; btn.innerHTML = '🔗 Connect WhatsApp'; }

    const img     = document.getElementById('wa_qr_img');
    const loading = document.getElementById('wa_qr_loading');
    if (img)     { img.src = ''; img.style.display = 'none'; }
    if (loading) { loading.style.display = 'block'; loading.innerHTML = '<div style="font-size:28px">⏳</div><div style="font-size:13px;margin-top:6px">Loading QR...</div>'; }

    const msg = document.getElementById('wa_connected_msg');
    if (msg) msg.style.display = 'none';
}

// ── وقف الـ poll لو المستخدم غير الـ tab ─────────────────────
document.addEventListener('click', function(e) {
    const btn = e.target.closest('.tab-btn');
    if (btn && btn.dataset.tab !== 'tab-whatsapp') {
        waPollActive = false;
        clearInterval(waPollTimer);
    }
});
</script>
