<?php
session_start();
$page_title = 'Broadcast Message';
$active_nav = 'broadcast';
include("includes/header.php");

if (!$is_admin) {
    echo '<div class="alert alert-error">Only restaurant admins can send broadcasts.</div>';
    include("includes/footer.php"); exit;
}

$success = '';
$error   = '';

// Ensure the optional "featured menu item" column exists on both tables so a
// broadcast can promote a specific dish that deep-links into the menu.
foreach (['customer_notifications', 'broadcasts'] as $__tbl) {
    $__c = @$conn->query("SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='{$__tbl}' AND COLUMN_NAME='menu_item_id'");
    if ($__c && $__c->num_rows === 0) @$conn->query("ALTER TABLE `{$__tbl}` ADD COLUMN `menu_item_id` INT NULL");
}

// Menu items this restaurant can feature in a broadcast.
$menu_items = [];
if ($mi = $conn->prepare("SELECT id, name, price FROM menu_items WHERE restaurant_id=? AND is_available=1 ORDER BY name")) {
    $mi->bind_param("i", $__rid);
    $mi->execute();
    $menu_items = $mi->get_result()->fetch_all(MYSQLI_ASSOC);
}

// ── Handle POST ───────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'send_broadcast') {
    $subject  = trim($_POST['subject']  ?? '');
    $message  = trim($_POST['message']  ?? '');
    $audience = $_POST['audience'] ?? 'all';

    // Optional featured menu item (must belong to this restaurant).
    $feature_item = (int)($_POST['feature_item'] ?? 0);
    if ($feature_item) {
        $vi = $conn->prepare("SELECT id FROM menu_items WHERE id=? AND restaurant_id=? LIMIT 1");
        $vi->bind_param("ii", $feature_item, $__rid);
        $vi->execute();
        if ($vi->get_result()->num_rows === 0) $feature_item = 0;
    }
    $mi_param = $feature_item ?: null;

    if (!$subject || !$message) {
        $error = "Subject and message are required.";
    } else {
        $days_map = ['all' => null, 'recent_7' => 7, 'recent_30' => 30];
        $days     = $days_map[$audience] ?? null;

        // Fetch distinct customers who ordered from this restaurant
        if ($days) {
            $cq = $conn->prepare(
                "SELECT DISTINCT u.id, u.name, COALESCE(u.notify_promos,1) AS wants_promos
                 FROM orders o JOIN users u ON o.user_id = u.id
                 WHERE o.restaurant_id = ?
                   AND o.created_at >= NOW() - INTERVAL ? DAY
                 ORDER BY u.name"
            );
            $cq->bind_param("ii", $__rid, $days);
        } else {
            $cq = $conn->prepare(
                "SELECT DISTINCT u.id, u.name, COALESCE(u.notify_promos,1) AS wants_promos
                 FROM orders o JOIN users u ON o.user_id = u.id
                 WHERE o.restaurant_id = ?
                 ORDER BY u.name"
            );
            $cq->bind_param("i", $__rid);
        }
        $cq->execute();
        $customers = $cq->get_result()->fetch_all(MYSQLI_ASSOC);

        if (empty($customers)) {
            $error = "No customers found for the selected audience.";
        } else {
            $total      = count($customers);
            $notif_type = $feature_item ? 'promo' : 'broadcast';

            // 1. Save broadcast record
            $bs = $conn->prepare(
                "INSERT INTO broadcasts (restaurant_id, subject, message, audience, recipient_count, sent_by, menu_item_id, created_at)
                 VALUES (?, ?, ?, ?, ?, ?, ?, NOW())"
            );
            $bs->bind_param("isssiii", $__rid, $subject, $message, $audience, $total, $uid, $mi_param);
            $bs->execute();
            $broadcast_id = (int)$conn->insert_id;

            // 2. Insert into customer_notifications for each customer who accepts
            //    promotional messages (respects Settings → Notifications → Promotions).
            $sent      = 0;
            $notif_title = $__rest_name . ": " . mb_strimwidth($subject, 0, 60, '…');
            $notif_msg   = mb_strimwidth($message, 0, 180, '…');

            $ins = $conn->prepare(
                "INSERT INTO customer_notifications
                    (user_id, restaurant_id, broadcast_id, menu_item_id, type, title, message, is_read, created_at)
                 VALUES (?, ?, ?, ?, ?, ?, ?, 0, NOW())"
            );

            foreach ($customers as $c) {
                if ((int)($c['wants_promos'] ?? 1) === 0) continue; // customer turned promos off
                $cust_uid = (int)$c['id'];
                $ins->bind_param("iiiisss", $cust_uid, $__rid, $broadcast_id, $mi_param, $notif_type, $notif_title, $notif_msg);
                if ($ins->execute()) $sent++;
            }

            // 3. Update actual sent count
            $upd = $conn->prepare("UPDATE broadcasts SET sent_count=? WHERE id=?");
            $upd->bind_param("ii", $sent, $broadcast_id);
            $upd->execute();

            // 4. Also create one restaurant-side notification so admin sees it in their panel
            $rest_notif_msg = "Broadcast sent to $sent customer" . ($sent !== 1 ? 's' : '') . ": $subject";
            $rn = $conn->prepare(
                "INSERT INTO notifications (restaurant_id, type, title, message, related_id, is_read, created_at)
                 VALUES (?, 'broadcast', 'Broadcast Sent', ?, ?, 0, NOW())"
            );
            $rn->bind_param("isi", $__rid, $rest_notif_msg, $broadcast_id);
            $rn->execute();

            $success = "Broadcast sent to <strong>$sent customer" . ($sent !== 1 ? 's' : '') . "</strong> successfully!";
        }
    }
}

