<?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'     => '',
];

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();
    } 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");
$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">
            <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  +  MESSAGE TABS  (linked together)
                 ══════════════════════════════════════════════════ -->
            <label class="form-label">Campaign Type</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="checkbox" name="type_whatsapp" value="1"
                           id="chk_wa"
                           <?= !empty($camp['type_whatsapp']) ? 'checked' : '' ?>
                           onchange="syncTypeTab('wa', this.checked)">
                    💬 WhatsApp
                </label>

                <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
                    <input type="checkbox" name="type_email" value="1"
                           id="chk_email"
                           <?= !empty($camp['type_email']) ? 'checked' : '' ?>
                           onchange="syncTypeTab('email', this.checked)">
                    ✉️ Email
                </label>

                <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
                    <input type="checkbox" name="type_sms" value="1"
                           id="chk_sms"
                           <?= !empty($camp['type_sms']) ? 'checked' : '' ?>
                           onchange="syncTypeTab('sms', this.checked)">
                    📱 SMS
                </label>

            </div>

            <!-- Message Tabs (only enabled types shown) -->
            <div id="messageTabs">
                <div class="message-tabs" id="msgTabBtns" style="display:flex;gap:4px;margin-bottom:12px;flex-wrap:wrap"></div>

                <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>

                <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 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>

            <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">
                        <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>
            </div>

            <!-- Dynamic Filters -->
            <div id="dynamicTarget" style="display:none">
                <h4>Dynamic Filters</h4>
                <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 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="previewCampaign()">Preview Recipients</button>
                <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>

            <div id="campaignPreview" style="margin-top:16px"></div>
        </form>
    </div>
</div>

<style>
.msg-tab {
    padding: 6px 16px;
    border: 1px solid var(--border-color, #ddd);
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
    font-size: 13px;
    transition: background .15s, color .15s;
}
.msg-tab.active {
    background: var(--primary, #2563eb);
    color: #fff;
    border-color: transparent;
}
.msg-tab:disabled {
    opacity: .35;
    cursor: not-allowed;
}
.filter-card .filter-body { display: none; padding: 10px 0; }
.filter-card.open .filter-body { display: block; }
.check-list { display: flex; flex-direction: column; gap: 6px; max-height: 220px; overflow-y: auto; }
.check-list label { display: flex; align-items: center; gap: 8px; font-size: 13px; }
.label-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; flex-shrink: 0; }
</style>

<script>
// ─── tab/type synchronisation ───────────────────────────────
// Map: tab id → { checkbox id, label }
const TYPE_MAP = {
    wa:    { chk: 'chk_wa',    label: '💬 WhatsApp' },
    email: { chk: 'chk_email', label: '✉️ Email'    },
    sms:   { chk: 'chk_sms',   label: '📱 SMS'      },
};

/** Rebuild the tab bar based on currently-checked type checkboxes */
function rebuildTabs() {
    const bar = document.getElementById('msgTabBtns');
    bar.innerHTML = '';

    let firstEnabled = null;
    let currentTabVisible = false;

    for (const [tabId, meta] of Object.entries(TYPE_MAP)) {
        const chk = document.getElementById(meta.chk);
        if (!chk || !chk.checked) {
            // hide the message panel if this type is unchecked
            document.getElementById('msg-' + tabId).style.display = 'none';
            continue;
        }

        if (!firstEnabled) firstEnabled = tabId;

        const btn = document.createElement('button');
        btn.type      = 'button';
        btn.className = 'msg-tab';
        btn.dataset.tab = tabId;
        btn.textContent = meta.label;
        btn.onclick = () => showMsgTab(tabId);
        bar.appendChild(btn);

        // check if previously active tab is still enabled
        const panel = document.getElementById('msg-' + tabId);
        if (panel.style.display !== 'none') currentTabVisible = true;
    }

    // If currently visible tab was disabled, switch to first available
    if (!currentTabVisible && firstEnabled) {
        showMsgTab(firstEnabled);
    } else if (firstEnabled) {
        // re-activate the correct tab button
        const active = [...bar.querySelectorAll('.msg-tab')]
            .find(b => document.getElementById('msg-' + b.dataset.tab)?.style.display !== 'none');
        if (active) active.classList.add('active');
    }

    // Hide the whole tabs section if nothing enabled
    document.getElementById('messageTabs').style.display = firstEnabled ? 'block' : 'none';
}

/** Show a specific message tab */
function showMsgTab(tabId) {
    for (const id of Object.keys(TYPE_MAP)) {
        document.getElementById('msg-' + id).style.display = 'none';
    }
    const panel = document.getElementById('msg-' + tabId);
    if (panel) panel.style.display = 'block';

    document.querySelectorAll('#msgTabBtns .msg-tab').forEach(b => {
        b.classList.toggle('active', b.dataset.tab === tabId);
    });
}

/** Called when a type checkbox changes */
function syncTypeTab(tabId, checked) {
    rebuildTabs();
    if (checked) showMsgTab(tabId);
}

// ─── target toggle ───────────────────────────────────────────
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';
    });
}

// ─── api calls ───────────────────────────────────────────────
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) {
    // Client-side validation: each checked type must have a message
    const checks = [
        { chk: 'chk_wa',    ta: 'ta_wa',    label: 'WhatsApp' },
        { chk: 'chk_email', ta: 'ta_email',  label: 'Email'    },
        { chk: 'chk_sms',   ta: 'ta_sms',   label: 'SMS'      },
    ];
    for (const c of checks) {
        const chkEl = document.getElementById(c.chk);
        const taEl  = document.getElementById(c.ta);
        if (chkEl && chkEl.checked && taEl && !taEl.value.trim()) {
            showMsgTab(c.chk.replace('chk_', '').replace('chk_wa', 'wa').replace('chk_', ''));
            // simpler: derive tab from chk id
            const tabId = c.chk === 'chk_wa' ? 'wa' : c.chk === 'chk_email' ? 'email' : 'sms';
            showMsgTab(tabId);
            taEl.focus();
            showToast(`${c.label} message cannot be empty`, 'error');
            return;
        }
    }

    const fd = new FormData(document.getElementById('campaignForm'));
    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');
    }
}

// ─── init ────────────────────────────────────────────────────
(function init() {
    toggleTarget();
    rebuildTabs();
    // activate the right tab based on saved data
    const initialTab = <?= json_encode($initialTab) ?>;
    if (document.getElementById('chk_' + initialTab)?.checked) {
        showMsgTab(initialTab);
    }
})();
</script>