Files
imf-sms-dashboard/web/send-now.html
T
2026-06-06 00:03:51 +01:00

382 lines
16 KiB
HTML

<!doctype html>
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Send SMS Now — IMFestival SMS Dashboard</title>
<link href="assets/vendor/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet"
crossorigin="anonymous">
<link href="assets/css/dashboard.css" rel="stylesheet">
<link href="assets/css/chat.css" rel="stylesheet">
</head>
<body>
<!-- ─── Mobile top bar ─── -->
<div class="topbar">
<button class="hamburger" data-bs-toggle="offcanvas" data-bs-target="#mobileSidebar" aria-label="Open menu">
<i class="fa-solid fa-bars"></i>
</button>
<span style="font-weight:600;font-size:0.95rem;">SMS Dashboard</span>
</div>
<!-- ─── Mobile offcanvas sidebar ─── -->
<div class="offcanvas offcanvas-start" tabindex="-1" id="mobileSidebar">
<div class="offcanvas-header">
<div class="brand"
style="border:none;margin:0;padding:0;flex-direction:column;align-items:flex-start;gap:0.5rem;">
<span>IMFestival SMS Dashboard</span>
</div>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close"></button>
</div>
<div class="offcanvas-body p-3">
<nav class="d-flex flex-column gap-1">
<a href="index.html" class="nav-link-custom">
<i class="fa-solid fa-house fa-fw"></i>
Home
</a>
<a href="attendees.html" class="nav-link-custom">
<i class="fa-solid fa-users fa-fw"></i>
Attendees
</a>
<a href="templates.html" class="nav-link-custom">
<i class="fa-solid fa-comment-sms fa-fw"></i>
SMS Templates
</a>
<a href="schedule.html" class="nav-link-custom">
<i class="fa-solid fa-calendar-days fa-fw"></i>
Schedule
</a>
<a href="delivery-log.html" class="nav-link-custom">
<i class="fa-solid fa-list-check fa-fw"></i>
Delivery Log
</a>
</nav>
</div>
</div>
<!-- ─── Desktop sidebar ─── -->
<div class="sidebar">
<div class="brand">
<span style="margin: 0 auto;">IMFestival SMS Dashboard</span>
</div>
<nav class="d-flex flex-column gap-1 mt-2">
<a href="index.html" class="nav-link-custom">
<i class="fa-solid fa-house fa-fw"></i>
Home
</a>
<a href="attendees.html" class="nav-link-custom">
<i class="fa-solid fa-users fa-fw"></i>
Attendees
</a>
<a href="templates.html" class="nav-link-custom">
<i class="fa-solid fa-comment-sms fa-fw"></i>
SMS Templates
</a>
<a href="schedule.html" class="nav-link-custom">
<i class="fa-solid fa-calendar-days fa-fw"></i>
Schedule
</a>
<a href="delivery-log.html" class="nav-link-custom">
<i class="fa-solid fa-list-check fa-fw"></i>
Delivery Log
</a>
</nav>
<div class="mt-auto pt-3" style="border-top:1px solid var(--border);">
<div class="nav-link-custom" style="cursor:default;">
<i class="fa-solid fa-circle-user fa-fw"></i>
<span style="font-size:0.82rem;">Admin</span>
</div>
</div>
</div>
<!-- ─── Main content ─── -->
<div class="main">
<div class="main-inner">
<div id="sandboxBanner" class="alert alert-warning"
style="display:none;font-size:0.85rem;font-weight:600;text-align:center;">
<i class="fa-solid fa-flask me-1"></i> Sandbox mode is active — texts are tagged as a test and excluded from
cost calculations.
</div>
<div class="page-header d-flex align-items-center gap-3">
<a href="index.html" class="btn btn-sm btn-secondary">
<i class="fa-solid fa-arrow-left me-1"></i> Back
</a>
<div>
<h1>Send SMS Now</h1>
<p>Compose and send a one-off message to your attendees instantly.</p>
</div>
</div>
<div class="row g-4">
<!-- Compose card -->
<div class="col-12 col-md-7">
<div class="card p-4">
<h2 class="section-title mb-4">Compose</h2>
<label class="form-label text-muted" style="font-size:0.82rem;">Recipients</label>
<select class="form-select mb-3" id="recipients">
<option value="all" data-count="0">Loading attendees…</option>
</select>
<label class="form-label text-muted" style="font-size:0.82rem;">Message</label>
<select class="form-select mb-2" id="templatePicker">
<option value="">— Custom message —</option>
</select>
<textarea id="message" class="form-control mb-1" rows="5" maxlength="160"
placeholder="Type your message…"></textarea>
<small id="charCount" class="text-muted d-block mb-2">0/160 characters</small>
<div class="d-flex flex-wrap gap-1 mb-4">
<span class="text-muted" style="font-size:0.75rem;align-self:center;">Insert:</span>
<button type="button" class="btn btn-sm"
style="font-size:0.75rem;padding:0.15em 0.6em;background:rgba(79,142,247,0.12);color:var(--accent);border:1px solid rgba(79,142,247,0.3);border-radius:6px;"
onclick="insertPlaceholder('{name}')">{name}</button>
<button type="button" class="btn btn-sm"
style="font-size:0.75rem;padding:0.15em 0.6em;background:rgba(79,142,247,0.12);color:var(--accent);border:1px solid rgba(79,142,247,0.3);border-radius:6px;"
onclick="insertPlaceholder('{workshop}')">{workshop}</button>
<button type="button" class="btn btn-sm"
style="font-size:0.75rem;padding:0.15em 0.6em;background:rgba(79,142,247,0.12);color:var(--accent);border:1px solid rgba(79,142,247,0.3);border-radius:6px;"
onclick="insertPlaceholder('{workshop_time}')">{workshop_time}</button>
</div>
<button class="btn btn-primary w-100" id="sendBtn" disabled>
<i class="fa-solid fa-paper-plane me-2"></i>
Send to <span id="recipientCount">0</span> attendees
</button>
<div id="sendResult" class="mt-3" style="display:none;"></div>
</div>
</div>
<!-- Preview card -->
<div class="col-12 col-md-5">
<div class="card p-4">
<h2 class="section-title mb-4">Preview</h2>
<section id="previewSection" style="visibility:hidden;">
<div class="from-them" id="preview"></div>
</section>
<p id="previewPlaceholder" class="text-muted" style="font-size:0.85rem;">Your message preview will appear
here as you type.</p>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
crossorigin="anonymous"></script>
<script>
const SEND_MAX = 160;
// GSM-7 basic + extended character set
const GSM7 = new Set('@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà€[]{}\\^|~');
const GSM7_EXTENDED = new Set('€[]{}\\^|~');
function smsEncoding(text) {
const isUnicode = [...text].some(c => !GSM7.has(c));
const limit = isUnicode ? 70 : 160;
const length = isUnicode ? text.length : [...text].reduce((n, c) => n + (GSM7_EXTENDED.has(c) ? 2 : 1), 0);
return { length, limit, isUnicode };
}
const msgEl = document.getElementById('message');
const countEl = document.getElementById('charCount');
const previewEl = document.getElementById('preview');
const sectionEl = document.getElementById('previewSection');
const placeholderEl = document.getElementById('previewPlaceholder');
const sendBtn = document.getElementById('sendBtn');
const countSpan = document.getElementById('recipientCount');
const recipientsSel = document.getElementById('recipients');
const resultEl = document.getElementById('sendResult');
// ── Populate recipients from API ───────────────────────────
async function loadRecipients() {
try {
const [attData, wsData] = await Promise.all([
fetch('/api/attendees.php').then(r => r.json()),
fetch('/api/workshops.php').then(r => r.json()),
]);
const total = attData.total ?? 0;
const workshops = wsData.workshops ?? [];
const opts = [`<option value="all" data-count="${total}">All attendees (${total})</option>`];
// Group sessions by workshop name (case-insensitive)
const groups = {};
workshops.forEach(ws => {
const key = ws.workshop_name.toLowerCase();
if (!groups[key]) groups[key] = { label: ws.workshop_name, sessions: [] };
groups[key].sessions.push(ws);
});
const fmtTime = ws => ws.workshop_time
? new Date(ws.workshop_time.replace(' ', 'T')).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })
: '(no time)';
Object.values(groups).forEach(({ label, sessions }) => {
if (sessions.length === 1) {
const ws = sessions[0];
opts.push(`<option value="workshop:${ws.id}" data-count="${ws.attendee_count}">${esc(label)}${fmtTime(ws)} (${ws.attendee_count})</option>`);
} else {
opts.push(`<optgroup label="${esc(label)}">`);
sessions.forEach(ws => {
opts.push(`<option value="workshop:${ws.id}" data-count="${ws.attendee_count}">${fmtTime(ws)} (${ws.attendee_count})</option>`);
});
opts.push(`</optgroup>`);
}
});
recipientsSel.innerHTML = opts.join('');
updateCount();
} catch {
recipientsSel.innerHTML = '<option value="all" data-count="0">Could not load recipients</option>';
}
}
function updateCount() {
const selected = recipientsSel.options[recipientsSel.selectedIndex];
countSpan.textContent = selected?.dataset.count ?? '0';
}
recipientsSel.addEventListener('change', updateCount);
// ── Message compose ───────────────────────────────────────
function previewText(raw) {
return raw
.replace(/\{name\}/gi, 'Jordan')
.replace(/\{first[_ ]name\}/gi, 'Jordan')
.replace(/\{workshop\}/gi, 'Axe Throwing')
.replace(/\{workshop_time\}/gi, '13:30');
}
function insertPlaceholder(text) {
const start = msgEl.selectionStart;
const end = msgEl.selectionEnd;
const val = msgEl.value;
msgEl.value = val.slice(0, start) + text + val.slice(end);
msgEl.selectionStart = msgEl.selectionEnd = start + text.length;
msgEl.focus();
msgEl.dispatchEvent(new Event('input'));
}
msgEl.addEventListener('input', function () {
const val = this.value;
const { length, limit, isUnicode } = smsEncoding(val);
const remaining = limit - length;
countEl.innerHTML = `${length}/${limit} characters${isUnicode ? ' &nbsp;<span style="color:#f87171;font-size:0.8em;"><i class="fa-solid fa-triangle-exclamation"></i> Unicode encoding — limit reduced to 70</span>' : ''}`;
countEl.className = `d-block mb-2 ${remaining <= 10 ? (remaining <= 0 ? 'text-danger' : 'text-warning') : 'text-muted'}`;
const empty = val.trim() === '';
sectionEl.style.visibility = empty ? 'hidden' : 'visible';
placeholderEl.style.display = empty ? '' : 'none';
previewEl.textContent = empty ? '' : previewText(val);
sendBtn.disabled = empty;
resultEl.style.display = 'none';
});
// ── Send ───────────────────────────────────────────────────
function esc(str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
sendBtn.addEventListener('click', async () => {
const message = msgEl.value.trim();
if (!message) return;
const selVal = recipientsSel.value;
const isAll = selVal === 'all';
const wsId = isAll ? null : parseInt(selVal.split(':')[1]);
sendBtn.disabled = true;
sendBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i>Sending…';
resultEl.style.display = 'none';
try {
const selectedTemplateId = templatePicker.value ? parseInt(templatePicker.value) : null;
const payload = {
recipient_scope: isAll ? 'all' : 'workshop',
};
if (selectedTemplateId) {
payload.template_id = selectedTemplateId;
} else {
payload.message = message;
}
if (!isAll) payload.workshop_session_id = wsId;
const res = await fetch('/api/send-now.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error ?? 'Unknown error');
resultEl.style.display = '';
resultEl.innerHTML = `
<div style="background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.3);border-radius:8px;padding:0.75rem 1rem;color:#4ade80;font-size:0.9rem;">
<i class="fa-solid fa-circle-check me-2"></i>
Sent to ${data.sent} recipient${data.sent !== 1 ? 's' : ''}.
</div>`;
msgEl.value = '';
msgEl.dispatchEvent(new Event('input'));
} catch (err) {
resultEl.style.display = '';
resultEl.innerHTML = `
<div style="background:rgba(220,53,69,0.1);border:1px solid rgba(220,53,69,0.3);border-radius:8px;padding:0.75rem 1rem;color:#f87171;font-size:0.9rem;">
<i class="fa-solid fa-circle-xmark me-2"></i>${esc(err.message)}
</div>`;
} finally {
sendBtn.disabled = msgEl.value.trim() === '';
sendBtn.innerHTML = '<i class="fa-solid fa-paper-plane me-2"></i>Send to <span id="recipientCount">' + countSpan.textContent + '</span> attendees';
}
});
loadRecipients();
// ── Template picker ───────────────────────────────────────
const templatePicker = document.getElementById('templatePicker');
let templateBodies = {}; // id → body
async function loadTemplatePicker() {
try {
const data = await fetch('/api/templates.php').then(r => r.json());
const templates = data.templates ?? [];
templateBodies = {};
templates.forEach(t => { templateBodies[t.id] = t.body; });
templatePicker.innerHTML = '<option value="">— Custom message —</option>'
+ templates.map(t => `<option value="${t.id}">${esc(t.name)}</option>`).join('');
} catch {
// leave the default option in place
}
}
templatePicker.addEventListener('change', () => {
const body = templateBodies[templatePicker.value];
if (body !== undefined) {
msgEl.value = body;
msgEl.dispatchEvent(new Event('input'));
msgEl.focus();
}
});
loadTemplatePicker();
</script>
<script>
(async function () {
try {
const d = await fetch('/api/admin.php').then(r => r.json());
document.getElementById('sandboxBanner').style.display = d.sandbox_mode ? '' : 'none';
} catch { }
}());
</script>
</body>
</html>