// ── Audience counts (no email filter — all customers count) ───────────────────
$count_all = $conn->prepare(
    "SELECT COUNT(DISTINCT u.id) FROM orders o JOIN users u ON o.user_id=u.id
     WHERE o.restaurant_id=?"
);
$count_all->bind_param("i", $__rid); $count_all->execute();
$cnt_all = (int)$count_all->get_result()->fetch_row()[0];

$count_7 = $conn->prepare(
    "SELECT COUNT(DISTINCT u.id) FROM orders o JOIN users u ON o.user_id=u.id
     WHERE o.restaurant_id=? AND o.created_at >= NOW()-INTERVAL 7 DAY"
);
$count_7->bind_param("i", $__rid); $count_7->execute();
$cnt_7 = (int)$count_7->get_result()->fetch_row()[0];

$count_30 = $conn->prepare(
    "SELECT COUNT(DISTINCT u.id) FROM orders o JOIN users u ON o.user_id=u.id
     WHERE o.restaurant_id=? AND o.created_at >= NOW()-INTERVAL 30 DAY"
);
$count_30->bind_param("i", $__rid); $count_30->execute();
$cnt_30 = (int)$count_30->get_result()->fetch_row()[0];

// ── Broadcast history ─────────────────────────────────────────────────────────
$history = $conn->prepare(
    "SELECT b.*, u.name as sent_by_name
     FROM broadcasts b LEFT JOIN users u ON b.sent_by=u.id
     WHERE b.restaurant_id=? ORDER BY b.created_at DESC LIMIT 20"
);
$history->bind_param("i", $__rid); $history->execute();
$history_result = $history->get_result();
?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:26px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Broadcast Message</h1>
    <p style="color:var(--text-muted);font-size:.85rem">Send a message to customers of <?php echo htmlspecialchars($__rest_name); ?></p>
  </div>
</div>

<?php if ($success): ?>
<div class="alert alert-success" style="margin-bottom:20px">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round">
    <path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>
  </svg>
  <?php echo $success; ?>
</div>
<?php endif; ?>

<?php if ($error): ?>
<div class="alert alert-error" style="margin-bottom:20px">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round">
    <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/>
  </svg>
  <?php echo htmlspecialchars($error); ?>
</div>
<?php endif; ?>

