<?php
require_once '../includes/config.php';
requireAdmin();
require_once '../includes/mailer.php';
require_once 'includes/header.php';

// ── AJAX: Send emails ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json');

    $subject   = trim($_POST['subject']   ?? '');
    $body_html = trim($_POST['body_html'] ?? '');
    $user_ids  = $_POST['user_ids'] ?? [];   // array or 'all'
    $send_all  = ($_POST['send_all'] ?? '') === '1';

    if (!$subject || !$body_html) {
        echo json_encode(['success' => false, 'message' => 'Subject and body are required.']); exit;
    }

    // Fetch recipients
    if ($send_all) {
        $stmt = $pdo->query("SELECT id, name, email FROM users WHERE is_verified=1 AND (is_disabled IS NULL OR is_disabled=0) ORDER BY name");
    } else {
        if (empty($user_ids)) {
            echo json_encode(['success' => false, 'message' => 'No users selected.']); exit;
        }
        $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
        $stmt = $pdo->prepare("SELECT id, name, email FROM users WHERE id IN ($placeholders) ORDER BY name");
        $stmt->execute(array_map('intval', $user_ids));
    }
    $recipients = $stmt->fetchAll();

    if (empty($recipients)) {
        echo json_encode(['success' => false, 'message' => 'No valid recipients found.']); exit;
    }

    $sent = 0; $failed = 0; $errors = [];

    foreach ($recipients as $u) {
        // Personalise: replace {name} placeholder
        $personal_body = str_replace(
            ['{name}', '{email}'],
            [htmlspecialchars($u['name']), htmlspecialchars($u['email'])],
            $body_html
        );

        // Wrap in StudyTrack email template
        $full_html = _st2Wrap($personal_body);

        $ok = _smtpSend2($u['email'], $u['name'], $subject, $full_html);
        if ($ok) $sent++;
        else { $failed++; $errors[] = $u['email']; }
    }

    echo json_encode([
        'success'  => true,
        'sent'     => $sent,
        'failed'   => $failed,
        'errors'   => $errors,
        'total'    => count($recipients),
    ]);
    exit;
}

