<?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':'';}
?>
<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 ?>"><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><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><label class="form-label">Campaign Type</label><div class="type-boxes"><label><input type="checkbox" name="type_whatsapp" value="1" <?= !empty($camp['type_whatsapp'])?'checked':'' ?>> 💬 WhatsApp</label><label><input type="checkbox" name="type_email" value="1" <?= !empty($camp['type_email'])?'checked':'' ?>> ✉️ Email</label><label><input type="checkbox" name="type_sms" value="1" <?= !empty($camp['type_sms'])?'checked':'' ?>> 📱 SMS</label></div><div class="hr"></div><label class="form-label">Target</label><div class="type-boxes"><label><input type="radio" name="target_type" value="audience" <?= ($camp['target_type']??'audience')==='audience'?'checked':'' ?> onchange="toggleTarget()"> Saved Audience</label><label><input type="radio" name="target_type" value="dynamic" <?= ($camp['target_type']??'audience')==='dynamic'?'checked':'' ?> onchange="toggleTarget()"> Dynamic Filter</label></div><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><div id="dynamicTarget"><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>Website/App/etc</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><h4>Messages</h4><div class="message-tabs"><button type="button" class="msg-tab active" onclick="showMsgTab('wa',this)">WhatsApp</button><button type="button" class="msg-tab" onclick="showMsgTab('sms',this)">SMS</button><button type="button" class="msg-tab" onclick="showMsgTab('email',this)">Email</button></div><div id="msg-wa" class="msg-box"><label class="form-label">WhatsApp Message</label><textarea name="message_whatsapp" class="form-control" rows="4"><?= htmlspecialchars($camp['message_whatsapp']) ?></textarea></div><div id="msg-sms" class="msg-box" style="display:none"><label class="form-label">SMS Message</label><textarea name="message_sms" class="form-control" rows="3"><?= 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']??'') ?>"></div><label class="form-label">Email Message</label><textarea name="message_email" class="form-control" rows="5"><?= htmlspecialchars($camp['message_email']) ?></textarea></div><div class="hr"></div><div class="d-flex gap-8"><button type="button" class="btn btn-secondary" onclick="previewCampaign()">Preview Recipients</button><button type="button" class="btn btn-primary" onclick="saveCampaign()">Save Campaign</button></div><div id="campaignPreview" style="margin-top:16px"></div></form></div></div>
<style>.type-boxes{display:flex;gap:10px;flex-wrap:wrap}.type-boxes label{padding:12px 16px;border:1px solid var(--border);border-radius:12px;background:var(--bg-base);cursor:pointer}.message-tabs{display:flex;gap:8px;margin-bottom:12px}.msg-tab{border:1px solid var(--border);background:white;border-radius:10px;padding:8px 14px;cursor:pointer}.msg-tab.active{background:var(--primary);color:white}.filter-accordion{display:grid;gap:12px}.filter-card{border:1px solid var(--border);border-radius:14px;background:var(--bg-base);overflow:hidden}.filter-head{width:100%;display:flex;justify-content:space-between;align-items:center;padding:14px 16px;border:0;background:white;cursor:pointer;font-weight:700;color:var(--text-primary)}.filter-head small{font-weight:400;color:var(--text-muted)}.filter-body{display:none;padding:14px 16px;border-top:1px solid var(--border)}.filter-card.open .filter-body{display:block}.check-list{display:grid;gap:8px;max-height:240px;overflow:auto;padding:10px;border:1px solid var(--border);border-radius:10px;background:white}.check-list label{display:flex;gap:8px;align-items:center}.label-dot{display:inline-block;width:10px;height:10px;border-radius:50%}</style>
<script>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'});}function showMsgTab(id,btn){document.querySelectorAll('.msg-box').forEach(x=>x.style.display='none');document.querySelectorAll('.msg-tab').forEach(x=>x.classList.remove('active'));document.getElementById('msg-'+id).style.display='block';btn.classList.add('active')}toggleTarget();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(){const fd=new FormData(document.getElementById('campaignForm'));const r=await apiCall('handlers/campaigns.php',fd);if(r.success){showToast('Campaign saved','success');setTimeout(()=>location.href='index.php?page=campaign_view&id='+r.id,700)}else showToast(r.message||'Error','error')}</script>
