<?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']??'');$where="c.account_id=$account_id";if($search)$where.=" AND (c.name LIKE '%$search%' OR c.description LIKE '%$search%')";$tq=$conn->query("SELECT COUNT(*) cnt FROM campaign c WHERE $where");$total_rows=$tq?(int)$tq->fetch_assoc()['cnt']:0;$total_pages=max(1,ceil($total_rows/$limit));
$list=$conn->query("SELECT c.*,u.name creator_name,a.name audience_name FROM campaign c LEFT JOIN users u ON u.id=c.added_by LEFT JOIN audience a ON a.id=c.audience_id WHERE $where ORDER BY c.date_created DESC LIMIT $offset,$limit");
?>
<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="campaignSearch" value="<?= htmlspecialchars($search) ?>" placeholder="Search campaigns..."></div> <a class="btn btn-primary" data-permission="add" href="index.php?page=campaign_add">+ New Campaign</a></div><div class="card"><div class="table-wrapper"><table class="crm-table"><thead><tr><th>Name</th><th>Type</th><th>Target</th><th>Status</th><th>Sent</th><th>Customers</th><th>Date</th><th>Added By</th><th>Actions</th></tr></thead><tbody><?php if(!$list||$list->num_rows===0): ?><tr><td colspan="9" class="text-center text-muted" style="padding:40px">No campaigns found</td></tr><?php else: while($c=$list->fetch_assoc()): $types=[]; if(!empty($c['type_whatsapp']))$types[]='WhatsApp'; if(!empty($c['type_email']))$types[]='Email'; if(!empty($c['type_sms']))$types[]='SMS'; $displayCount=(int)($c['customer_count'] ?? 0); if(($c['target_type']??'')==='audience' && !empty($c['audience_id']) && tableExists($conn,'audience_customers')){ $aid=(int)$c['audience_id']; $cq=$conn->query("SELECT COUNT(*) cnt FROM audience_customers ac INNER JOIN customers cc ON cc.id=ac.customer_id WHERE ac.audience_id=$aid AND cc.account_id=$account_id"); if($cq)$displayCount=(int)$cq->fetch_assoc()['cnt']; } ?><tr><td><strong><?= htmlspecialchars($c['name']) ?></strong><div class="text-xs text-muted"><?= htmlspecialchars($c['description']?:'') ?></div></td><td><?= $types?implode(' ',array_map(fn($x)=>'<span class="badge badge-blue">'.$x.'</span>',$types)):'—' ?></td><td><?= $c['target_type']==='audience' ? 'Audience: '.htmlspecialchars($c['audience_name']?:'—') : 'Dynamic Filter' ?></td><td><span class="badge badge-<?= $c['status']?'green':'gray' ?>"><?= $c['status']?'Active':'Inactive' ?></span></td><td><?= !empty($c['is_sent']) ? '<span class="badge badge-green">Sent</span>' : '<span class="badge badge-gray">Pending</span>' ?></td><td><span class="badge badge-blue"><?= $displayCount ?></span></td><td class="text-xs text-muted"><?= formatDate($c['date_created']) ?></td><td><?= htmlspecialchars($c['creator_name'] ?: '—') ?></td><td><div class="d-flex gap-8"><a class="btn btn-primary btn-sm" href="index.php?page=campaign_view&id=<?= crmEid($c['id']) ?>">Open</a><a class="btn btn-secondary btn-sm" href="index.php?page=campaign_report&id=<?= crmEid($c['id']) ?>">Report</a><?php if(empty($c['is_sent'])): ?><a class="btn btn-secondary btn-sm" data-permission="edit" href="index.php?page=campaign_edit&id=<?= crmEid($c['id']) ?>">Edit</a><?php endif; ?><button class="btn btn-danger btn-sm" data-permission="delete" onclick="deleteCampaign('<?= crmEid($c['id']) ?>')">Delete</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 ?> campaigns</div><div><?php for($i=1;$i<=$total_pages;$i++): ?><a class="btn btn-<?= $i==$page_num?'primary':'secondary' ?> btn-sm" href="?page=campaigns&page_num=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a> <?php endfor; ?></div></div></div></div><script>document.getElementById('campaignSearch').addEventListener('keydown',e=>{if(e.key==='Enter')location.href='?page=campaigns&search='+encodeURIComponent(e.target.value)});async function deleteCampaign(id){confirmAction('Delete this campaign?',async()=>{const r=await apiCall('handlers/campaigns.php',{action:'delete',id});if(r.success)location.reload();else showToast(r.message||'Error','error')})}</script>
