<?php
require_once __DIR__ . '/../lib/audience_rules.php';

$isEdit = ($_GET['page'] ?? '') === 'campaign_edit';
$id     = (int) ($_GET['id'] ?? 0);

$camp = [
    'name'              => '',
    'description'       => '',
    'status'            => 1,
    'type_whatsapp'     => 1,
    'type_email'        => 0,
    'type_sms'          => 0,
    'target_type'       => 'audience',
    'audience_id'       => 0,
    'rules_json'        => '',
    'message_whatsapp'  => '',
    'message_email'     => '',
    'message_sms'       => '',
    'email_subject'     => '',
    'media_url'         => '',
    'media_type'        => '',
];

if ($isEdit) {
    $q = $conn->query("SELECT * FROM campaign WHERE id=$id AND account_id=$account_id LIMIT 1");
    if ($q && $q->num_rows) {
        $camp = $q->fetch_assoc();
        if (!empty($camp['is_sent'])) { echo '<div class="alert alert-error">This campaign was already sent and cannot be edited.</div>'; return; }
    } else {
        echo '<div class="alert alert-error">Campaign not found</div>';
        return;
    }
}

$rules           = crm_decode_rules($camp['rules_json'] ?? '');
$audiences       = $conn->query("SELECT id,name FROM audience WHERE account_id=$account_id AND statuss=1 ORDER BY name");
$countries       = $conn->query("SELECT c.id,c.name FROM country_account ca INNER JOIN countries c ON c.id=ca.country_id WHERE ca.account_id=$account_id ORDER BY c.name");
$labels          = $conn->query("SELECT id,name,color FROM customer_lable WHERE account_id=$account_id AND status=1 ORDER BY name");
$sources         = tableExists($conn,'customer_sources') ? $conn->query("SELECT id,name FROM customer_sources WHERE account_id=$account_id AND datetime_deleted IS NULL ORDER BY name") : (tableExists($conn,'source') ? $conn->query("SELECT id,name FROM source WHERE account_id=$account_id ORDER BY name") : false);
$items           = $conn->query("SELECT id,name FROM items WHERE account_id=$account_id ORDER BY name");
$manualCustomers = $conn->query("SELECT id,customer_name,business_name,phone FROM customers WHERE account_id=$account_id ORDER BY customer_name ASC");

function cin($arr, $id) {
    return in_array((int)$id, array_map('intval', $arr ?? [])) ? 'checked' : '';
}

// Build the initially-active tab from saved data
$initialTab = 'wa'; // default
if (!empty($camp['type_whatsapp'])) $initialTab = 'wa';
elseif (!empty($camp['type_email'])) $initialTab = 'email';
elseif (!empty($camp['type_sms']))   $initialTab = 'sms';
?>

