// ── SMS Tab ────────────────────────────────────────────────────────────

// Render PPSMS documentation (called when provider is selected)
function renderPpsmsDocs() {
    const container = document.getElementById('smsDocsContent');
    if (!container) {
        console.error('smsDocsContent element not found');
        return;
    }
    container.innerHTML = `
        <h6 class="mb-2">📘 PPSMS API Guide</h6>
        <p class="mb-2">This driver automatically chooses between <strong>single</strong> and <strong>bulk</strong> endpoints based on input.</p>

        <div class="accordion" id="ppsmsDocsAccordion">
            <div class="accordion-item">
                <h2 class="accordion-header" id="headingSingle">
                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseSingle">
                        📨 Single SMS
                    </button>
                </h2>
                <div id="collapseSingle" class="accordion-collapse collapse show" data-bs-parent="#ppsmsDocsAccordion">
                    <div class="accordion-body">
                        <p>Endpoint: <code>POST https://sms.ppradhan.com.np/api/send_sms.php</code></p>
                        <p><strong>Usage:</strong> Enter a single phone number in the "Test SMS" field.</p>
                        <p class="mb-1"><strong>Example (PHP event):</strong></p>
                        <pre class="bg-light p-2 rounded small"><code>$sms = new \\PpPhp\\Core\\SMS();
$sms->send('9841200000', 'Your OTP is 123456', 'Ppsms');</code></pre>
                        <p class="text-muted mb-0">Optional: Provide a Sender ID in the settings.</p>
                    </div>
                </div>
            </div>

            <div class="accordion-item">
                <h2 class="accordion-header" id="headingBulk">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseBulk">
                        👥 Bulk SMS (Multiple Numbers)
                    </button>
                </h2>
                <div id="collapseBulk" class="accordion-collapse collapse" data-bs-parent="#ppsmsDocsAccordion">
                    <div class="accordion-body">
                        <p>Endpoint: <code>POST https://sms.ppradhan.com.np/api/send_campaign.php</code></p>
                        <p><strong>Usage:</strong> Enter comma‑separated numbers in the "Test SMS" field (e.g., <code>9841000000,9842000000</code>).</p>
                        <p class="mb-1"><strong>Example (PHP event):</strong></p>
                        <pre class="bg-light p-2 rounded small"><code>$numbers = ['9841000000', '9842000000'];
$sms->send(implode(',', $numbers), 'Alert: Server update at 10pm', 'Ppsms');</code></pre>
                    </div>
                </div>
            </div>

            <div class="accordion-item">
                <h2 class="accordion-header" id="headingGroup">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseGroup">
                        📇 Bulk SMS to Phonebook Group
                    </button>
                </h2>
                <div id="collapseGroup" class="accordion-collapse collapse" data-bs-parent="#ppsmsDocsAccordion">
                    <div class="accordion-body">
                        <p><strong>Usage:</strong> Provide a <strong>Group ID</strong> in the settings (optional field). When a Group ID is set, the driver will ignore the "Test SMS" field and send to the whole group.</p>
                        <p class="mb-1"><strong>Example (PHP event):</strong></p>
                        <pre class="bg-light p-2 rounded small"><code>$config = ['api_token' => 'your_token', 'group_id' => 5];
$sms->send('', 'Special announcement', 'Ppsms', $config);</code></pre>
                        <p class="text-muted mb-0">Note: The <code>$to</code> parameter can be left empty when using <code>group_id</code>.</p>
                    </div>
                </div>
            </div>

            <div class="accordion-item">
                <h2 class="accordion-header" id="headingSchedule">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseSchedule">
                        ⏰ Scheduled SMS (Bulk only)
                    </button>
                </h2>
                <div id="collapseSchedule" class="accordion-collapse collapse" data-bs-parent="#ppsmsDocsAccordion">
                    <div class="accordion-body">
                        <p><strong>Usage:</strong> Add a <code>scheduled_at</code> parameter to your configuration array.</p>
                        <p class="mb-1"><strong>Example (PHP event):</strong></p>
                        <pre class="bg-light p-2 rounded small"><code>$config = [
    'api_token'    => 'your_token',
    'scheduled_at' => '2025-12-25 08:00:00',
];
$sms->send('9841000000,9842000000', 'Merry Christmas!', 'Ppsms', $config);</code></pre>
                        <p class="text-muted mb-0">Format: <code>YYYY-MM-DD HH:MM:SS</code>. Works with bulk or group mode.</p>
                    </div>
                </div>
            </div>

            <div class="accordion-item">
                <h2 class="accordion-header" id="headingEvents">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseEvents">
                        🔗 Using in Project Events (PHP)
                    </button>
                </h2>
                <div id="collapseEvents" class="accordion-collapse collapse" data-bs-parent="#ppsmsDocsAccordion">
                    <div class="accordion-body">
                        <p>In your <strong>Events</strong> module, you can call SMS like this:</p>
                        <pre class="bg-light p-2 rounded small"><code>use PpPhp\Core\SMS;

function onOrderStatusChanged($order) {
    $sms = new SMS();
    $result = $sms->send(
        $order['customer_phone'],
        "Your order #{$order['id']} is now {$order['status']}.",
        'Ppsms'   // provider name as stored in config
    );
    if (!$result['success']) {
        error_log('SMS failed: ' . $result['error']);
    }
}</code></pre>
                    </div>
                </div>
            </div>
        </div>
        <hr class="my-2">
        <p class="mb-0 text-muted"><i class="bi bi-shield-check"></i> <strong>Authentication:</strong> Bearer token (required). All examples assume the token is set in the Misc → SMS settings.</p>
    `;
}

