<?php
$id=(int)($_GET['id']??0);
$q=$conn->query("SELECT * FROM campaign WHERE id=$id AND account_id=$account_id LIMIT 1");
if(!$q||!$q->num_rows){ echo '<div class="alert alert-error">Campaign not found</div>'; return; }
$camp=$q->fetch_assoc();
$stats=['total'=>0,'sent'=>0,'failed'=>0,'pending'=>0];
$logs=false;
if(tableExists($conn,'campaign_logs')){
  $sq=$conn->query("SELECT status,COUNT(*) cnt FROM campaign_logs WHERE campaign_id=$id GROUP BY status");
  while($sq && $r=$sq->fetch_assoc()){ $stats['total']+=(int)$r['cnt']; if($r['status']==='sent')$stats['sent']=(int)$r['cnt']; elseif($r['status']==='failed')$stats['failed']=(int)$r['cnt']; }
  $expected=(int)($camp['customer_count']??0);
  $stats['pending']=max(0,$expected-$stats['total']);
  $logs=$conn->query("SELECT cl.*, c.customer_name, c.phone, c.email FROM campaign_logs cl LEFT JOIN customers c ON c.id=cl.customer_id WHERE cl.campaign_id=$id ORDER BY cl.sent_at DESC, cl.id DESC LIMIT 1000");
}
?>
<div class="fade-in">
  <div class="toolbar" style="justify-content:space-between;gap:10px;flex-wrap:wrap">
    <a href="index.php?page=campaign_view&id=<?= $id ?>" class="btn btn-secondary">← Back</a>
    <h3 style="margin:0">Campaign Report: <?= htmlspecialchars($camp['name']) ?></h3>
  </div>
  <div class="stats-grid">
    <div class="stat-card"><div class="stat-label">Total Attempts</div><div class="stat-value"><?= (int)$stats['total'] ?></div></div>
    <div class="stat-card"><div class="stat-label">Success</div><div class="stat-value"><?= (int)$stats['sent'] ?></div></div>
    <div class="stat-card"><div class="stat-label">Failed</div><div class="stat-value"><?= (int)$stats['failed'] ?></div></div>
    <div class="stat-card"><div class="stat-label">Pending</div><div class="stat-value"><?= (int)$stats['pending'] ?></div></div>
  </div>
  <div class="card"><div class="card-header"><span class="card-title">Send Details</span></div><div class="table-wrapper"><table class="crm-table"><thead><tr><th>Date</th><th>Customer</th><th>Contact</th><th>Type</th><th>Status</th><th>Response</th></tr></thead><tbody>
  <?php if(!$logs || !$logs->num_rows): ?><tr><td colspan="6" class="text-center text-muted">No results yet</td></tr><?php else: while($l=$logs->fetch_assoc()): ?>
    <tr><td><?= htmlspecialchars($l['sent_at']??'') ?></td><td><?= htmlspecialchars($l['customer_name']??('#'.$l['customer_id'])) ?></td><td><?= htmlspecialchars(($l['type']==='email'?($l['email']??''):($l['phone']??'')) ?: '—') ?></td><td><?= htmlspecialchars($l['type']) ?></td><td><span class="badge badge-<?= $l['status']==='sent'?'green':'red' ?>"><?= htmlspecialchars($l['status']) ?></span></td><td><?= htmlspecialchars(mb_strimwidth($l['response']??'',0,160,'...')) ?></td></tr>
  <?php endwhile; endif; ?>
  </tbody></table></div></div>
</div>
