<?php
require_once __DIR__ . '/../lib/audience_rules.php';
$id=(int)($_GET['id']??0);$q=$conn->query("SELECT * FROM audience WHERE id=$id AND account_id=$account_id LIMIT 1");if(!$q||!$q->num_rows){echo '<div class="alert alert-error">Audience not found</div>';return;}$aud=$q->fetch_assoc();$rules=crm_decode_rules($aud['rules_json']??'');$count=crm_count_customers_by_rules($conn,$account_id,$rules);$customers=crm_get_customers_by_rules($conn,$account_id,$rules,200,0);
?>
<div class="fade-in"><div class="toolbar"><a href="index.php?page=audience" class="btn btn-secondary">← Back</a><a href="index.php?page=audience_edit&id=<?= $id ?>" class="btn btn-primary">Edit</a><button class="btn btn-secondary" onclick="refreshAudience(<?= $id ?>)">Refresh Stored List</button></div><div class="card" style="padding:20px;margin-bottom:16px"><h3 style="margin-top:0"><?= htmlspecialchars($aud['name']) ?></h3><p class="text-muted"><?= htmlspecialchars($aud['description']?:'') ?></p><strong><?= $count ?></strong> live customers match this audience.</div><div class="card"><div class="table-wrapper"><table class="crm-table"><thead><tr><th>Customer</th><th>Business</th><th>Phone</th><th>Email</th><th>Country</th><th>Priority</th></tr></thead><tbody><?php while($c=$customers->fetch_assoc()): ?><tr><td><?= htmlspecialchars($c['customer_name']) ?></td><td><?= htmlspecialchars($c['business_name']?:'—') ?></td><td><?= htmlspecialchars($c['phone']?:'—') ?></td><td><?= htmlspecialchars($c['email']?:'—') ?></td><td><?= htmlspecialchars($c['country_name']?:'—') ?></td><td><?= renderStars($c['priority']) ?></td></tr><?php endwhile; ?></tbody></table></div></div></div><script>async function refreshAudience(id){const r=await apiCall('handlers/audience.php',{action:'refresh',id});if(r.success)showToast('Refreshed '+r.count+' customers','success');else showToast(r.message||'Error','error')}</script>