function fillSmsProviderDropdown() {
    const select = document.getElementById('smsProvider');
    if (!select || typeof smsDrivers === 'undefined') {
        console.warn('smsDrivers not defined or select missing');
        return;
    }
    select.innerHTML = '';
    // console.log('Available SMS drivers:', smsDrivers);
    for (const [key, info] of Object.entries(smsDrivers)) {
        select.innerHTML += `<option value="${key}">${info.label}</option>`;
    }
}

function applySmsPreset() {
    const provider = document.getElementById('smsProvider').value;
    const providerLower = provider.toLowerCase();
    // console.log('Selected provider:', provider);
    const p = smsDrivers[provider] || {};
    const docsPanel = document.getElementById('smsDocsPanel');
    const docsContent = document.getElementById('smsDocsContent');


    // Show documentation for any provider whose name contains 'ppsms' (case‑insensitive)
    if (providerLower.includes('ppsms')) {
        // console.log('Rendering PPSMS documentation');
        renderPpsmsDocs();
        if (docsPanel) {
            docsPanel.style.display = 'block';
            docsPanel.style.border = '2px solid red';  // temporary: verify visibility
        }
    } else {
        if (docsPanel) docsPanel.style.display = 'none';
    }

    document.getElementById('smsHelp').textContent = p.help || '';
    const container = document.getElementById('smsFields');
    let html = '';
    if (p.fields) {
        for (const [key, label] of Object.entries(p.fields)) {
            html += `<div class="col-md-6"><label class="form-label small mb-1">${label}</label><input type="text" class="form-control form-control-sm sms-setting" id="sms_${key}" data-key="${key}"></div>`;
        }
    }
    container.innerHTML = html;
    const cfg = currentConfig.sms || {};
    if (p.fields) {
        for (const key of Object.keys(p.fields)) {
            const el = document.getElementById('sms_' + key);
            if (el) el.value = cfg[key] || '';
        }
    }
    container.querySelectorAll('.sms-setting').forEach(el => el.addEventListener('change', () => saveSection('sms')));
}

function populateSmsTab() {
    const cfg = currentConfig.sms || {};
    document.getElementById('smsProvider').value = cfg.provider || 'twilio';
    applySmsPreset();
    const custom = cfg.customProviders || {};
    const sel = document.getElementById('smsProvider');
    sel.querySelectorAll('option').forEach(opt => {
        if (opt.value === cfg.provider && custom[cfg.provider]) opt.dataset.custom = 'true';
    });
}

// Helper to collect current SMS settings (provider + dynamic fields)
function getCurrentSmsData() {
    const data = { provider: document.getElementById('smsProvider')?.value || '' };
    document.querySelectorAll('#smsFields .sms-setting').forEach(el => {
        data[el.dataset.key] = el.value;
    });
    return data;
}

// Save on page hide (navigation, refresh, close) using sendBeacon
window.addEventListener('pagehide', () => {
    const smsData = getCurrentSmsData();
    if (Object.keys(smsData).length) {
        navigator.sendBeacon(
            `${baseUrl}/project/${projectSlug}/misc/save`,
            JSON.stringify({ section: 'sms', data: smsData })
        );
    }
});