<div style="display:grid;grid-template-columns:1fr 340px;gap:20px;align-items:start">

  <!-- Compose Form -->
  <div class="card">
    <div class="card-header"><h3>Compose Broadcast</h3></div>
    <div class="card-body">
      <form method="POST">
        <input type="hidden" name="action" value="send_broadcast">

        <!-- Audience -->
        <div class="form-group">
          <label style="font-weight:700;margin-bottom:10px;display:block">Audience</label>
          <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:4px">

            <label style="cursor:pointer">
              <input type="radio" name="audience" value="all" checked style="display:none" class="aud-radio">
              <div class="aud-card" style="border:2px solid var(--primary);background:var(--primary-bg);border-radius:12px;padding:14px;text-align:center;transition:all .2s">
                <div style="font-size:1.4rem;font-weight:800;color:var(--primary)"><?php echo $cnt_all; ?></div>
                <div style="font-size:.75rem;font-weight:700;color:var(--primary);margin-top:2px">All Customers</div>
                <div style="font-size:.68rem;color:var(--text-muted);margin-top:2px">Ever ordered</div>
              </div>
            </label>

            <label style="cursor:pointer">
              <input type="radio" name="audience" value="recent_30" style="display:none" class="aud-radio">
              <div class="aud-card" style="border:2px solid var(--border);background:var(--white);border-radius:12px;padding:14px;text-align:center;transition:all .2s">
                <div style="font-size:1.4rem;font-weight:800"><?php echo $cnt_30; ?></div>
                <div style="font-size:.75rem;font-weight:700;margin-top:2px">Last 30 Days</div>
                <div style="font-size:.68rem;color:var(--text-muted);margin-top:2px">Recent customers</div>
              </div>
            </label>

            <label style="cursor:pointer">
              <input type="radio" name="audience" value="recent_7" style="display:none" class="aud-radio">
              <div class="aud-card" style="border:2px solid var(--border);background:var(--white);border-radius:12px;padding:14px;text-align:center;transition:all .2s">
                <div style="font-size:1.4rem;font-weight:800"><?php echo $cnt_7; ?></div>
                <div style="font-size:.75rem;font-weight:700;margin-top:2px">Last 7 Days</div>
                <div style="font-size:.68rem;color:var(--text-muted);margin-top:2px">This week</div>
              </div>
            </label>

          </div>
        </div>

        <!-- Subject -->
        <div class="form-group">
          <label style="font-weight:700;margin-bottom:8px;display:block">Subject *</label>
          <input type="text" name="subject" class="form-control"
                 placeholder="e.g. 🎉 Special Weekend Offer!"
                 maxlength="100" required oninput="updatePreview()">
          <div style="font-size:.72rem;color:var(--text-muted);margin-top:4px">Max 100 characters</div>
        </div>

        <!-- Message -->
        <div class="form-group" style="margin-bottom:20px">
          <label style="font-weight:700;margin-bottom:8px;display:block">Message *</label>
          <textarea name="message" id="msgBody" class="form-control" rows="5" maxlength="500"
                    placeholder="Write your message here… e.g. Try our latest dish this weekend!"
                    required oninput="updateCharCount(this);updatePreview()"></textarea>
          <div style="display:flex;justify-content:space-between;margin-top:4px">
            <div style="font-size:.72rem;color:var(--text-muted)">Keep it concise and clear</div>
            <div style="font-size:.72rem;color:var(--text-muted)"><span id="charCount">0</span>/500</div>
          </div>
        </div>

        <!-- Feature a menu item (optional) -->
        <div class="form-group" style="margin-bottom:24px">
          <label style="font-weight:700;margin-bottom:8px;display:block">Feature a dish <span style="font-weight:500;color:var(--text-muted)">(optional)</span></label>
          <select name="feature_item" class="form-control">
            <option value="0">— None (message only) —</option>
            <?php foreach ($menu_items as $m): ?>
            <option value="<?php echo (int)$m['id']; ?>"><?php echo htmlspecialchars($m['name']); ?> — ₦<?php echo number_format($m['price'], 0); ?></option>
            <?php endforeach; ?>
          </select>
          <div style="font-size:.72rem;color:var(--text-muted);margin-top:4px">When a dish is selected, customers can tap the notification to open it in your menu and order — great for "try our latest dish" promos.</div>
        </div>

        <button type="submit" class="btn btn-primary btn-lg" style="width:100%;justify-content:center"
                onclick="return confirm('Send this broadcast to the selected customers?')">
          <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round">
            <line x1="22" y1="2" x2="11" y2="13"/>
            <polygon points="22 2 15 22 11 13 2 9 22 2"/>
          </svg>
          Send Broadcast
        </button>
      </form>
    </div>
  </div>

  <!-- Right Panel -->
  <div style="display:flex;flex-direction:column;gap:16px">

    <!-- Live Preview -->
    <div class="card">
      <div class="card-header"><h3>Preview</h3></div>
      <div class="card-body">
        <div style="background:var(--bg);border-radius:12px;padding:16px;border:1.5px solid var(--border)">
          <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:var(--text-muted);margin-bottom:8px">
            <?php echo htmlspecialchars($__rest_name); ?>
          </div>
          <div style="font-size:.9rem;font-weight:700;margin-bottom:6px;color:var(--text)" id="previewSubject">
            Your subject here…
          </div>
          <div style="font-size:.82rem;color:var(--text-muted);line-height:1.6" id="previewBody">
            Your message will appear here…
          </div>
        </div>
        <div style="font-size:.72rem;color:var(--text-muted);margin-top:10px;text-align:center">
          Delivered as in-app notification to each customer
        </div>
      </div>
    </div>

    <!-- Audience Summary -->
    <div class="card">
      <div class="card-header"><h3>Audience Summary</h3></div>
      <div class="card-body" style="padding:16px">
        <?php foreach ([
          ['All-time customers',      $cnt_all],
          ['Ordered last 30 days',    $cnt_30],
          ['Ordered last 7 days',     $cnt_7],
        ] as [$label, $count]): ?>
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px">
          <span style="font-size:.83rem;color:var(--text-muted)"><?php echo $label; ?></span>
          <span style="font-weight:700"><?php echo $count; ?></span>
        </div>
        <?php endforeach; ?>
        <?php if ($cnt_all === 0): ?>
        <div style="background:var(--warning-bg);border-radius:8px;padding:10px 12px;font-size:.78rem;color:var(--warning);margin-top:4px">
          <strong>No customers yet.</strong> Broadcasts will be available once customers start ordering.
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Tips -->
    <div class="card" style="background:var(--primary-bg);border:1.5px solid rgba(34,90,227,.15)">
      <div class="card-body" style="padding:16px">
        <div style="font-size:.78rem;font-weight:700;color:var(--primary);margin-bottom:10px">💡 Tips</div>
        <?php foreach ([
          'Use for offers, new items, or announcements',
          'Target recent customers for higher engagement',
          'Keep messages short and actionable',
          'Emojis help your message stand out 🎉',
        ] as $tip): ?>
        <div style="display:flex;gap:7px;margin-bottom:7px">
          <span style="color:var(--primary);flex-shrink:0">•</span>
          <span style="font-size:.78rem;color:var(--text-muted)"><?php echo $tip; ?></span>
        </div>
        <?php endforeach; ?>
      </div>
    </div>

  </div>
