<?php
require_once __DIR__ . '/../lib/audience_rules.php';
$limit = defined('CRM_ROWS_PER_PAGE') ? CRM_ROWS_PER_PAGE : 30;
$page_num = max(1, (int)($_GET['page_num'] ?? 1));
$offset = ($page_num - 1) * $limit;
$search = sanitize($conn, $_GET['search'] ?? '');
$return_to = urlencode($_SERVER['REQUEST_URI'] ?? 'index.php?page=audience');
$where = "(a.account_id=$account_id OR a.account_id IS NULL)";
if ($search) $where .= " AND (a.name LIKE '%$search%' OR a.description LIKE '%$search%')";
$total_q = $conn->query("SELECT COUNT(*) cnt FROM audience a WHERE $where");
$total_rows = $total_q ? (int)$total_q->fetch_assoc()['cnt'] : 0;
$total_pages = max(1, ceil($total_rows / $limit));
$list = $conn->query("SELECT a.*, u.name creator_name, (SELECT COUNT(*) FROM audience_customers ac WHERE ac.audience_id=a.id) stored_count FROM audience a LEFT JOIN users u ON u.id=a.added_by WHERE $where ORDER BY a.date_created DESC LIMIT $offset,$limit");
function audienceRuleSummary($rules){
  $parts=[]; if(!empty($rules['country_ids']))$parts[]='Countries: '.count($rules['country_ids']); if(!empty($rules['priority']))$parts[]='Priority: '.implode(',',$rules['priority']); if(!empty($rules['label_ids']))$parts[]='Labels: '.count($rules['label_ids']); if(!empty($rules['has_leads']))$parts[]='Has Leads'; if(!empty($rules['item_ids']))$parts[]='Items: '.count($rules['item_ids']); return $parts?implode(' · ',$parts):'Manual / no rules';
}
?>
<div class="fade-in">
  <div class="toolbar" style="justify-content:space-between;gap:12px;flex-wrap:wrap;">
    <div class="search-wrap" style="flex:1;min-width:240px;"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg><input id="audienceSearch" value="<?= htmlspecialchars($search) ?>" placeholder="Search audiences..."></div>
    <a class="btn btn-primary" data-permission="add" href="index.php?page=audience_add">+ New Audience</a>
  </div>
  <div class="card"><div class="table-wrapper"><table class="crm-table"><thead><tr><th>Name</th><th>Rules</th><th>Stored Members</th><th>Live Match</th><th>Status</th><th>Date</th><th>Added By</th><th>Actions</th></tr></thead><tbody>
  <?php if(!$list || $list->num_rows===0): ?><tr><td colspan="8" class="text-center text-muted" style="padding:40px">No audiences found</td></tr><?php else: while($a=$list->fetch_assoc()): $rules=crm_decode_rules($a['rules_json'] ?? ''); $live=crm_count_customers_by_rules($conn,$account_id,$rules); ?>
    <tr><td><strong><?= htmlspecialchars($a['name']) ?></strong><div class="text-xs text-muted"><?= htmlspecialchars($a['description'] ?: '') ?></div></td><td><?= htmlspecialchars(audienceRuleSummary($rules)) ?></td><td><span class="badge badge-blue"><?= (int)$a['stored_count'] ?></span></td><td><span class="badge badge-green"><?= $live ?></span></td><td><span class="badge badge-<?= (int)$a['statuss']?'green':'gray' ?>"><?= (int)$a['statuss']?'Active':'Inactive' ?></span></td><td class="text-xs text-muted"><?= formatDate($a['date_created']) ?></td><td><?= htmlspecialchars($a['creator_name'] ?: '—') ?></td><td><div class="d-flex gap-8"><a class="btn btn-secondary btn-sm" href="index.php?page=audience_view&id=<?= crmEid($a['id']) ?>">View</a><a class="btn btn-secondary btn-sm" data-permission="edit" href="index.php?page=audience_edit&id=<?= crmEid($a['id']) ?>&return_to=<?= $return_to ?>">Edit</a><button class="btn btn-primary btn-sm" onclick="updateAudience('<?= crmEid($a['id']) ?>')">Update Audience</button></div></td></tr>
  <?php endwhile; endif; ?></tbody></table></div><div class="pagination" style="display:flex;align-items:center;justify-content:space-between;gap:10px;padding:16px 20px;border-top:1px solid var(--border);"><div class="text-xs text-muted">Showing <?= $total_rows?($offset+1):0 ?> – <?= min($offset+$limit,$total_rows) ?> of <?= $total_rows ?> audiences</div><div><?php for($i=1;$i<=$total_pages;$i++): ?><a class="btn btn-<?= $i==$page_num?'primary':'secondary' ?> btn-sm" href="?page=audience&page_num=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a> <?php endfor; ?></div></div></div>
</div>
<script>
document.getElementById('audienceSearch').addEventListener('keydown',e=>{if(e.key==='Enter'){location.href='?page=audience&search='+encodeURIComponent(e.target.value)}});
async function updateAudience(id){const p=await apiCall('handlers/audience.php',{action:'preview_update',id}); if(!p.success){showToast(p.message||'Error','error');return;} const n=parseInt(p.new_count||0); if(n<=0){showToast('No new customers to add','success');return;} confirmAction(n+' new customers found. Add them to this audience?',async()=>{const r=await apiCall('handlers/audience.php',{action:'add_new',id}); if(r.success){showToast('Audience updated: '+(r.added||0)+' added','success'); setTimeout(()=>location.reload(),500)}else showToast(r.message||'Error','error')});}
async function deleteAudience(id){confirmAction('Delete this audience?',async()=>{const r=await apiCall('handlers/audience.php',{action:'delete',id}); if(r.success) location.reload(); else showToast(r.message||'Error','error')})}
</script>
