<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireAdmin();
$pageTitle = 'Broadcast Email';

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

// Handle send
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send'])) {
  $subject  = trim($_POST['subject'] ?? '');
  $bodyHtml = trim($_POST['body_html'] ?? '');
  $target   = $_POST['target'] ?? 'all';

  if (!$subject || !$bodyHtml) {
    $error = 'Subject and body are required.';
  } else {
    // Get recipients
    if ($target === 'all') {
      $recipients = Database::fetchAll("SELECT email, contact_name FROM customers WHERE status='active' AND email IS NOT NULL AND email != ''");
    } else {
      $recipients = Database::fetchAll("SELECT email, contact_name FROM customers WHERE status='active' AND email IS NOT NULL AND email != '' ORDER BY id DESC LIMIT 100");
    }

    $sent = 0; $failed = 0;
    $wrappedHtml = emailHtmlWrapper($bodyHtml);
    foreach ($recipients as $r) {
      if (sendEmail($r['email'], $subject, $wrappedHtml)) {
        $sent++;
      } else {
        $failed++;
      }
    }
    logActivity('admin', $_SESSION['admin_id'], "Broadcast email sent to $sent recipients: $subject");
    $success = "Broadcast sent! $sent delivered, $failed failed.";
  }
}

// Preview HTML
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['preview'])) {
  $preview = emailHtmlWrapper(trim($_POST['body_html'] ?? ''));
}

$totalCustomers = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM customers WHERE status='active' AND email IS NOT NULL AND email!=''")['c'] ?? 0);
require_once __DIR__ . '/includes/header.php';
?>

