<?php
require_once __DIR__ . '/../lib/audience_rules.php';
$id = (int)($_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'] ?? '');
$count = !empty($camp['customer_count']) ? (int)$camp['customer_count'] : crm_count_customers_by_rules($conn, $account_id, $rules);
$rows = crm_get_customers_by_rules($conn, $account_id, $rules, 200, 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']);
?>
<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>
    <?php if (!$isSent): ?>
      <a href="index.php?page=campaign_edit&id=<?= $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; ?>
  </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">
      <span class="badge badge-blue">Type: <?= htmlspecialchars(implode(', ', $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' : 'Draft / not sent' ?></span>
    </div>
  </div>

  <div class="card" style="padding:20px;margin-bottom:16px">
    <h4>Messages</h4>
    <div class="form-grid">
      <div><label class="form-label">WhatsApp</label><div class="message-box"><?= nl2br(htmlspecialchars($camp['message_whatsapp'] ?: '—')) ?></div></div>
      <div><label class="form-label">SMS</label><div class="message-box"><?= nl2br(htmlspecialchars($camp['message_sms'] ?: '—')) ?></div></div>
      <div><label class="form-label">Email</label><div class="message-box"><strong><?= htmlspecialchars($camp['email_subject'] ?: '') ?></strong><br><?= nl2br(htmlspecialchars($camp['message_email'] ?: '—')) ?></div></div>
    </div>
    <?php if (!empty($camp['media_url'])): ?><div style="margin-top:12px"><label class="form-label">Image</label><br><img src="<?= htmlspecialchars($camp['media_url']) ?>" style="max-width:220px;border-radius:12px;border:1px solid var(--border)"></div><?php endif; ?>
  </div>

  <div class="card">
    <div class="card-header"><span class="card-title">Customers Preview</span><span class="text-xs text-muted">Send is only from the campaign button above.</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>Open</th></tr></thead><tbody>
      <?php if(!$rows || !$rows->num_rows): ?><tr><td colspan="5" class="text-center text-muted">No customers</td></tr><?php else: while($c=$rows->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><a class="btn btn-secondary btn-sm" href="index.php?page=customer_view&id=<?= $c['id'] ?>">View</a></td></tr>
      <?php endwhile; endif; ?>
    </tbody></table></div>
  </div>

  <?php $logs = tableExists($conn,'campaign_logs') ? $conn->query("SELECT cl.*, c.customer_name 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 300") : false; ?>
  <div class="card" style="margin-top:16px"><div class="card-header"><span class="card-title">Send Results</span></div><div class="table-wrapper"><table class="crm-table"><thead><tr><th>Date</th><th>Customer</th><th>Type</th><th>Status</th><th>Response</th></tr></thead><tbody><?php if(!$logs || $logs->num_rows===0): ?><tr><td colspan="5" class="text-center text-muted">No send 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']) ?></td><td><span class="badge badge-<?= $l['status']==='sent'?'green':'red' ?>"><?= htmlspecialchars($l['status']) ?></span></td><td><?= htmlspecialchars(mb_strimwidth($l['response'] ?? '',0,120,'...')) ?></td></tr><?php endwhile; endif; ?></tbody></table></div></div>
</div>
<style>.message-box{padding:12px;border:1px solid var(--border);border-radius:10px;background:var(--bg-base);min-height:80px}</style>
<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');
}
</script>
