<?php
require_once __DIR__ . '/../lib/audience_rules.php';
$isEdit = ($_GET['page'] ?? '') === 'audience_edit';
$id = (int)($_GET['id'] ?? 0);
$aud = ['name'=>'','description'=>'','statuss'=>1,'rules_json'=>''];
if ($isEdit) { $q=$conn->query("SELECT * FROM audience WHERE id=$id AND account_id=$account_id LIMIT 1"); if($q&&$q->num_rows)$aud=$q->fetch_assoc(); else { echo '<div class="alert alert-error">Audience not found</div>'; return; } }
$rules = crm_decode_rules($aud['rules_json'] ?? '');
$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 labels WHERE account_id=$account_id ORDER BY name");
$items=$conn->query("SELECT id,name FROM items WHERE account_id=$account_id ORDER BY name");
function checkedIn($arr,$id){ return in_array((int)$id, array_map('intval',$arr??[])) ? 'checked' : ''; }
?>
<div class="fade-in"><div class="toolbar"><a href="index.php?page=audience" class="btn btn-secondary">← Back</a></div><div class="card" style="padding:20px;max-width:980px;"><h3 style="margin-top:0"><?= $isEdit?'Edit':'Add' ?> Audience</h3><form id="audienceForm"><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">Audience Name *</label><input name="name" required class="form-control" value="<?= htmlspecialchars($aud['name']) ?>"></div><div class="form-group"><label class="form-label">Status</label><select name="statuss" class="form-control"><option value="1" <?= (int)$aud['statuss']?'selected':'' ?>>Active</option><option value="0" <?= !(int)$aud['statuss']?'selected':'' ?>>Inactive</option></select></div></div><div class="form-group"><label class="form-label">Description</label><textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($aud['description']) ?></textarea></div><div class="hr"></div><h4>Audience Rules</h4><div class="form-grid"><div><label class="form-label">Countries</label><div class="check-list"><?php while($r=$countries->fetch_assoc()): ?><label><input type="checkbox" name="country_ids[]" value="<?= $r['id'] ?>" <?= checkedIn($rules['country_ids']??[],$r['id']) ?>> <?= htmlspecialchars($r['name']) ?></label><?php endwhile; ?></div></div><div><label class="form-label">Priority</label><div class="check-list"><?php for($i=1;$i<=5;$i++): ?><label><input type="checkbox" name="priority[]" value="<?= $i ?>" <?= checkedIn($rules['priority']??[],$i) ?>> <?= str_repeat('★',$i) ?></label><?php endfor; ?></div></div><div><label class="form-label">Labels</label><div class="check-list"><?php while($r=$labels->fetch_assoc()): ?><label><input type="checkbox" name="label_ids[]" value="<?= $r['id'] ?>" <?= checkedIn($rules['label_ids']??[],$r['id']) ?>> <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:<?= htmlspecialchars($r['color']) ?>"></span> <?= htmlspecialchars($r['name']) ?></label><?php endwhile; ?></div></div><div><label class="form-label">Lead Conditions</label><div class="check-list"><label><input type="checkbox" name="has_leads" value="1" <?= !empty($rules['has_leads'])?'checked':'' ?>> Customers who have 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'] ?>" <?= checkedIn($rules['item_ids']??[],$r['id']) ?>> <?= htmlspecialchars($r['name']) ?></label><?php endwhile; ?></div></div></div><div class="hr"></div><div class="d-flex gap-8"><button type="button" class="btn btn-secondary" onclick="previewAudience()">Preview Customers</button><button type="button" class="btn btn-primary" onclick="saveAudience()">Save Audience</button></div><div id="audiencePreview" style="margin-top:16px"></div></form></div></div><style>.check-list{display:grid;gap:8px;max-height:220px;overflow:auto;padding:10px;border:1px solid var(--border);border-radius:10px;background:var(--bg-base)}.check-list label{display:flex;gap:8px;align-items:center}</style><script>
async function previewAudience(){const fd=new FormData(document.getElementById('audienceForm'));fd.set('action','preview');const r=await apiCall('handlers/audience.php',fd);document.getElementById('audiencePreview').innerHTML=r.success?`<div class="alert alert-info"><strong>${r.count}</strong> customers match</div>`+(r.html||''):`<div class="alert alert-error">${r.message||'Error'}</div>`}
async function saveAudience(){const fd=new FormData(document.getElementById('audienceForm'));const r=await apiCall('handlers/audience.php',fd);if(r.success){showToast('Audience saved. '+r.count+' customers refreshed','success');setTimeout(()=>location.href='index.php?page=audience',700)}else showToast(r.message||'Error','error')}
</script>
