<?php
require_once __DIR__ . '/../lib/audience_rules.php';
$id = crmId($_GET['id'] ?? 0);
$q = $conn->query("SELECT c.*, a.name audience_name FROM campaign c LEFT JOIN audience a ON a.id=c.audience_id WHERE c.id=$id AND c.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();
$rules = crm_decode_rules($camp['rules_json'] ?? '');
if (($camp['target_type'] ?? '') === 'audience' && !empty($camp['audience_id']) && tableExists($conn,'audience_customers')) {
  $aid=(int)$camp['audience_id'];
  $countQ=$conn->query("SELECT COUNT(DISTINCT c.id) cnt FROM audience_customers ac INNER JOIN customers c ON c.id=ac.customer_id WHERE ac.audience_id=$aid AND c.account_id=$account_id");
  $count=$countQ?(int)$countQ->fetch_assoc()['cnt']:0;
  $rows=$conn->query("SELECT DISTINCT c.id,c.customer_name,c.business_name,c.phone,c.email,c.priority,co.name country_name FROM audience_customers ac INNER JOIN customers c ON c.id=ac.customer_id LEFT JOIN countries co ON co.id=c.country_id WHERE ac.audience_id=$aid AND c.account_id=$account_id ORDER BY c.customer_name ASC LIMIT 500");
} else {
  $count = crm_count_customers_by_rules($conn, $account_id, $rules);
  $rows = crm_get_customers_by_rules($conn, $account_id, $rules, 500, 0);
}
$types = [];
if (!empty($camp['type_whatsapp'])) $types[] = 'whatsapp';
if (!empty($camp['type_email'])) $types[] = 'email';
if (!empty($camp['type_sms'])) $types[] = 'sms';
$isSent = !empty($camp['is_sent']);
$logMap=[];
if(tableExists($conn,'campaign_logs')){
  $lq=$conn->query("SELECT * FROM campaign_logs WHERE campaign_id=$id ORDER BY sent_at DESC, id DESC");
  while($lq && $l=$lq->fetch_assoc()) $logMap[(int)$l['customer_id']][$l['type']]=$l;
}
function cv_msg($camp,$type){
  if($type==='whatsapp') return $camp['message_whatsapp'] ?: '—';
  if($type==='email') return ($camp['email_subject']?'<strong>'.htmlspecialchars($camp['email_subject']).'</strong><br>':'').($camp['message_email'] ?: '—');
  return $camp['message_sms'] ?: '—';
}
?>
<div class="fade-in">
  <div class="toolbar" style="gap:8px;flex-wrap:wrap">
    <a href="index.php?page=campaigns" class="btn btn-secondary">← Back</a>
    <a href="index.php?page=campaign_report&id=<?= crmEid($id) ?>" class="btn btn-secondary">Report</a>
    <?php if (!$isSent): ?>
      <a href="index.php?page=campaign_edit&id=<?= crmEid($id) ?>" class="btn btn-primary">Edit</a>
      <button class="btn btn-secondary" onclick="prepareCampaignSend()">Send Campaign Now</button>
    <?php else: ?>
      <span class="badge badge-green">Sent <?= htmlspecialchars($camp['sent_at'] ?: '') ?></span>
    <?php endif; ?>
    <button class="btn btn-danger" data-permission="delete" onclick="deleteCampaign(<?= $id ?>)">Delete</button>
  </div>

  <div class="card" style="padding:20px;margin-bottom:16px">
    <h3 style="margin-top:0"><?= htmlspecialchars($camp['name']) ?></h3>
    <p class="text-muted"><?= htmlspecialchars($camp['description'] ?: '') ?></p>
    <div class="d-flex gap-8" style="flex-wrap:wrap;margin-bottom:14px">
      <span class="badge badge-blue">Type: <?= htmlspecialchars(implode(', ', array_map('ucfirst',$types)) ?: '—') ?></span>
      <span class="badge badge-purple">Target: <?= $camp['target_type']==='audience' ? 'Audience - '.htmlspecialchars($camp['audience_name'] ?: '—') : 'Dynamic Filter' ?></span>
      <span class="badge badge-green"><?= number_format($count) ?> Customers</span>
      <span class="badge badge-<?= $isSent ? 'green' : 'gray' ?>"><?= $isSent ? 'Sent' : 'Pending' ?></span>
    </div>
    <div class="campaign-message-summary">
      <?php foreach($types as $t): ?><div class="campaign-message-chip"><strong><?= ucfirst($t) ?> Message</strong><div><?= $t==='email' ? cv_msg($camp,$t) : nl2br(htmlspecialchars(cv_msg($camp,$t))) ?></div></div><?php endforeach; ?>
    </div>
  </div>

  <div class="card">
    <div class="card-header"><span class="card-title">Customers & Send Results</span><span class="text-xs text-muted">Campaign can be sent one time only.</span></div>
    <div class="table-wrapper"><table class="crm-table"><thead><tr><th>Customer</th><th>Business</th><th>Phone</th><th>Email</th><th>Type</th><th>Status</th><th>Response</th><th>Open</th></tr></thead><tbody>
      <?php if(!$rows || !$rows->num_rows): ?><tr><td colspan="8" class="text-center text-muted">No customers</td></tr><?php else: while($c=$rows->fetch_assoc()): foreach($types ?: ['—'] as $t): $log=$logMap[(int)$c['id']][$t]??null; $st=$log['status']??($isSent?'pending':'not sent'); ?>
        <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(ucfirst($t)) ?></td><td><span class="badge badge-<?= $st==='sent'?'green':($st==='failed'?'red':'gray') ?>"><?= htmlspecialchars($st) ?></span></td><td><?= htmlspecialchars(mb_strimwidth($log['response']??'—',0,120,'...')) ?></td><td><a class="btn btn-secondary btn-sm" target="_blank" href="index.php?page=customer_view&id=<?= crmEid($c['id']) ?>">View</a></td></tr>
      <?php endforeach; endwhile; endif; ?>
    </tbody></table></div>
  </div>
</div>
<script>
async function prepareCampaignSend(){
  if(!confirm('Send this campaign now? You cannot send it again after it is marked sent.')) return;
  const r=await apiCall('handlers/campaigns.php',{action:'send',id:<?= $id ?>});
  if(r.success){showToast('Sent '+r.sent+' messages, failed '+r.failed,'success');setTimeout(()=>location.reload(),700);} else showToast(r.message||'Error','error');
}
async function deleteCampaign(id){
  if(!confirm('Delete this campaign?')) return;
  const r=await apiCall('handlers/campaigns.php',{action:'delete',id:id});
  if(r.success){showToast('Campaign deleted','success');setTimeout(()=>location.href='index.php?page=campaigns',500);} else showToast(r.message||'Error','error');
}
</script>