<div class="fade-in campaign-form-page">
    <div class="toolbar">
        <a href="index.php?page=campaigns" class="btn btn-secondary">← Back</a>
    </div>

    <div class="card" style="padding:20px;max-width:1100px">
        <h3 style="margin-top:0"><?= $isEdit ? 'Edit' : 'Add' ?> Campaign</h3>

        <form id="campaignForm" enctype="multipart/form-data">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id"     value="<?= $id ?>">

            <!-- Name & Status -->
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Campaign Name *</label>
                    <input name="name" required class="form-control" value="<?= htmlspecialchars($camp['name']) ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-control">
                        <option value="1" <?= (int)$camp['status'] ? 'selected' : '' ?>>Active</option>
                        <option value="0" <?= !(int)$camp['status'] ? 'selected' : '' ?>>Inactive</option>
                    </select>
                </div>
            </div>

            <!-- Description -->
            <div class="form-group">
                <label class="form-label">Description</label>
                <textarea name="description" rows="2" class="form-control"><?= htmlspecialchars($camp['description']) ?></textarea>
            </div>

            <div class="hr"></div>

            <!-- Campaign Type: one type only -->
            <label class="form-label">Campaign Type</label>
            <input type="hidden" name="type_whatsapp" id="type_whatsapp_val" value="<?= !empty($camp['type_whatsapp']) ? '1' : '0' ?>">
            <input type="hidden" name="type_email" id="type_email_val" value="<?= !empty($camp['type_email']) ? '1' : '0' ?>">
            <input type="hidden" name="type_sms" id="type_sms_val" value="<?= !empty($camp['type_sms']) ? '1' : '0' ?>">

            <div class="campaign-type-picker">
                <label class="campaign-type-card">
                    <input type="radio" name="campaign_type_single" value="wa" <?= $initialTab === 'wa' ? 'checked' : '' ?> onchange="selectCampaignType('wa')">
                    <span class="type-icon">💬</span>
                    <span>WhatsApp</span>
                </label>

                <label class="campaign-type-card">
                    <input type="radio" name="campaign_type_single" value="email" <?= $initialTab === 'email' ? 'checked' : '' ?> onchange="selectCampaignType('email')">
                    <span class="type-icon">✉️</span>
                    <span>Email</span>
                </label>

                <label class="campaign-type-card">
                    <input type="radio" name="campaign_type_single" value="sms" <?= $initialTab === 'sms' ? 'checked' : '' ?> onchange="selectCampaignType('sms')">
                    <span class="type-icon">📱</span>
                    <span>SMS</span>
                </label>
            </div>

            <!-- Message Box -->
            <div id="messageTabs" class="message-panel">
                <div id="msg-wa" class="msg-box" style="display:none">
                    <label class="form-label">WhatsApp Message <span class="text-danger">*</span></label>
                    <textarea name="message_whatsapp" class="form-control" rows="4"
                              id="ta_wa"
                              placeholder="Enter WhatsApp message..."><?= htmlspecialchars($camp['message_whatsapp']) ?></textarea>
                    <div class="campaign-media-box">
                        <label class="form-label">WhatsApp Image <span class="text-xs text-muted">optional</span></label>
                        <label class="media-upload-drop" for="campaignMediaInput">
                            <input type="file" id="campaignMediaInput" name="media" accept="image/*" onchange="previewCampaignMedia(this)" hidden>
                            <div class="media-upload-icon">🖼️</div>
                            <div class="media-upload-text">
                                <strong>Click to upload image</strong>
                                <span>JPG, PNG, GIF, WEBP up to 5MB</span>
                            </div>
                        </label>
                        <div id="campaignMediaPreview" class="campaign-media-preview" <?= empty($camp['media_url']) ? 'style="display:none"' : '' ?>>
                            <img id="campaignMediaImg" src="<?= htmlspecialchars($camp['media_url'] ?? '') ?>" alt="Campaign image">
                            <span id="campaignMediaName" class="text-xs text-muted"><?= !empty($camp['media_url']) ? 'Current campaign image' : '' ?></span>
                        </div>
                    </div>
                </div>

                <div id="msg-email" class="msg-box" style="display:none">
                    <div class="form-group">
                        <label class="form-label">Email Subject</label>
                        <input name="email_subject" class="form-control"
                               value="<?= htmlspecialchars($camp['email_subject'] ?? '') ?>"
                               placeholder="Email subject line...">
                    </div>
                    <label class="form-label">Email Message <span class="text-danger">*</span></label>
                    <textarea name="message_email" class="form-control" rows="5"
                              id="ta_email"
                              placeholder="Enter email body..."><?= htmlspecialchars($camp['message_email']) ?></textarea>
                </div>

                <div id="msg-sms" class="msg-box" style="display:none">
                    <label class="form-label">SMS Message <span class="text-danger">*</span></label>
                    <textarea name="message_sms" class="form-control" rows="3"
                              id="ta_sms"
                              placeholder="Enter SMS message..."><?= htmlspecialchars($camp['message_sms']) ?></textarea>
                </div>
            </div>

            <div class="hr"></div>

            <!-- Target -->
            <label class="form-label">Target</label>
            <div class="type-boxes" style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px">
                <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
                    <input type="radio" name="target_type" value="audience"
                           <?= ($camp['target_type'] ?? 'audience') === 'audience' ? 'checked' : '' ?>
                           onchange="toggleTarget()">
                    Saved Audience
                </label>
                <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
                    <input type="radio" name="target_type" value="dynamic"
                           <?= ($camp['target_type'] ?? 'audience') === 'dynamic' ? 'checked' : '' ?>
                           onchange="toggleTarget()">
                    Dynamic Filter
                </label>
            </div>

            <!-- Audience Selection -->
            <div id="audienceTarget">
                <div class="form-group">
                    <label class="form-label">Select Audience</label>
                    <select name="audience_id" class="form-control" onchange="loadAudienceCount(this.value)">
                        <option value="0">— Select Audience —</option>
                        <?php while ($a = $audiences->fetch_assoc()): ?>
                            <option value="<?= $a['id'] ?>"
                                <?= (int)$camp['audience_id'] == (int)$a['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($a['name']) ?>
                            </option>
                        <?php endwhile; ?>
                    </select><div id="audienceCountBox" class="text-xs text-muted" style="margin-top:8px">Select audience to see customer count.</div><div id="campaignAudiencePreview" style="margin-top:10px"></div>
                </div>
            </div>

            <!-- Dynamic Filters -->
            <div id="dynamicTarget" style="display:none">
                <div class="dynamic-filter-title">
                    <h4>Dynamic Filters</h4>
                    <span>Choose who should receive this campaign</span>
                </div>
                <div class="filter-accordion">

                    <div class="filter-card">
                        <button type="button" class="filter-head" onclick="toggleFilterBox(this)">
                            <span>🌍 By Country</span><small>Open countries</small>
                        </button>
                        <div class="filter-body">
                            <div class="check-list">
                                <?php while ($r = $countries->fetch_assoc()): ?>
                                    <label>
                                        <input type="checkbox" name="country_ids[]" value="<?= $r['id'] ?>" <?= cin($rules['country_ids'] ?? [], $r['id']) ?>>
                                        <?= htmlspecialchars($r['name']) ?>
                                    </label>
                                <?php endwhile; ?>
                            </div>
                        </div>
                    </div>

                    <div class="filter-card">
                        <button type="button" class="filter-head" onclick="toggleFilterBox(this)">
                            <span>⭐ By Priority</span><small>1 to 5 stars</small>
                        </button>
                        <div class="filter-body">
                            <div class="check-list">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <label>
                                        <input type="checkbox" name="priority[]" value="<?= $i ?>" <?= cin($rules['priority'] ?? [], $i) ?>>
                                        <?= str_repeat('★', $i) ?>
                                    </label>
                                <?php endfor; ?>
                            </div>
                        </div>
                    </div>



                    <div class="filter-card">
                        <button type="button" class="filter-head" onclick="toggleFilterBox(this)">
                            <span>🧭 By Source</span><small>Google Ads / Social / Other</small>
                        </button>
                        <div class="filter-body">
                            <div class="check-list">
                                <?php if ($sources): while ($r = $sources->fetch_assoc()): ?>
                                    <label>
                                        <input type="checkbox" name="source_ids[]" value="<?= $r['id'] ?>" <?= cin($rules['source_ids'] ?? [], $r['id']) ?>>
                                        <?= htmlspecialchars($r['name']) ?>
                                    </label>
                                <?php endwhile; else: ?>
                                    <span class="text-muted text-xs">No sources found.</span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <div class="filter-card">
                        <button type="button" class="filter-head" onclick="toggleFilterBox(this)">
                            <span>🏷️ By Labels</span><small>Filter by label</small>
                        </button>
                        <div class="filter-body">
                            <div class="check-list">
                                <?php while ($r = $labels->fetch_assoc()): ?>
                                    <label>
                                        <input type="checkbox" name="label_ids[]" value="<?= $r['id'] ?>" <?= cin($rules['label_ids'] ?? [], $r['id']) ?>>
                                        <span class="label-dot" style="background:<?= htmlspecialchars($r['color']) ?>"></span>
                                        <?= htmlspecialchars($r['name']) ?>
                                    </label>
                                <?php endwhile; ?>
                            </div>
                        </div>
                    </div>

                    <div class="filter-card">
                        <button type="button" class="filter-head" onclick="toggleFilterBox(this)">
                            <span>📌 By Leads / Items</span><small>Open leads filters</small>
                        </button>
                        <div class="filter-body">
                            <div class="check-list">
                                <label>
                                    <input type="checkbox" name="has_leads" value="1" <?= !empty($rules['has_leads']) ? 'checked' : '' ?>>
                                    Has leads
                                </label>
                            </div>
                            <label class="form-label" style="margin-top:12px">Lead Items</label>
                            <div class="check-list">
                                <?php while ($r = $items->fetch_assoc()): ?>
                                    <label>
                                        <input type="checkbox" name="item_ids[]" value="<?= $r['id'] ?>" <?= cin($rules['item_ids'] ?? [], $r['id']) ?>>
                                        <?= htmlspecialchars($r['name']) ?>
                                    </label>
                                <?php endwhile; ?>
                            </div>
                        </div>
                    </div>

                    <div class="filter-card">
                        <button type="button" class="filter-head" onclick="toggleFilterBox(this)">
                            <span>👥 Pick Customers Manually</span><small>Specific recipients</small>
                        </button>
                        <div class="filter-body">
                            <input type="text" class="form-control" placeholder="Search customer..."
                                   oninput="filterManualCustomers(this.value)" style="margin-bottom:10px">
                            <div class="check-list manual-customers" id="manualCustomersList">
                                <?php while ($r = $manualCustomers->fetch_assoc()): ?>
                                    <label data-text="<?= strtolower(htmlspecialchars($r['customer_name'] . ' ' . $r['business_name'] . ' ' . $r['phone'])) ?>">
                                        <input type="checkbox" name="customer_ids[]" value="<?= $r['id'] ?>" <?= cin($rules['customer_ids'] ?? [], $r['id']) ?>>
                                        <strong><?= htmlspecialchars($r['customer_name']) ?></strong>
                                        <span class="text-muted text-xs"><?= htmlspecialchars($r['business_name'] ?: $r['phone'] ?: '') ?></span>
                                    </label>
                                <?php endwhile; ?>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <div class="hr"></div>

            <!-- Action Buttons -->
            <div class="d-flex gap-8" style="flex-wrap:wrap">
                
                <button type="button" class="btn btn-secondary" onclick="saveCampaign(false)">Save Only</button>
                <button type="button" class="btn btn-primary"   onclick="saveCampaign(true)">Create & Send Now</button>
            </div>

            <div class="text-xs text-muted" style="margin-top:8px">
                "Create & Send Now" saves the campaign then sends to all selected recipients via the chosen channels.
            </div>

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

<style>
.campaign-form-page .card{border-radius:18px;box-shadow:0 8px 28px rgba(15,23,42,.06);}
.campaign-type-picker{display:grid;grid-template-columns:repeat(3,minmax(140px,1fr));gap:12px;margin:8px 0 18px;}
.campaign-type-card{position:relative;display:flex;align-items:center;gap:10px;padding:14px 16px;border:1px solid #dce6f2;border-radius:14px;background:#fff;cursor:pointer;font-weight:700;color:#0f1f3d;transition:.18s ease;}
.campaign-type-card:hover{border-color:#2563eb;box-shadow:0 8px 22px rgba(37,99,235,.10);transform:translateY(-1px);}
.campaign-type-card input{position:absolute;opacity:0;pointer-events:none;}
.campaign-type-card:has(input:checked){background:linear-gradient(135deg,#2563eb,#1e3a8a);border-color:#2563eb;color:#fff;box-shadow:0 12px 28px rgba(37,99,235,.22);}
.type-icon{width:36px;height:36px;border-radius:12px;display:flex;align-items:center;justify-content:center;background:#eef4ff;font-size:18px;transition:.18s ease;}
.campaign-type-card:has(input:checked) .type-icon{background:rgba(255,255,255,.18);}
.message-panel{background:#f8fbff;border:1px solid #e3ecf8;border-radius:16px;padding:16px;margin-bottom:20px;}
.msg-box{animation:fadeMsg .18s ease;}
@keyframes fadeMsg{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
.dynamic-filter-title{display:flex;align-items:end;justify-content:space-between;gap:12px;margin:4px 0 12px;}
.dynamic-filter-title h4{margin:0;color:#0f1f3d;font-size:18px;}
.dynamic-filter-title span{font-size:12px;color:#7690b2;}
.filter-accordion{display:grid;gap:10px;}
.filter-card{border:1px solid #e0e9f5;border-radius:14px;background:#fff;overflow:hidden;box-shadow:0 4px 14px rgba(15,23,42,.035);}
.filter-head{width:100%;border:0;background:#fff;padding:14px 16px;display:flex;align-items:center;justify-content:space-between;gap:12px;cursor:pointer;text-align:left;font-weight:800;color:#0f1f3d;transition:.15s ease;}
.filter-head:hover{background:#f7faff;}
.filter-head span{display:flex;align-items:center;gap:8px;font-size:14px;}
.filter-head small{font-size:12px;color:#7d95b8;font-weight:600;}
.filter-head::after{content:'+';width:24px;height:24px;border-radius:999px;background:#edf4ff;color:#2563eb;display:flex;align-items:center;justify-content:center;font-weight:900;margin-left:auto;}
.filter-card.open .filter-head{background:#f7faff;}
.filter-card.open .filter-head::after{content:'−';}
.filter-card .filter-body{display:none;padding:0 16px 16px;border-top:1px solid #eef3f9;}
.filter-card.open .filter-body{display:block;}
.check-list{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;max-height:260px;overflow-y:auto;padding-top:12px;}
.check-list label{display:flex;align-items:center;gap:8px;font-size:13px;padding:9px 10px;border:1px solid #edf2f8;border-radius:10px;background:#fbfdff;cursor:pointer;}
.check-list label:hover{border-color:#bcd0ea;background:#f6faff;}
.manual-customers{grid-template-columns:repeat(auto-fill,minmax(240px,1fr));}
.label-dot{width:10px;height:10px;border-radius:50%;display:inline-block;flex-shrink:0;}
.campaign-media-box{margin-top:12px;}
.media-upload-drop{display:flex;align-items:center;gap:14px;padding:16px;border:1.5px dashed #cfdcf0;border-radius:14px;background:#fff;cursor:pointer;transition:.15s ease;}
.media-upload-drop:hover{border-color:#2563eb;background:#f7fbff;}
.media-upload-icon{font-size:28px;width:44px;height:44px;border-radius:12px;background:#eef4ff;display:flex;align-items:center;justify-content:center;}
.media-upload-text{display:flex;flex-direction:column;gap:3px;}
.media-upload-text span{font-size:12px;color:#8299bc;}
.campaign-media-preview{display:flex;align-items:center;gap:12px;margin-top:12px;padding:10px;border:1px solid #e3ecf8;border-radius:14px;background:#fff;}
.campaign-media-preview img{width:86px;height:86px;object-fit:cover;border-radius:12px;border:1px solid #e0e9f5;}
@media(max-width:700px){.campaign-type-picker{grid-template-columns:1fr}.dynamic-filter-title{display:block}.check-list{grid-template-columns:1fr}}
</style>

<script src="https://cdn.ckeditor.com/ckeditor5/41.4.2/classic/ckeditor.js"></script>
<script>
let emailEditor=null;
if (window.ClassicEditor) { ClassicEditor.create(document.querySelector('#ta_email')).then(ed=>{ emailEditor=ed; }).catch(()=>{}); }
async function loadAudienceCount(id){
  const box=document.getElementById('audienceCountBox'); const prev=document.getElementById('campaignAudiencePreview');
  if(!id || parseInt(id)<=0){ if(box) box.textContent='Select audience to see customer count.'; if(prev) prev.innerHTML=''; return; }
  const fd=new FormData(document.getElementById('campaignForm')); fd.set('action','preview'); fd.set('target_type','audience'); fd.set('audience_id',id);
  const r=await apiCall('handlers/campaigns.php',fd);
  if(box) box.innerHTML=r.success?('<strong>'+r.count+'</strong> customers in this audience'):(r.message||'Error');
  if(prev) prev.innerHTML=r.success?('<a class="btn btn-secondary btn-sm" target="_blank" href="index.php?page=audience_view&id='+encodeURIComponent(id)+'">View audience customers</a>'):'';
}

function previewCampaignMedia(input) {
    const box = document.getElementById('campaignMediaPreview');
    const img = document.getElementById('campaignMediaImg');
    const name = document.getElementById('campaignMediaName');
    const file = input.files && input.files[0];
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) { showToast('Image is too large. Max 5MB','error'); input.value=''; return; }
    img.src = URL.createObjectURL(file);
    name.textContent = file.name;
    box.style.display = 'flex';
}

function selectCampaignType(type) {
    document.getElementById('type_whatsapp_val').value = type === 'wa' ? '1' : '0';
    document.getElementById('type_email_val').value = type === 'email' ? '1' : '0';
    document.getElementById('type_sms_val').value = type === 'sms' ? '1' : '0';

    ['wa','email','sms'].forEach(id => {
        const box = document.getElementById('msg-' + id);
        if (box) box.style.display = id === type ? 'block' : 'none';
    });
}

function toggleTarget() {
    const t = document.querySelector('input[name="target_type"]:checked').value;
    document.getElementById('audienceTarget').style.display  = t === 'audience' ? 'block' : 'none';
    document.getElementById('dynamicTarget').style.display   = t === 'dynamic'  ? 'block' : 'none';
}

function toggleFilterBox(btn) {
    btn.closest('.filter-card').classList.toggle('open');
}

function filterManualCustomers(q) {
    q = (q || '').toLowerCase();
    document.querySelectorAll('#manualCustomersList label').forEach(l => {
        l.style.display = (!q || (l.dataset.text || '').includes(q)) ? 'flex' : 'none';
    });
}

async function previewCampaign() {
    const fd = new FormData(document.getElementById('campaignForm'));
    fd.set('action', 'preview');
    const r = await apiCall('handlers/campaigns.php', fd);
    document.getElementById('campaignPreview').innerHTML = r.success
        ? `<div class="alert alert-info"><strong>${r.count}</strong> recipients found</div>` + (r.html || '')
        : `<div class="alert alert-error">${r.message || 'Error'}</div>`;
}

async function saveCampaign(sendNow = false) {
    const selected = document.querySelector('input[name="campaign_type_single"]:checked')?.value || 'wa';
    selectCampaignType(selected);

    const map = {
        wa: { ta: 'ta_wa', label: 'WhatsApp' },
        email: { ta: 'ta_email', label: 'Email' },
        sms: { ta: 'ta_sms', label: 'SMS' }
    };
    const current = map[selected];
    const form = document.getElementById('campaignForm');
    if (emailEditor) {
        form.querySelector('[name="message_email"]').value = emailEditor.getData();
    }
    const taEl = document.getElementById(current.ta);
    const currentValue = selected === 'email' && emailEditor ? emailEditor.getData().replace(/<[^>]*>/g, '').trim() : (taEl ? taEl.value.trim() : '');
    if (!currentValue) {
        if (taEl) taEl.focus();
        showToast(`${current.label} message cannot be empty`, 'error');
        return;
    }

    const targetType = form.querySelector('input[name="target_type"]:checked')?.value || 'audience';
    if (targetType === 'audience') {
        const audienceId = parseInt(form.querySelector('[name="audience_id"]')?.value || '0', 10);
        if (!audienceId) { showToast('Select an audience before saving campaign', 'error'); return; }
    } else {
        const hasDynamic = form.querySelectorAll('#dynamicTarget input[type="checkbox"]:checked').length > 0;
        if (!hasDynamic) { showToast('Choose at least one dynamic filter/customer before saving campaign', 'error'); return; }
    }

    if (emailEditor) { form.querySelector('[name="message_email"]').value = emailEditor.getData(); }
    const fd = new FormData(form);
    fd.set('action', 'save');
    const r = await apiCall('handlers/campaigns.php', fd);

    if (!r.success) {
        showToast(r.message || 'Error saving campaign', 'error');
        return;
    }

    if (!sendNow) {
        showToast('Campaign saved', 'success');
        setTimeout(() => location.href = 'index.php?page=campaign_view&id=' + r.id, 700);
        return;
    }

    showToast('Campaign saved. Sending now…', 'info');
    const sr = await apiCall('handlers/campaigns.php', { action: 'send', id: r.id });

    if (sr.success) {
        let msg = `Sent: ${sr.sent} / Failed: ${sr.failed}`;
        if (sr.failed > 0 && sr.errors && sr.errors.length) {
            msg += '<br><small>' + sr.errors.slice(0, 5).join('<br>') + '</small>';
        }
        showToast(msg, sr.failed > 0 ? 'warning' : 'success');
    } else {
        showToast(sr.message || 'Sending failed', 'error');
    }
}

(function init() {
    toggleTarget();
    const initialTab = <?= json_encode($initialTab) ?>;
    selectCampaignType(initialTab || 'wa');
    const audSel=document.querySelector('[name="audience_id"]'); if(audSel && audSel.value && parseInt(audSel.value)>0) loadAudienceCount(audSel.value);
})();
</script>