</div>

<!-- Broadcast History -->
<div class="card" style="margin-top:24px">
  <div class="card-header">
    <h3>Broadcast History</h3>
    <span style="font-size:.78rem;color:var(--text-muted)">Last 20 broadcasts</span>
  </div>
  <?php if ($history_result->num_rows === 0): ?>
  <div style="padding:48px;text-align:center;color:var(--text-muted)">
    <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 12px;display:block">
      <line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
    </svg>
    <p style="font-weight:700;margin-bottom:4px">No broadcasts yet</p>
    <p style="font-size:.82rem">Your broadcast history will appear here</p>
  </div>
  <?php else: ?>
    <div class="table-scroll">
<table class="data-table">
    <thead>
      <tr><th>Subject</th><th>Message</th><th>Audience</th><th>Sent To</th><th>Sent By</th><th>Date</th></tr>
    </thead>
    <tbody>
    <?php
    $aud_labels = ['all'=>'All Customers','recent_7'=>'Last 7 Days','recent_30'=>'Last 30 Days'];
    while ($b = $history_result->fetch_assoc()):
    ?>
    <tr>
      <td style="font-weight:600;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
        <?php echo htmlspecialchars($b['subject']); ?>
      </td>
      <td style="font-size:.82rem;color:var(--text-muted);max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
        <?php echo htmlspecialchars($b['message']); ?>
      </td>
      <td><span class="badge badge-primary" style="font-size:.68rem"><?php echo $aud_labels[$b['audience']] ?? $b['audience']; ?></span></td>
      <td style="font-weight:700;text-align:center"><?php echo $b['sent_count']; ?> customers</td>
      <td style="font-size:.82rem"><?php echo htmlspecialchars($b['sent_by_name'] ?? '—'); ?></td>
      <td style="font-size:.75rem;color:var(--text-muted);white-space:nowrap"><?php echo date('M j, Y g:i A', strtotime($b['created_at'])); ?></td>
    </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
</div>
  <?php endif; ?>
</div>

<script>
document.querySelectorAll('.aud-radio').forEach(radio => {
  radio.addEventListener('change', function() {
    document.querySelectorAll('.aud-card').forEach(c => {
      c.style.borderColor = 'var(--border)';
      c.style.background  = 'var(--white)';
      c.querySelector('div:first-child').style.color = '';
      c.querySelectorAll('div:nth-child(2)').forEach(d => d.style.color = '');
    });
    const card = this.nextElementSibling;
    card.style.borderColor = 'var(--primary)';
    card.style.background  = 'var(--primary-bg)';
    card.querySelector('div:first-child').style.color = 'var(--primary)';
    card.querySelectorAll('div:nth-child(2)').forEach(d => d.style.color = 'var(--primary)');
  });
});

function updateCharCount(el) {
  const cc = document.getElementById('charCount');
  if (cc) cc.textContent = el.value.length;
}

function updatePreview() {
  const subj = document.querySelector('input[name="subject"]');
  const body = document.getElementById('msgBody');
  const ps   = document.getElementById('previewSubject');
  const pb   = document.getElementById('previewBody');
  if (ps && subj) ps.textContent = subj.value || 'Your subject here…';
  if (pb && body) pb.textContent = body.value || 'Your message will appear here…';
}
</script>

<?php include("includes/footer.php"); ?>