document.addEventListener('DOMContentLoaded', () => {
    fillSmsProviderDropdown();
    document.getElementById('smsProvider')?.addEventListener('change', () => {
        applySmsPreset();
        saveSection('sms');
    });
    document.getElementById('btnTestSms')?.addEventListener('click', async () => {
        const to = await pp.dialog.prompt('Send test SMS to:', '+1234567890');
        if (!to) return;
        Swal.fire({ title: 'Sending test SMS…', text: 'Please wait while we verify your configuration.', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
        try {
            const settings = getCurrentSmsData();
            const res = await fetch(`${baseUrl}/project/${projectSlug}/misc/test-sms`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ to, settings })
            });
            const rawText = await res.text();
            let data;
            try { data = JSON.parse(rawText); }
            catch (e) { Swal.close(); console.error('Invalid JSON received:', rawText); pp.dialog.alert('Server Error', 'The server returned an unexpected response.', 'error'); return; }
            Swal.close();
            if (data.success) pp.dialog.toast('success', 'Test SMS sent successfully!');
            else pp.dialog.alert('Failed', data.error || data.message, 'error');
        } catch (err) { Swal.close(); pp.dialog.toast('error', 'Network error.'); }
    });

    // Custom provider modal handlers (unchanged)
    document.getElementById('btnAddCustomProvider')?.addEventListener('click', () => openCustomProviderModal());
    document.getElementById('btnSaveCustomProvider')?.addEventListener('click', saveCustomProvider);
    document.getElementById('btnDeleteCustomProvider')?.addEventListener('click', deleteCustomProvider);

    function openCustomProviderModal(key = null) {
        const cfg = currentConfig.sms?.customProviders || {};
        if (key && cfg[key]) {
            const c = cfg[key];
            document.getElementById('cpModalTitle').textContent = 'Edit Custom Provider';
            document.getElementById('cpEditKey').value = key;
            document.getElementById('cpKey').value = key; document.getElementById('cpKey').readOnly = true;
            document.getElementById('cpLabel').value = c.label || '';
            document.getElementById('cpUrl').value = c.url || '';
            document.getElementById('cpMethod').value = c.method || 'POST';
            document.getElementById('cpToParam').value = c.toParam || 'to';
            document.getElementById('cpMsgParam').value = c.msgParam || 'message';
            document.getElementById('cpFromParam').value = c.fromParam || 'from';
            document.getElementById('cpExtraParams').value = c.extraParams || '';
            document.getElementById('btnDeleteCustomProvider').classList.remove('d-none');
        } else {
            document.getElementById('cpModalTitle').textContent = 'Add Custom Provider';
            document.getElementById('cpEditKey').value = '';
            document.getElementById('cpKey').value = ''; document.getElementById('cpKey').readOnly = false;
            document.getElementById('cpLabel').value = '';
            document.getElementById('cpUrl').value = '';
            document.getElementById('cpMethod').value = 'POST';
            document.getElementById('cpToParam').value = 'to';
            document.getElementById('cpMsgParam').value = 'message';
            document.getElementById('cpFromParam').value = 'from';
            document.getElementById('cpExtraParams').value = '';
            document.getElementById('btnDeleteCustomProvider').classList.add('d-none');
        }
        new bootstrap.Modal(document.getElementById('customProviderModal')).show();
    }

    async function saveCustomProvider() {
        if (typeof isPageUnloading !== 'undefined' && isPageUnloading) return;
        const key = document.getElementById('cpKey').value.trim();
        const data = {
            label: document.getElementById('cpLabel').value.trim(),
            url: document.getElementById('cpUrl').value.trim(),
            method: document.getElementById('cpMethod').value,
            toParam: document.getElementById('cpToParam').value.trim(),
            msgParam: document.getElementById('cpMsgParam').value.trim(),
            fromParam: document.getElementById('cpFromParam').value.trim(),
            extraParams: document.getElementById('cpExtraParams').value.trim(),
        };
        if (!key || !data.label || !data.url) { pp.dialog.toast('error', 'Key, label, and URL are required.'); return; }
        if (!currentConfig.sms) currentConfig.sms = {};
        if (!currentConfig.sms.customProviders) currentConfig.sms.customProviders = {};
        currentConfig.sms.customProviders[key] = data;
        await fetch(`${baseUrl}/project/${projectSlug}/misc/sms/custom`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key, data }) });
        location.reload();
    }

    async function deleteCustomProvider() {
        const key = document.getElementById('cpEditKey').value;
        if (!key) return;
        const ok = await pp.dialog.confirm('Delete provider?', `Remove "${key}" permanently?`);
        if (!ok) return;
        delete currentConfig.sms.customProviders[key];
        await fetch(`${baseUrl}/project/${projectSlug}/misc/sms/custom`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key, data: null }) });
        location.reload();
    }
});