// ── Fetch all users for UI ─────────────────────────────────────────────────
$users = $pdo->query("
    SELECT u.id, u.name, u.email,
           COALESCE(SUM(ss.duration_minutes),0) as total_mins,
           (SELECT COUNT(*) FROM study_sessions ss2 WHERE ss2.user_id=u.id AND ss2.date=CURDATE()) as today_sessions,
           u.created_at
    FROM users u
    LEFT JOIN study_sessions ss ON ss.user_id = u.id AND ss.date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    WHERE u.is_verified=1 AND (u.is_disabled IS NULL OR u.is_disabled=0)
    GROUP BY u.id
    ORDER BY u.name
")->fetchAll();

renderAdminHeader('📧 Bulk Mail Sender', 'mail');
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;700;800;900&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap');

:root { --font-head: 'Outfit', sans-serif; --font-body: 'Plus Jakarta Sans', sans-serif; }

.mail-wrap { max-width: 1200px; font-family: var(--font-body); padding-bottom: 60px; }

/* ── Page header ── */
.mail-ph {
  display: flex; align-items: center; gap: 16px;
  margin-bottom: 28px; animation: mrise .4s ease both;
}
.mail-ph-icon {
  width: 52px; height: 52px; border-radius: 16px;
  background: linear-gradient(135deg, #6366f1, #a855f7);
  display: flex; align-items: center; justify-content: center;
  font-size: 24px; box-shadow: 0 8px 24px rgba(99,102,241,.35);
  flex-shrink: 0;
}
.mail-ph-title { font-family: var(--font-head); font-size: 24px; font-weight: 800; color: var(--text-primary); }
.mail-ph-sub   { font-size: 13px; color: var(--text-muted); margin-top: 3px; }

/* ── Two-column layout ── */
.mail-grid {
  display: grid; grid-template-columns: 380px 1fr; gap: 20px; align-items: start;
}
@media(max-width: 960px) { .mail-grid { grid-template-columns: 1fr; } }

/* ── Card ── */
.mc {
  background: var(--bg-card); border: 1px solid var(--border);
  border-radius: 20px; overflow: hidden;
  animation: mrise .45s .05s ease both;
}
.mc-head {
  display: flex; align-items: center; justify-content: space-between;
  padding: 16px 20px; border-bottom: 1px solid var(--border);
  background: var(--bg-secondary);
}
.mc-title { font-family: var(--font-head); font-size: 14px; font-weight: 700; color: var(--text-primary); display: flex; align-items: center; gap: 8px; }
.mc-badge { background: rgba(99,102,241,.15); color: var(--accent); border-radius: 99px; padding: 3px 10px; font-size: 12px; font-weight: 700; }
.mc-body  { padding: 16px 20px; }

/* ── Search ── */
.mail-search {
  display: flex; align-items: center; gap: 10px;
  background: var(--bg-secondary); border: 1px solid var(--border);
  border-radius: 10px; padding: 9px 14px; margin-bottom: 14px;
}
.mail-search input {
  flex: 1; border: none; background: transparent; outline: none;
  font-family: var(--font-body); font-size: 13px; color: var(--text-primary);
}
.mail-search input::placeholder { color: var(--text-muted); }

/* ── Select all bar ── */
.mail-selbar {
  display: flex; align-items: center; justify-content: space-between;
  margin-bottom: 12px; padding: 10px 14px;
  background: linear-gradient(100deg, rgba(99,102,241,.1), rgba(168,85,247,.06));
  border: 1px solid rgba(99,102,241,.2); border-radius: 10px;
}
.mail-selbar-left { display: flex; align-items: center; gap: 10px; }
.mail-selbar-lbl  { font-size: 13px; font-weight: 600; color: var(--text-primary); }
.mail-sel-count   { font-size: 12px; color: var(--accent); font-weight: 700; }
.mail-selbar-btns { display: flex; gap: 6px; }
.ms-btn {
  padding: 5px 12px; border-radius: 8px; font-size: 12px; font-weight: 700;
  border: 1px solid var(--border); cursor: pointer; transition: all .15s;
  background: var(--bg-card); color: var(--text-secondary);
}
.ms-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(99,102,241,.08); }
.ms-btn.active { background: var(--accent); color: #fff; border-color: transparent; }

/* ── User list ── */
.mail-userlist { max-height: 480px; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; }
.mail-userlist::-webkit-scrollbar { width: 5px; }
.mail-userlist::-webkit-scrollbar-track { background: transparent; }
.mail-userlist::-webkit-scrollbar-thumb { background: var(--border); border-radius: 99px; }

.mu-item {
  display: flex; align-items: center; gap: 12px;
  padding: 10px 12px; border-radius: 12px; cursor: pointer;
  border: 1.5px solid transparent; transition: all .15s;
  background: var(--bg-secondary);
}
.mu-item:hover { border-color: rgba(99,102,241,.3); background: rgba(99,102,241,.06); }
.mu-item.selected { border-color: rgba(99,102,241,.5); background: rgba(99,102,241,.1); }
.mu-item.hidden { display: none; }

.mu-check {
  width: 18px; height: 18px; border-radius: 6px;
  border: 2px solid var(--border); background: var(--bg-card);
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0; transition: all .15s;
}
.mu-item.selected .mu-check { background: var(--accent); border-color: var(--accent); }
.mu-check-tick { display: none; color: #fff; font-size: 11px; font-weight: 800; }
.mu-item.selected .mu-check-tick { display: block; }

.mu-av {
  width: 36px; height: 36px; border-radius: 50%;
  background: linear-gradient(135deg, #6366f1, #a855f7);
  display: flex; align-items: center; justify-content: center;
  font-size: 14px; font-weight: 800; color: #fff; flex-shrink: 0;
}
.mu-info { flex: 1; min-width: 0; }
.mu-name  { font-size: 13px; font-weight: 600; color: var(--text-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mu-email { font-size: 11px; color: var(--text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mu-hrs   { font-size: 11px; font-weight: 700; color: var(--accent); white-space: nowrap; }

/* ── Composer ── */
.mc-composer { animation: mrise .45s .1s ease both; }

.form-group  { margin-bottom: 16px; }
.form-label  { display: block; font-size: 12px; font-weight: 700; color: var(--text-muted); letter-spacing: .5px; text-transform: uppercase; margin-bottom: 7px; }
.form-input  {
  width: 100%; box-sizing: border-box;
  background: var(--bg-secondary); border: 1px solid var(--border);
  border-radius: 10px; padding: 11px 14px;
  font-family: var(--font-body); font-size: 14px; color: var(--text-primary);
  outline: none; transition: border-color .15s;
}
.form-input:focus  { border-color: var(--accent); }
.form-input::placeholder { color: var(--text-muted); }

/* ── Toolbar ── */
.editor-toolbar {
  display: flex; flex-wrap: wrap; gap: 4px;
  padding: 10px 12px; background: var(--bg-secondary);
  border: 1px solid var(--border); border-bottom: none;
  border-radius: 10px 10px 0 0;
}
.etb { 
  min-width: 32px; height: 30px; padding: 0 8px;
  border: 1px solid var(--border); border-radius: 6px;
  background: var(--bg-card); color: var(--text-secondary);
  font-size: 12px; font-weight: 700; cursor: pointer;
  display: flex; align-items: center; justify-content: center;
  transition: all .15s; font-family: var(--font-body);
}
.etb:hover { background: var(--accent); color: #fff; border-color: transparent; }
.etb.sep { width: 1px; background: var(--border); padding: 0; pointer-events: none; margin: 0 3px; }

.editor-area {
  width: 100%; box-sizing: border-box; min-height: 260px;
  background: var(--bg-secondary); border: 1px solid var(--border);
  border-radius: 0 0 10px 10px; padding: 14px;
  font-family: var(--font-body); font-size: 14px; color: var(--text-primary);
  outline: none; line-height: 1.7; resize: vertical;
}

/* ── Preview panel ── */
.preview-wrap {
  margin-top: 16px; border: 1px solid var(--border); border-radius: 10px; overflow: hidden;
}
.preview-head {
  display: flex; align-items: center; justify-content: space-between;
  padding: 10px 14px; background: var(--bg-secondary); border-bottom: 1px solid var(--border);
  font-size: 12px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: .5px;
}
.preview-frame {
  background: #0f1117; min-height: 200px; max-height: 320px; overflow-y: auto;
  padding: 20px;
}

/* ── Placeholder tags ── */
.placeholder-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 12px; }
.ph-tag {
  padding: 4px 10px; border-radius: 99px; font-size: 11px; font-weight: 700;
  background: rgba(6,182,212,.1); border: 1px solid rgba(6,182,212,.25); color: #06b6d4;
  cursor: pointer; transition: all .15s; user-select: none;
}
.ph-tag:hover { background: rgba(6,182,212,.2); }

/* ── Templates ── */
.tpl-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 16px; }
.tpl-card {
  padding: 10px 13px; border: 1px solid var(--border); border-radius: 10px;
  cursor: pointer; transition: all .15s; background: var(--bg-secondary);
}
.tpl-card:hover { border-color: rgba(99,102,241,.4); background: rgba(99,102,241,.08); }
.tpl-name { font-size: 13px; font-weight: 700; color: var(--text-primary); }
.tpl-sub  { font-size: 11px; color: var(--text-muted); margin-top: 2px; }

/* ── Send button ── */
.send-bar {
  display: flex; align-items: center; justify-content: space-between;
  margin-top: 18px; padding-top: 16px; border-top: 1px solid var(--border);
  flex-wrap: wrap; gap: 12px;
}
.send-info { font-size: 13px; color: var(--text-muted); }
.send-info strong { color: var(--accent); }
.btn-send {
  display: inline-flex; align-items: center; gap: 10px;
  padding: 12px 28px; border: none; border-radius: 12px;
  background: linear-gradient(135deg, #6366f1, #a855f7);
  color: #fff; font-family: var(--font-head); font-size: 14px; font-weight: 700;
  cursor: pointer; transition: all .2s;
  box-shadow: 0 6px 20px rgba(99,102,241,.35);
}
.btn-send:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 10px 28px rgba(99,102,241,.45); }
.btn-send:disabled { opacity: .5; cursor: not-allowed; transform: none; }

/* ── Result overlay ── */
.result-overlay {
  position: fixed; inset: 0; z-index: 9999;
  background: rgba(0,0,0,.6); backdrop-filter: blur(6px);
  display: none; align-items: center; justify-content: center; padding: 20px;
}
.result-box {
  background: var(--bg-card); border: 1px solid var(--border);
  border-radius: 20px; padding: 36px 40px; max-width: 420px; width: 100%;
  text-align: center; animation: mrise .35s cubic-bezier(.34,1.4,.64,1);
}
.result-icon { font-size: 52px; margin-bottom: 14px; }
.result-title { font-family: var(--font-head); font-size: 22px; font-weight: 800; color: var(--text-primary); margin-bottom: 8px; }
.result-sub   { font-size: 14px; color: var(--text-muted); line-height: 1.6; margin-bottom: 22px; }
.result-stats { display: flex; gap: 12px; justify-content: center; margin-bottom: 22px; }
.result-stat  { flex: 1; background: var(--bg-secondary); border-radius: 12px; padding: 14px 10px; }
.result-stat-n { font-family: var(--font-head); font-size: 28px; font-weight: 900; }
.result-stat-l { font-size: 11px; color: var(--text-muted); font-weight: 600; margin-top: 3px; text-transform: uppercase; letter-spacing: .5px; }
.result-close {
  padding: 11px 28px; border: none; border-radius: 10px;
  background: linear-gradient(135deg, #6366f1, #a855f7);
  color: #fff; font-weight: 700; font-size: 14px; cursor: pointer;
  transition: opacity .2s;
}
.result-close:hover { opacity: .85; }

/* ── Progress bar ── */
.send-progress {
  display: none; margin-top: 14px;
  background: var(--bg-secondary); border-radius: 99px; height: 6px; overflow: hidden;
}
.send-progress-bar { height: 100%; border-radius: 99px; background: linear-gradient(90deg, #6366f1, #a855f7); width: 0%; transition: width .3s ease; }

@keyframes mrise { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: none; } }
</style>

<div class="mail-wrap">

  <!-- Page header -->
  <div class="mail-ph">
    <div class="mail-ph-icon">📧</div>
    <div>
      <div class="mail-ph-title">Bulk Mail Sender</div>
      <div class="mail-ph-sub">Select users and compose a personalized email to send directly.</div>
    </div>
  </div>

  <div class="mail-grid">

    <!-- ══ LEFT: User selector ══ -->
    <div>
      <div class="mc">
        <div class="mc-head">
          <div class="mc-title">👥 Select Recipients</div>
          <div class="mc-badge" id="selBadge">0 selected</div>
        </div>
        <div class="mc-body">

          <!-- Search -->
          <div class="mail-search">
            <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" style="color:var(--text-muted);flex-shrink:0"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
            <input type="text" id="userSearch" placeholder="Search by name or email…" oninput="filterUsers(this.value)">
          </div>

          <!-- Select all bar -->
          <div class="mail-selbar">
            <div class="mail-selbar-left">
              <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
                <div class="mu-check" id="allCheck" onclick="toggleAll()">
                  <span class="mu-check-tick" id="allTick">✓</span>
                </div>
                <span class="mail-selbar-lbl">Select All</span>
              </label>
              <span class="mail-sel-count" id="selCount">0 / <?= count($users) ?></span>
            </div>
            <div class="mail-selbar-btns">
              <button class="ms-btn" onclick="selectAll()">All</button>
              <button class="ms-btn" onclick="selectNone()">None</button>
            </div>
          </div>

          <!-- User list -->
          <div class="mail-userlist" id="userList">
            <?php foreach ($users as $u):
              $hrs  = floor($u['total_mins'] / 60);
              $mins = $u['total_mins'] % 60;
              $init = strtoupper(mb_substr($u['name'], 0, 1));
              $colors = ['#6366f1','#a855f7','#06b6d4','#10b981','#f59e0b','#ef4444','#ec4899'];
              $col = $colors[crc32($u['name']) % count($colors)];
            ?>
            <div class="mu-item" data-id="<?= $u['id'] ?>" data-name="<?= htmlspecialchars(strtolower($u['name'])) ?>" data-email="<?= htmlspecialchars(strtolower($u['email'])) ?>" onclick="toggleUser(this)">
              <div class="mu-check"><span class="mu-check-tick">✓</span></div>
              <div class="mu-av" style="background:linear-gradient(135deg,<?= $col ?>,<?= $col ?>aa)"><?= $init ?></div>
              <div class="mu-info">
                <div class="mu-name"><?= htmlspecialchars($u['name']) ?></div>
                <div class="mu-email"><?= htmlspecialchars($u['email']) ?></div>
              </div>
              <div class="mu-hrs"><?= $hrs ?>h <?= $mins ?>m</div>
            </div>
            <?php endforeach; ?>
          </div>

        </div>
      </div>
    </div>

    <!-- ══ RIGHT: Composer ══ -->
    <div class="mc mc-composer">
      <div class="mc-head">
        <div class="mc-title">✍️ Compose Email</div>
        <div style="font-size:12px;color:var(--text-muted)">Use <code style="background:var(--bg-secondary);padding:2px 6px;border-radius:4px;color:var(--accent)">{name}</code> for personalization</div>
      </div>
      <div class="mc-body">

        <!-- Templates -->
        <div class="form-group">
          <div class="form-label">Quick Templates</div>
          <div class="tpl-grid">
            <div class="tpl-card" onclick="loadTemplate('motivation')">
              <div class="tpl-name">🔥 Motivation Boost</div>
              <div class="tpl-sub">Encourage students to study</div>
            </div>
            <div class="tpl-card" onclick="loadTemplate('exam_reminder')">
              <div class="tpl-name">📅 Exam Reminder</div>
              <div class="tpl-sub">Upcoming exam notification</div>
            </div>
            <div class="tpl-card" onclick="loadTemplate('feature_update')">
              <div class="tpl-name">🆕 Feature Update</div>
              <div class="tpl-sub">Announce new features</div>
            </div>
            <div class="tpl-card" onclick="loadTemplate('streak_reminder')">
              <div class="tpl-name">⚡ Streak Alert</div>
              <div class="tpl-sub">Don't break your streak!</div>
            </div>
          </div>
        </div>

        <!-- Subject -->
        <div class="form-group">
          <label class="form-label">Subject Line</label>
          <input type="text" class="form-input" id="emailSubject" placeholder="Enter email subject…" maxlength="150">
        </div>

        <!-- Placeholders -->
        <div class="form-group">
          <div class="form-label">Available Placeholders</div>
          <div class="placeholder-tags">
            <div class="ph-tag" onclick="insertPlaceholder('{name}')">👤 {name}</div>
            <div class="ph-tag" onclick="insertPlaceholder('{email}')">📧 {email}</div>
          </div>
        </div>

        <!-- Toolbar + Editor -->
        <div class="form-group">
          <div class="form-label">Email Body (HTML Supported)</div>
          <div class="editor-toolbar">
            <button class="etb" onclick="fmt('bold')" title="Bold"><b>B</b></button>
            <button class="etb" onclick="fmt('italic')" title="Italic"><i>I</i></button>
            <button class="etb" onclick="fmt('underline')" title="Underline"><u>U</u></button>
            <div class="etb sep"></div>
            <button class="etb" onclick="fmtHeading()" title="Heading">H2</button>
            <button class="etb" onclick="fmtList()" title="List">≡</button>
            <div class="etb sep"></div>
            <button class="etb" onclick="fmtColor('#6366f1')" title="Purple" style="background:#6366f1;border-color:#6366f1;color:#fff">A</button>
            <button class="etb" onclick="fmtColor('#10b981')" title="Green"  style="background:#10b981;border-color:#10b981;color:#fff">A</button>
            <button class="etb" onclick="fmtColor('#f59e0b')" title="Amber"  style="background:#f59e0b;border-color:#f59e0b;color:#fff">A</button>
            <button class="etb" onclick="fmtColor('#ef4444')" title="Red"    style="background:#ef4444;border-color:#ef4444;color:#fff">A</button>
            <div class="etb sep"></div>
            <button class="etb" onclick="fmtLink()" title="Link">🔗</button>
            <button class="etb" onclick="fmtHr()" title="Divider">—</button>
            <div class="etb sep"></div>
            <button class="etb" onclick="togglePreview()" title="Preview" id="previewBtn">👁️</button>
          </div>
          <div class="editor-area" id="emailBody" contenteditable="true" 
               data-placeholder="Write your email content here…
Use {name} to personalize with the recipient's name.

Example:
Hi {name},

We noticed you've been working hard on your A/L studies. Keep going! 💪"
               oninput="onBodyInput()"></div>
        </div>

        <!-- Preview -->
        <div class="preview-wrap" id="previewWrap" style="display:none">
          <div class="preview-head">
            <span>📧 Email Preview</span>
            <span style="font-size:11px;color:var(--text-muted)">As seen in inbox</span>
          </div>
          <div class="preview-frame" id="previewFrame"></div>
        </div>

        <!-- Send bar -->
        <div class="send-bar">
          <div class="send-info">
            Sending to: <strong id="sendToCount">0</strong> user(s)
          </div>
          <button class="btn-send" id="sendBtn" onclick="sendEmails()" disabled>
            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
            Send Email
          </button>
        </div>

        <div class="send-progress" id="sendProgress">
          <div class="send-progress-bar" id="sendProgressBar"></div>
        </div>

      </div>
    </div>

  </div>
</div>

<!-- Result overlay -->
<div class="result-overlay" id="resultOverlay">
  <div class="result-box">
    <div class="result-icon" id="resultIcon">✅</div>
    <div class="result-title" id="resultTitle">Emails Sent!</div>
    <div class="result-sub" id="resultSub">Your message has been delivered.</div>
    <div class="result-stats" id="resultStats" style="display:none">
      <div class="result-stat">
        <div class="result-stat-n" id="rsSent" style="color:#10b981">0</div>
        <div class="result-stat-l">Sent</div>
      </div>
      <div class="result-stat">
        <div class="result-stat-n" id="rsFailed" style="color:#ef4444">0</div>
        <div class="result-stat-l">Failed</div>
      </div>
      <div class="result-stat">
        <div class="result-stat-n" id="rsTotal" style="color:var(--accent)">0</div>
        <div class="result-stat-l">Total</div>
      </div>
    </div>
    <button class="result-close" onclick="closeResult()">Done</button>
  </div>
</div>

<script>
// ── State ──────────────────────────────────────────────────────────────────
var selected = new Set();
var totalUsers = <?= count($users) ?>;

// ── Placeholder insert ──────────────────────────────────────────────────────
function insertPlaceholder(ph) {
  var ed = document.getElementById('emailBody');
  ed.focus();
  document.execCommand('insertText', false, ph);
  onBodyInput();
}

// ── User selection ──────────────────────────────────────────────────────────
function toggleUser(el) {
  var id = el.getAttribute('data-id');
  if (selected.has(id)) {
    selected.delete(id);
    el.classList.remove('selected');
  } else {
    selected.add(id);
    el.classList.add('selected');
  }
  updateSelUI();
}

function selectAll() {
  document.querySelectorAll('.mu-item:not(.hidden)').forEach(function(el) {
    selected.add(el.getAttribute('data-id'));
    el.classList.add('selected');
  });
  updateSelUI();
}
function selectNone() {
  selected.clear();
  document.querySelectorAll('.mu-item').forEach(function(el) { el.classList.remove('selected'); });
  updateSelUI();
}
function toggleAll() {
  if (selected.size === totalUsers) selectNone(); else selectAll();
}

function updateSelUI() {
  var cnt = selected.size;
  document.getElementById('selBadge').textContent   = cnt + ' selected';
  document.getElementById('selCount').textContent   = cnt + ' / ' + totalUsers;
  document.getElementById('sendToCount').textContent = cnt;
  // all-check visual
  var ac = document.getElementById('allCheck');
  var at = document.getElementById('allTick');
  if (cnt === totalUsers && totalUsers > 0) {
    ac.style.background = 'var(--accent)'; ac.style.borderColor = 'var(--accent)'; at.style.display = 'block';
  } else {
    ac.style.background = ''; ac.style.borderColor = ''; at.style.display = 'none';
  }
  updateSendBtn();
}

// ── Search ──────────────────────────────────────────────────────────────────
function filterUsers(q) {
  q = q.toLowerCase().trim();
  document.querySelectorAll('.mu-item').forEach(function(el) {
    var name  = el.getAttribute('data-name');
    var email = el.getAttribute('data-email');
    el.classList.toggle('hidden', q && !name.includes(q) && !email.includes(q));
  });
}

// ── Editor helpers ──────────────────────────────────────────────────────────
function fmt(cmd) { document.execCommand(cmd, false, null); document.getElementById('emailBody').focus(); onBodyInput(); }
function fmtColor(c) { document.execCommand('foreColor', false, c); document.getElementById('emailBody').focus(); onBodyInput(); }
function fmtHeading() {
  var ed = document.getElementById('emailBody');
  ed.focus();
  document.execCommand('insertHTML', false, '<h2 style="color:#f8fafc;font-size:18px;font-weight:700;margin:16px 0 8px;">Heading</h2>');
  onBodyInput();
}
function fmtList() {
  document.execCommand('insertUnorderedList', false, null);
  document.getElementById('emailBody').focus(); onBodyInput();
}
function fmtLink() {
  var url = prompt('Enter URL:', 'https://');
  if (url) { document.execCommand('createLink', false, url); onBodyInput(); }
}
function fmtHr() {
  document.execCommand('insertHTML', false, '<hr style="border:none;border-top:1px solid rgba(255,255,255,0.1);margin:18px 0;">');
  onBodyInput();
}

function onBodyInput() {
  updateSendBtn();
  if (document.getElementById('previewWrap').style.display !== 'none') renderPreview();
}

function updateSendBtn() {
  var hasRecipients = selected.size > 0;
  var hasSubject    = document.getElementById('emailSubject').value.trim().length > 0;
  var hasBody       = document.getElementById('emailBody').innerHTML.trim().replace(/<br\s*\/?>/gi,'').length > 5;
  document.getElementById('sendBtn').disabled = !(hasRecipients && hasSubject && hasBody);
}

// ── Preview ──────────────────────────────────────────────────────────────────
function togglePreview() {
  var pw = document.getElementById('previewWrap');
  var shown = pw.style.display !== 'none';
  pw.style.display = shown ? 'none' : 'block';
  if (!shown) renderPreview();
}
function renderPreview() {
  var body = document.getElementById('emailBody').innerHTML
    .replace(/\{name\}/g, '<strong style="color:#a5b4fc">Kasun Perera</strong>')
    .replace(/\{email\}/g, 'kasun@example.com');
  document.getElementById('previewFrame').innerHTML =
    '<div style="color:#94a3b8;font-size:14px;line-height:1.7;font-family:Arial,sans-serif">' + body + '</div>';
}

// ── Templates ──────────────────────────────────────────────────────────────
var templates = {
  motivation: {
    subject: '🔥 Keep Going, {name}! Your A/L Journey Continues',
    body: '<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 12px;">Hey {name}, you\'re doing amazing! 💪</h2><p style="color:#94a3b8;line-height:1.8;margin:0 0 16px;">We\'ve been watching your study progress on <strong style="color:#f8fafc;">StudyTrack</strong> and we just want to say — <strong style="color:#a5b4fc;">keep it up!</strong> Every session you log brings you one step closer to your A/L goals.</p><div style="background:rgba(99,102,241,0.12);border:1px solid rgba(99,102,241,0.25);border-radius:12px;padding:18px;margin:16px 0;"><p style="color:#94a3b8;font-size:14px;margin:0;line-height:2;">📚 &nbsp;Log a study session today<br>🔥 &nbsp;Maintain your study streak<br>🎯 &nbsp;Check your weekly targets<br>📊 &nbsp;Review your progress report</p></div><p style="color:#94a3b8;line-height:1.8;margin:0;">Remember — <strong style="color:#f8fafc;">consistent effort</strong> beats last-minute cramming every time. You\'ve got this! 🌟</p>'
  },
  exam_reminder: {
    subject: '📅 Important: A/L Exam Reminder for {name}',
    body: '<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 12px;">📅 A/L Exam Reminder</h2><p style="color:#94a3b8;line-height:1.8;margin:0 0 16px;">Hi <strong style="color:#f8fafc;">{name}</strong>,<br>This is a friendly reminder that your <strong style="color:#a5b4fc;">A/L Examinations</strong> are approaching. Now is the time to intensify your preparation!</p><div style="background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.25);border-radius:12px;padding:18px;margin:16px 0;"><p style="color:#94a3b8;font-size:14px;font-weight:600;margin:0 0 10px;">⚡ Action Plan:</p><p style="color:#94a3b8;font-size:13px;margin:0;line-height:2.2;">📖 &nbsp;Review all past papers<br>⏱️ &nbsp;Practice time management<br>🗒️ &nbsp;Revise key notes and formulas<br>😴 &nbsp;Ensure proper sleep and diet</p></div><p style="color:#94a3b8;line-height:1.8;margin:0;">Log your daily sessions on StudyTrack to stay on track. Best of luck, <strong style="color:#f8fafc;">{name}</strong>! 🍀</p>'
  },
  feature_update: {
    subject: '🆕 New Features on StudyTrack — Check Them Out!',
    body: '<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 12px;">🆕 What\'s New on StudyTrack</h2><p style="color:#94a3b8;line-height:1.8;margin:0 0 16px;">Hi <strong style="color:#f8fafc;">{name}</strong>,<br>We\'ve been busy improving StudyTrack to make your study experience even better!</p><div style="background:rgba(16,185,129,0.08);border:1px solid rgba(16,185,129,0.25);border-radius:12px;padding:18px;margin:16px 0;"><p style="color:#94a3b8;font-size:14px;font-weight:700;margin:0 0 12px;color:#6ee7b7;">✨ Latest Updates:</p><p style="color:#94a3b8;font-size:13px;margin:0;line-height:2.2;">🔥 &nbsp;<strong style="color:#f8fafc;">Enhanced Countdown</strong> — Flip card for detailed timer<br>📊 &nbsp;<strong style="color:#f8fafc;">Improved Analytics</strong> — Better progress tracking<br>🏫 &nbsp;<strong style="color:#f8fafc;">Class Hours</strong> — Track attendance easily<br>🎯 &nbsp;<strong style="color:#f8fafc;">Weekly Targets</strong> — Set and hit subject goals</p></div><p style="color:#94a3b8;line-height:1.8;margin:0;">Log in today and explore all the new features. Happy studying! 📚</p>'
  },
  streak_reminder: {
    subject: '⚡ {name}, Don\'t Break Your Study Streak!',
    body: '<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 12px;">⚡ Your Streak is on the Line, {name}!</h2><p style="color:#94a3b8;line-height:1.8;margin:0 0 16px;">We noticed you haven\'t logged a study session today yet. <strong style="color:#fbbf24;">Your streak is in danger!</strong> 🔥</p><div style="background:rgba(245,158,11,0.08);border:1px solid rgba(245,158,11,0.3);border-radius:12px;padding:20px;text-align:center;margin:16px 0;"><div style="font-size:42px;margin-bottom:8px;">🔥</div><div style="color:#fcd34d;font-size:18px;font-weight:800;">Keep Your Streak Alive!</div><div style="color:#94a3b8;font-size:13px;margin-top:6px;">Even a 15-minute session counts</div></div><p style="color:#94a3b8;line-height:1.8;margin:0;">Log even a small study session today to maintain your streak. Consistency is the key to A/L success! 💪</p>'
  }
};

function loadTemplate(key) {
  var tpl = templates[key];
  if (!tpl) return;
  document.getElementById('emailSubject').value = tpl.subject;
  document.getElementById('emailBody').innerHTML = tpl.body;
  updateSendBtn();
}

// ── Send ──────────────────────────────────────────────────────────────────
async function sendEmails() {
  if (selected.size === 0) return;
  if (!confirm('Send email to ' + selected.size + ' user(s)? This cannot be undone.')) return;

  var btn = document.getElementById('sendBtn');
  btn.disabled = true;
  btn.innerHTML = '<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24" style="animation:spin 1s linear infinite"><path d="M21 12a9 9 0 1 1-9-9"/></svg> Sending…';

  var prog = document.getElementById('sendProgress');
  var bar  = document.getElementById('sendProgressBar');
  prog.style.display = 'block';

  // Animate progress
  var pct = 0;
  var pTimer = setInterval(function() {
    pct = Math.min(pct + Math.random() * 8, 85);
    bar.style.width = pct + '%';
  }, 300);

  var fd = new FormData();
  fd.append('subject',   document.getElementById('emailSubject').value.trim());
  fd.append('body_html', document.getElementById('emailBody').innerHTML);
  fd.append('send_all',  selected.size === totalUsers ? '1' : '0');
  selected.forEach(function(id) { fd.append('user_ids[]', id); });

  try {
    var res  = await fetch(window.location.href, { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest' }, body: fd });
    var data = await res.json();

    clearInterval(pTimer);
    bar.style.width = '100%';
    setTimeout(function() { prog.style.display = 'none'; bar.style.width = '0%'; }, 600);

    if (data.success) {
      document.getElementById('resultIcon').textContent  = data.failed === 0 ? '✅' : '⚠️';
      document.getElementById('resultTitle').textContent  = data.failed === 0 ? 'All Emails Sent!' : 'Sent with Some Failures';
      document.getElementById('resultSub').textContent   = data.failed === 0
        ? 'All messages delivered successfully.'
        : data.failed + ' email(s) failed to send. Check the error log.';
      document.getElementById('rsSent').textContent   = data.sent;
      document.getElementById('rsFailed').textContent = data.failed;
      document.getElementById('rsTotal').textContent  = data.total;
      document.getElementById('resultStats').style.display = 'flex';
      document.getElementById('resultOverlay').style.display = 'flex';
    } else {
      alert('Error: ' + (data.message || 'Unknown error'));
    }
  } catch(e) {
    clearInterval(pTimer);
    alert('Network error. Please try again.');
  }

  btn.disabled = false;
  btn.innerHTML = '<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg> Send Email';
  updateSendBtn();
}

function closeResult() {
  document.getElementById('resultOverlay').style.display = 'none';
}

// Spin animation for loader
var st = document.createElement('style');
st.textContent = '@keyframes spin{to{transform:rotate(360deg)}}';
document.head.appendChild(st);

// Subject input also triggers button update
document.getElementById('emailSubject').addEventListener('input', updateSendBtn);

// Editor placeholder
var ed = document.getElementById('emailBody');
ed.addEventListener('focus', function() { if (!this.innerHTML.trim()) this.classList.add('focused'); });
ed.addEventListener('blur',  function() { this.classList.remove('focused'); });

// Initial state
updateSelUI();
</script>

<?php
require_once __DIR__ . '/includes/footer.php';
renderAdminFooter();
?>