<div class="max-w-5xl">
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-xl font-bold">📢 Broadcast Email</h1>
    <div class="text-sm text-gray-400"><?= $totalCustomers ?> active customers with email addresses</div>
  </div>

  <?php if ($success): ?>
  <div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-6"><?= e($success) ?></div>
  <?php endif; ?>
  <?php if ($error): ?>
  <div class="bg-red-600/10 border border-red-600/30 text-red-400 text-sm px-4 py-3 rounded-lg mb-6"><?= e($error) ?></div>
  <?php endif; ?>

  <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
    <!-- Compose -->
    <form method="POST" class="card-dark p-6">
      <h2 class="font-semibold mb-5 text-orange-400">Compose Message</h2>

      <div class="mb-4">
        <label class="block text-xs text-gray-400 mb-1">Target Audience</label>
        <select name="target" class="input-field">
          <option value="all">All Active Customers (<?= $totalCustomers ?>)</option>
        </select>
      </div>

      <div class="mb-4">
        <label class="block text-xs text-gray-400 mb-1">Email Subject *</label>
        <input type="text" name="subject" value="<?= e($_POST['subject'] ?? '') ?>" class="input-field" placeholder="e.g. New Stock Arrival — API 6A Gate Valves" required>
      </div>

      <div class="mb-4">
        <label class="block text-xs text-gray-400 mb-2">Message Body (HTML supported)</label>
        <!-- Quick templates -->
        <div class="flex flex-wrap gap-2 mb-2">
          <?php foreach ([
            ['New Stock', '<h2>New Stock Available</h2><p>We are pleased to inform you that the following products are now available:</p><ul><li>Item 1</li><li>Item 2</li></ul><p>Contact us or <a href="{{portal_url}}">log in to your portal</a> to request a quotation.</p>'],
            ['Price Update', '<h2>Price Update Notice</h2><p>Please be advised that pricing for the following items has been updated effective immediately:</p><ul><li>Item — New Price</li></ul><p>Contact our sales team for a formal quotation.</p>'],
            ['Promotion', '<h2>Special Offer</h2><p>For a limited time, we are offering preferential pricing on selected industrial equipment.</p><p>Contact us before the offer expires to lock in your pricing.</p>'],
            ['Announcement', '<h2>Important Announcement</h2><p>We would like to inform all our valued clients of the following update:</p><p>[Your message here]</p><p>Thank you for your continued business.</p>'],
          ] as [$label, $tpl]): ?>
          <button type="button" onclick="insertTemplate(<?= json_encode($tpl) ?>)"
            class="text-xs bg-navy-600 hover:bg-navy-500 text-gray-300 px-2.5 py-1 rounded-lg transition-colors">
            <?= $label ?>
          </button>
          <?php endforeach; ?>
        </div>
        <textarea name="body_html" id="broadcast-body" rows="12" class="input-field font-mono text-xs" placeholder="<h2>Hello!</h2><p>Your message here...</p>"><?= e($_POST['body_html'] ?? '') ?></textarea>
        <p class="text-xs text-gray-500 mt-1">Available variables: <code class="text-orange-400">{{company_name}}</code> <code class="text-orange-400">{{portal_url}}</code> <code class="text-orange-400">{{year}}</code></p>
      </div>

      <div class="flex gap-3">
        <button type="submit" name="send" class="btn-primary flex-1 py-2.5"
          onclick="return confirm('Send this email to <?= $totalCustomers ?> customers?')">
          🚀 Send Broadcast
        </button>
        <button type="submit" name="preview" class="btn-outline px-4 py-2.5">Preview</button>
      </div>
    </form>

    <!-- Preview panel -->
    <div class="card-dark p-6">
      <h2 class="font-semibold mb-4 text-orange-400">Email Preview</h2>
      <?php if ($preview): ?>
      <iframe srcdoc="<?= htmlspecialchars($preview) ?>" class="w-full rounded-lg bg-white" style="height:500px; border:none;"></iframe>
      <?php else: ?>
      <div class="h-72 bg-navy-700 rounded-xl flex flex-col items-center justify-center text-gray-500">
        <div class="text-4xl mb-3">📧</div>
        <p class="text-sm">Click "Preview" to see the rendered email</p>
      </div>
      <?php endif; ?>

      <!-- Tips -->
      <div class="mt-4 bg-navy-700 rounded-lg p-4">
        <h4 class="text-xs font-semibold text-orange-400 uppercase mb-2">Best Practices</h4>
        <ul class="text-xs text-gray-400 space-y-1">
          <li>• Keep subject lines under 60 characters</li>
          <li>• Lead with the most important information</li>
          <li>• Include a clear call-to-action (RFQ, call us, etc.)</li>
          <li>• Test send to yourself first using Email Templates → Test Send</li>
          <li>• Send during business hours (Mon–Sat, 9am–5pm PKT) for best open rates</li>
        </ul>
      </div>
    </div>
  </div>

  <!-- Broadcast history -->
  <div class="mt-8 card-dark p-5">
    <h3 class="font-semibold mb-4 text-orange-400">Recent Broadcasts</h3>
    <?php
    $broadcasts = Database::fetchAll("SELECT * FROM activity_log WHERE module='admin' AND action LIKE 'Broadcast email%' ORDER BY created_at DESC LIMIT 10");
    ?>
    <?php if ($broadcasts): ?>
    <table class="w-full text-sm">
      <thead><tr class="text-xs text-gray-500 border-b border-navy-500">
        <th class="text-left py-2">Date</th>
        <th class="text-left py-2">Subject / Summary</th>
      </tr></thead>
      <tbody>
        <?php foreach ($broadcasts as $b): ?>
        <tr class="border-b border-navy-600">
          <td class="py-2 text-gray-500 text-xs whitespace-nowrap"><?= date('d M Y H:i', strtotime($b['created_at'])) ?></td>
          <td class="py-2 text-gray-300 text-xs"><?= e($b['action']) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php else: ?>
    <p class="text-sm text-gray-500">No broadcasts sent yet.</p>
    <?php endif; ?>
  </div>
<script>
function insertTemplate(html) {
  document.getElementById('broadcast-body').value = html;
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
