chore: move js to single file
This commit is contained in:
+2
-133
@@ -178,140 +178,9 @@
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="assets/js/nav.js"></script>
|
||||
<script src="assets/js/app.js"></script>
|
||||
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
// ─── Load admin state ────────────────────────────────────────────────────────
|
||||
|
||||
async function loadAdmin() {
|
||||
try {
|
||||
const r = await fetch('/api/admin.php', { redirect: 'manual' });
|
||||
if (r.type === 'opaqueredirect') { window.location.reload(); return; }
|
||||
if (!r.ok) { window.location.replace('index.html'); return; }
|
||||
const data = await r.json();
|
||||
|
||||
if (!data.is_admin) {
|
||||
window.location.replace('index.html');
|
||||
return;
|
||||
}
|
||||
|
||||
document.querySelectorAll('.admin-nav-link').forEach(el => el.classList.remove('d-none'));
|
||||
const name = data.name || data.username;
|
||||
if (name) {
|
||||
document.querySelectorAll('.nav-username').forEach(el => { el.textContent = name; });
|
||||
}
|
||||
|
||||
document.getElementById('sandboxToggle').checked = data.sandbox_mode;
|
||||
document.getElementById('sandboxBanner').style.display = data.sandbox_mode ? '' : 'none';
|
||||
|
||||
document.getElementById('count-log').textContent = data.delivery_log_total ?? '—';
|
||||
document.getElementById('count-attendees').textContent = data.attendees ?? '—';
|
||||
document.getElementById('count-templates').textContent = data.templates ?? '—';
|
||||
document.getElementById('count-schedules').textContent = data.schedules ?? '—';
|
||||
} catch (e) {
|
||||
showResult('Failed to load admin data: ' + e.message, 'danger');
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Sandbox toggle ──────────────────────────────────────────────────────────
|
||||
|
||||
document.getElementById('sandboxToggle').addEventListener('change', async () => {
|
||||
try {
|
||||
const data = await fetch('/api/admin.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'toggle_sandbox' }),
|
||||
}).then(r => r.json());
|
||||
document.getElementById('sandboxToggle').checked = data.sandbox_mode;
|
||||
document.getElementById('sandboxBanner').style.display = data.sandbox_mode ? '' : 'none';
|
||||
showResult(`Sandbox mode ${data.sandbox_mode ? 'enabled' : 'disabled'}.`, 'success');
|
||||
} catch (e) {
|
||||
showResult('Failed to toggle sandbox mode: ' + e.message, 'danger');
|
||||
await loadAdmin(); // revert toggle visual state
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Mark all as sandbox ─────────────────────────────────────────────────────
|
||||
|
||||
async function markAllSandbox() {
|
||||
if (!confirm('Mark ALL existing delivery log entries as sandbox?\n\nThey will be excluded from cost calculations and success rate on the dashboard.')) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch('/api/admin.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'mark_all_sandbox' }),
|
||||
});
|
||||
if (!res.ok) throw new Error((await res.json()).error ?? 'Failed');
|
||||
showResult('All sends marked as sandbox.', 'success');
|
||||
loadAdmin();
|
||||
} catch (e) {
|
||||
showResult('Failed: ' + e.message, 'danger');
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Purge ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const PURGE_LABELS = {
|
||||
delivery_log: 'all delivery log entries',
|
||||
attendees: 'all attendees, registrations and workshops',
|
||||
templates: 'all SMS templates',
|
||||
schedules: 'all scheduled rules',
|
||||
};
|
||||
|
||||
async function purge(target, useDateFilter = false) {
|
||||
const body = { action: 'purge', target };
|
||||
|
||||
if (useDateFilter) {
|
||||
const before = document.getElementById('purgeBefore').value;
|
||||
if (!before) {
|
||||
alert('Please select a date first.');
|
||||
return;
|
||||
}
|
||||
if (!confirm(`Purge all delivery log entries before ${before}?\n\nThis cannot be undone.`)) {
|
||||
return;
|
||||
}
|
||||
body.before = before;
|
||||
} else {
|
||||
if (!confirm(`This will permanently delete ${PURGE_LABELS[target]}.\n\nThis cannot be undone. Are you sure?`)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/admin.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error ?? 'Purge failed');
|
||||
const n = typeof data.purged === 'number' ? ` (${data.purged} rows)` : '';
|
||||
showResult(`Purge completed successfully${n}.`, 'success');
|
||||
loadAdmin();
|
||||
} catch (e) {
|
||||
showResult('Purge failed: ' + e.message, 'danger');
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Toast/alert helper ──────────────────────────────────────────────────────
|
||||
|
||||
function showResult(msg, type) {
|
||||
const el = document.getElementById('adminResult');
|
||||
el.className = `alert alert-${type}`;
|
||||
el.textContent = msg;
|
||||
el.style.display = '';
|
||||
clearTimeout(el._timer);
|
||||
el._timer = setTimeout(() => { el.style.display = 'none'; }, 6000);
|
||||
}
|
||||
|
||||
// ─── Init ────────────────────────────────────────────────────────────────────
|
||||
|
||||
loadAdmin();
|
||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') loadAdmin(); });
|
||||
</script>
|
||||
|
||||
<nav class="bottom-nav" aria-label="Navigation">
|
||||
<a href="index.html" class="bottom-nav-item">
|
||||
<i class="fa-solid fa-house"></i>
|
||||
|
||||
File diff suppressed because one or more lines are too long
+21
-3
@@ -40,6 +40,18 @@
|
||||
document.body.style.removeProperty('padding-right');
|
||||
}
|
||||
|
||||
function swapPageModals(doc) {
|
||||
document.querySelectorAll('[data-ajax-modal="true"]').forEach(el => el.remove());
|
||||
doc.querySelectorAll('body > .modal').forEach(old => {
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.innerHTML = old.outerHTML;
|
||||
const modal = wrapper.firstElementChild;
|
||||
if (!modal) return;
|
||||
modal.setAttribute('data-ajax-modal', 'true');
|
||||
document.body.appendChild(modal);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Per-page inline <style> management ───────────────────────────────────
|
||||
const STYLE_ID = 'ajax-page-style';
|
||||
function setPageStyles(cssText) {
|
||||
@@ -100,7 +112,7 @@
|
||||
// Then re-expose every named function declaration to `window` so that
|
||||
// inline onclick="foo()" handlers continue to resolve them globally.
|
||||
const funcNames = [
|
||||
...code.matchAll(/^(?:async\s+)?function\s+(\w+)\s*\(/gm),
|
||||
...code.matchAll(/^\s*(?:async\s+)?function\s+(\w+)\s*\(/gm),
|
||||
].map(m => m[1]);
|
||||
|
||||
const expose = funcNames
|
||||
@@ -161,13 +173,19 @@
|
||||
// Cleanup outgoing page, then inject new content
|
||||
cleanupPage();
|
||||
mainInner.innerHTML = doc.querySelector('.main-inner')?.innerHTML ?? '';
|
||||
swapPageModals(doc);
|
||||
document.title = doc.title;
|
||||
|
||||
const filename = href.split('/').pop();
|
||||
setActiveNav(filename);
|
||||
|
||||
// Execute the new page's inline scripts in order
|
||||
runInlineScripts(doc);
|
||||
// Execute page scripts from the centralized app bundle when available.
|
||||
if (typeof window.__runPageScripts === 'function') {
|
||||
window.__runPageScripts(filename);
|
||||
} else {
|
||||
// Fallback for legacy pages that still carry inline scripts.
|
||||
runInlineScripts(doc);
|
||||
}
|
||||
|
||||
} catch {
|
||||
// Fallback to hard navigation on any error
|
||||
|
||||
+3
-456
@@ -195,449 +195,12 @@
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="assets/js/nav.js"></script>
|
||||
<script src="assets/js/app.js"></script>
|
||||
<script src="https://unpkg.com/dropzone@6.0.0-beta.1/dist/dropzone-min.js"></script>
|
||||
<script src="https://code.jquery.com/jquery-4.0.0.min.js"
|
||||
integrity="sha256-OaVG6prZf4v69dPg6PhVattBXkcOWQB62pdZ3ORyrao=" crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.datatables.net/2.3.8/js/dataTables.min.js"></script>
|
||||
<script>
|
||||
Dropzone.autoDiscover = false;
|
||||
|
||||
let pendingFile = null;
|
||||
let currentDuplicates = [];
|
||||
|
||||
const dz = new Dropzone("#csvDropzone", {
|
||||
url: "/api/attendees.php",
|
||||
acceptedFiles: ".csv",
|
||||
maxFiles: 1,
|
||||
maxFilesize: 5,
|
||||
autoProcessQueue: false,
|
||||
dictDefaultMessage: "",
|
||||
params: () => ({ mode: document.querySelector('input[name="importMode"]:checked').value }),
|
||||
});
|
||||
|
||||
dz.on("addedfile", (file) => {
|
||||
document.getElementById('confirmUploadFilename').textContent = file.name;
|
||||
document.getElementById('confirmUploadBar').classList.remove('d-none');
|
||||
document.getElementById('importResult').innerHTML = '';
|
||||
});
|
||||
|
||||
dz.on("removedfile", () => {
|
||||
document.getElementById('confirmUploadBar').classList.add('d-none');
|
||||
document.getElementById('confirmUploadFilename').textContent = '';
|
||||
});
|
||||
|
||||
function confirmUpload() {
|
||||
dz.processQueue();
|
||||
}
|
||||
|
||||
function cancelUpload() {
|
||||
dz.removeAllFiles();
|
||||
}
|
||||
|
||||
dz.on("success", (file, response) => {
|
||||
const r = typeof response === 'string' ? JSON.parse(response) : response;
|
||||
if (r.status === 'needs_resolution') {
|
||||
pendingFile = file;
|
||||
currentDuplicates = r.duplicates;
|
||||
showDuplicateModal(r.duplicates);
|
||||
return;
|
||||
}
|
||||
dz.removeFile(file);
|
||||
const resultEl = document.getElementById('importResult');
|
||||
const parts = [];
|
||||
if (r.imported) parts.push(`<span class="text-success">${r.imported} added</span>`);
|
||||
if (r.updated) parts.push(`<span class="text-info">${r.updated} updated</span>`);
|
||||
if (r.skipped) {
|
||||
const reasons = [];
|
||||
if (r.skip_reasons?.not_attending) reasons.push(`${r.skip_reasons.not_attending} not attending`);
|
||||
if (r.skip_reasons?.no_mobile) reasons.push(`${r.skip_reasons.no_mobile} invalid/missing mobile`);
|
||||
const detail = reasons.length ? ` (${reasons.join(', ')})` : '';
|
||||
parts.push(`<span class="text-muted">${r.skipped} skipped${detail}</span>`);
|
||||
}
|
||||
resultEl.innerHTML = parts.length ? 'Import complete: ' + parts.join(', ') + '.' : 'Import complete.';
|
||||
if (r.rejected && r.rejected.length > 0) {
|
||||
showRejectedRecords(r.rejected);
|
||||
} else {
|
||||
rejectedRows = [];
|
||||
renderRejectedTable();
|
||||
}
|
||||
loadAttendees();
|
||||
});
|
||||
|
||||
dz.on("error", (file, msg) => {
|
||||
const errText = typeof msg === 'object' ? (msg.error ?? JSON.stringify(msg)) : msg;
|
||||
document.getElementById('importResult').innerHTML = `<span class="text-danger">Import failed: ${esc(errText)}</span>`;
|
||||
dz.removeFile(file);
|
||||
});
|
||||
|
||||
let table = null;
|
||||
|
||||
async function loadAttendees() {
|
||||
const tbody = document.getElementById('attendeeBody');
|
||||
const countEl = document.getElementById('attendeeCount');
|
||||
|
||||
// Destroy existing DataTable instance before touching the DOM
|
||||
if (table) { table.destroy(); table = null; }
|
||||
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="text-muted text-center py-4">Loading…</td></tr>';
|
||||
try {
|
||||
const data = await fetch('/api/attendees.php').then(r => r.json());
|
||||
const list = data.attendees ?? [];
|
||||
countEl.textContent = list.length + ' total';
|
||||
if (list.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="text-muted text-center py-4">No attendees yet. Upload a CSV to get started.</td></tr>';
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = list.map(a => `
|
||||
<tr>
|
||||
<td>${esc(a.first_name + ' ' + a.last_name)}</td>
|
||||
<td style="color:var(--text-muted);">${esc(a.email ?? '')}</td>
|
||||
<td style="color:var(--text-muted);">${esc(a.mobile_number)}</td>
|
||||
<td>${esc(a.workshops ?? '—')}</td>
|
||||
<td style="color:var(--text-muted);">${formatWorkshopTimes(a.workshop_times)}</td>
|
||||
<td style="white-space:nowrap;">
|
||||
<button class="btn btn-sm btn-accent" onclick='openEditModal(${JSON.stringify(a)})'>
|
||||
<i class="fa-solid fa-pen fa-fw"></i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
table = new DataTable('#attendeesTable', { columnDefs: [{ orderable: false, targets: -1 }] });
|
||||
} catch {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="text-danger text-center py-4">Could not load attendees.</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
function esc(str) {
|
||||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
function formatWorkshopTimes(timesStr) {
|
||||
if (!timesStr) return '—';
|
||||
return esc(timesStr.split(',').map(t => {
|
||||
const d = new Date(t.trim().replace(' ', 'T'));
|
||||
return isNaN(d.getTime()) ? t.trim() : d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}).join(', '));
|
||||
}
|
||||
|
||||
async function purgeAttendees() {
|
||||
if (!confirm('This will permanently delete all attendees and their registrations. Are you sure?')) return;
|
||||
const btn = document.getElementById('purgeBtn');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const res = await fetch('/api/attendees.php', { method: 'DELETE' });
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
loadAttendees();
|
||||
} catch (e) {
|
||||
alert('Purge failed: ' + e.message);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openApiKeyModal() {
|
||||
document.getElementById('apiKeyInput').value = '';
|
||||
document.getElementById('apiKeyError').textContent = '';
|
||||
const statusEl = document.getElementById('apiKeyStatus');
|
||||
statusEl.textContent = 'Checking…';
|
||||
try {
|
||||
const [keyData, costData] = await Promise.all([
|
||||
fetch('/api/settings.php?key=clickatell_api_key').then(r => r.json()),
|
||||
fetch('/api/settings.php?key=clickatell_cost_per_sms').then(r => r.json()),
|
||||
]);
|
||||
statusEl.innerHTML = keyData.set
|
||||
? `API key set: <code>${esc(keyData.hint)}</code> — enter a new key to replace it.`
|
||||
: '<span class="text-warning">No API key configured.</span> Enter one below to enable SMS sending.';
|
||||
document.getElementById('costPerSmsInput').value = costData.value ?? '0.04849';
|
||||
} catch {
|
||||
statusEl.textContent = 'Could not load current settings.';
|
||||
}
|
||||
}
|
||||
|
||||
async function saveApiKey() {
|
||||
const key = document.getElementById('apiKeyInput').value.trim();
|
||||
const cost = document.getElementById('costPerSmsInput').value.trim();
|
||||
const errEl = document.getElementById('apiKeyError');
|
||||
const btn = document.getElementById('apiKeySaveBtn');
|
||||
errEl.textContent = '';
|
||||
if (!key && !cost) { errEl.textContent = 'Please enter at least one value.'; return; }
|
||||
const costNum = parseFloat(cost);
|
||||
if (cost && (isNaN(costNum) || costNum < 0)) { errEl.textContent = 'Cost must be a positive number.'; return; }
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const saves = [];
|
||||
if (key) saves.push(fetch('/api/settings.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'clickatell_api_key', value: key }) }));
|
||||
if (cost) saves.push(fetch('/api/settings.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'clickatell_cost_per_sms', value: cost }) }));
|
||||
const results = await Promise.all(saves);
|
||||
for (const res of results) { if (!res.ok) throw new Error((await res.json()).error ?? 'Save failed'); }
|
||||
bootstrap.Modal.getInstance(document.getElementById('apiKeyModal')).hide();
|
||||
} catch (e) {
|
||||
errEl.textContent = e.message;
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
loadAttendees();
|
||||
|
||||
// ─── Rejected records ────────────────────────────────────────────────────────
|
||||
|
||||
let rejectedRows = [];
|
||||
let rejectedFilter = 'no_mobile';
|
||||
|
||||
function showRejectedRecords(rejected) {
|
||||
rejectedRows = rejected.map(r => ({ ...r, dismissed: false }));
|
||||
rejectedFilter = 'no_mobile';
|
||||
document.querySelectorAll('#rejectedFilter button').forEach(b => b.classList.remove('active'));
|
||||
document.querySelector('#rejectedFilter button[data-filter="no_mobile"]').classList.add('active');
|
||||
renderRejectedTable();
|
||||
}
|
||||
|
||||
function renderRejectedTable() {
|
||||
const section = document.getElementById('rejectedSection');
|
||||
const tbody = document.getElementById('rejectedBody');
|
||||
const countEl = document.getElementById('rejectedCount');
|
||||
|
||||
const active = rejectedRows.filter(r => !r.dismissed);
|
||||
if (active.length === 0) { section.classList.add('d-none'); return; }
|
||||
|
||||
const visible = rejectedFilter === 'all'
|
||||
? active
|
||||
: rejectedFilter === 'not_attending'
|
||||
? active.filter(r => r.reason === 'not_attending')
|
||||
: active.filter(r => r.reason !== 'not_attending');
|
||||
section.classList.remove('d-none');
|
||||
countEl.textContent = active.length;
|
||||
|
||||
if (visible.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="text-muted text-center py-3">No records match this filter.</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = visible.map(r => {
|
||||
const idx = rejectedRows.indexOf(r);
|
||||
const reasonBadges = {
|
||||
not_attending: '<span class="badge" style="background:rgba(250,204,21,0.15);color:#facc15;">Not Attending</span>',
|
||||
no_mobile: '<span class="badge" style="background:rgba(248,113,113,0.15);color:#f87171;">No Mobile</span>',
|
||||
foreign_country_code: '<span class="badge" style="background:rgba(251,146,60,0.15);color:#fb923c;">Foreign Number</span>',
|
||||
invalid_number: '<span class="badge" style="background:rgba(248,113,113,0.15);color:#f87171;">Invalid Number</span>',
|
||||
};
|
||||
const reasonBadge = reasonBadges[r.reason] ?? reasonBadges.invalid_number;
|
||||
const addBtn = r.reason !== 'not_attending'
|
||||
? `<button class="btn btn-sm btn-accent me-1" onclick="addRejectedManually(${idx})"><i class="fa-solid fa-user-plus fa-fw"></i> Add</button>`
|
||||
: '';
|
||||
return `
|
||||
<tr>
|
||||
<td>${esc(r.first_name + ' ' + r.last_name)}</td>
|
||||
<td style="color:var(--text-muted);">${esc(r.email ?? '')}</td>
|
||||
<td style="color:var(--text-muted);">${esc(r.raw_mobile || '—')}</td>
|
||||
<td style="color:var(--text-muted);">${esc(r.status || '—')}</td>
|
||||
<td>${reasonBadge}</td>
|
||||
<td style="white-space:nowrap;">
|
||||
${addBtn}
|
||||
<button class="btn btn-sm btn-secondary" onclick="dismissRejected(${idx})"><i class="fa-solid fa-xmark fa-fw"></i></button>
|
||||
</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function dismissRejected(idx) {
|
||||
rejectedRows[idx].dismissed = true;
|
||||
renderRejectedTable();
|
||||
}
|
||||
|
||||
function dismissAllRejected() {
|
||||
rejectedRows.forEach(r => { r.dismissed = true; });
|
||||
renderRejectedTable();
|
||||
}
|
||||
|
||||
function addRejectedManually(idx) {
|
||||
const r = rejectedRows[idx];
|
||||
openEditModal({
|
||||
id: 0,
|
||||
first_name: r.first_name,
|
||||
last_name: r.last_name,
|
||||
email: r.email ?? '',
|
||||
mobile_number: r.raw_mobile ?? '',
|
||||
workshop_session_id: null,
|
||||
_rejectedIdx: idx,
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelectorAll('#rejectedFilter button').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
document.querySelectorAll('#rejectedFilter button').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
rejectedFilter = btn.dataset.filter;
|
||||
renderRejectedTable();
|
||||
});
|
||||
});
|
||||
|
||||
let editingAttendee = null;
|
||||
|
||||
function openEditModal(a) {
|
||||
editingAttendee = a;
|
||||
document.getElementById('editFirstName').value = a.first_name ?? '';
|
||||
document.getElementById('editLastName').value = a.last_name ?? '';
|
||||
document.getElementById('editEmail').value = a.email ?? '';
|
||||
document.getElementById('editMobile').value = a.mobile_number ?? '';
|
||||
document.getElementById('editError').textContent = '';
|
||||
|
||||
const sel = document.getElementById('editWorkshop');
|
||||
sel.innerHTML = '<option value="">— No workshop —</option>';
|
||||
fetch('/api/workshops.php').then(r => r.json()).then(data => {
|
||||
const workshops = data.workshops ?? [];
|
||||
// Group sessions by workshop name (case-insensitive) so capitalisation
|
||||
// variants (e.g. "Hot Sauce tasting" vs "Hot Sauce Tasting") are merged.
|
||||
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);
|
||||
});
|
||||
Object.values(groups).forEach(({ label, sessions }) => {
|
||||
const fmtTime = ws => ws.workshop_time
|
||||
? new Date(ws.workshop_time.replace(' ', 'T')).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
||||
: null;
|
||||
if (sessions.length === 1) {
|
||||
const ws = sessions[0];
|
||||
const opt = document.createElement('option');
|
||||
opt.value = ws.id;
|
||||
const time = fmtTime(ws);
|
||||
opt.textContent = label + (time ? ' (' + time + ')' : '');
|
||||
if (String(ws.id) === String(a.workshop_session_id)) opt.selected = true;
|
||||
sel.appendChild(opt);
|
||||
} else {
|
||||
const grp = document.createElement('optgroup');
|
||||
grp.label = label;
|
||||
sessions.forEach(ws => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = ws.id;
|
||||
opt.textContent = fmtTime(ws) ?? '(no time)';
|
||||
if (String(ws.id) === String(a.workshop_session_id)) opt.selected = true;
|
||||
grp.appendChild(opt);
|
||||
});
|
||||
sel.appendChild(grp);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
new bootstrap.Modal(document.getElementById('editModal')).show();
|
||||
}
|
||||
|
||||
async function saveEdit() {
|
||||
const errEl = document.getElementById('editError');
|
||||
const btn = document.getElementById('editSaveBtn');
|
||||
errEl.textContent = '';
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const wsVal = document.getElementById('editWorkshop').value;
|
||||
const res = await fetch('/api/attendees.php', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
id: editingAttendee.id,
|
||||
first_name: document.getElementById('editFirstName').value.trim(),
|
||||
last_name: document.getElementById('editLastName').value.trim(),
|
||||
email: document.getElementById('editEmail').value.trim(),
|
||||
mobile_number: document.getElementById('editMobile').value.trim(),
|
||||
workshop_session_id: wsVal ? parseInt(wsVal, 10) : 0,
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error ?? 'Save failed');
|
||||
bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
|
||||
// If this was a manual-add from the rejected table, dismiss that row
|
||||
if (editingAttendee._rejectedIdx !== undefined) {
|
||||
rejectedRows[editingAttendee._rejectedIdx].dismissed = true;
|
||||
renderRejectedTable();
|
||||
}
|
||||
loadAttendees();
|
||||
} catch (e) {
|
||||
errEl.textContent = e.message;
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function showDuplicateModal(duplicates) {
|
||||
const container = document.getElementById('dupGroups');
|
||||
container.innerHTML = duplicates.map((dup, gi) => {
|
||||
const rowHtml = dup.rows.map((row, ri) => `
|
||||
<div class="form-check mb-1">
|
||||
<input class="form-check-input" type="radio" name="dup_${gi}" id="dup_${gi}_${ri}" value="${ri}"${ri === 0 ? ' checked' : ''}>
|
||||
<label class="form-check-label" for="dup_${gi}_${ri}">
|
||||
<strong>${esc(row.first_name)} ${esc(row.last_name)}</strong>
|
||||
${row.email ? `<span class="text-muted ms-1">· ${esc(row.email)}</span>` : ''}
|
||||
${row.workshop_name ? `<span class="badge bg-secondary ms-1">${esc(row.workshop_name)}</span>` : ''}
|
||||
</label>
|
||||
</div>`).join('');
|
||||
return `
|
||||
<div class="mb-3 p-3 rounded" style="background:var(--bg-card);border:1px solid var(--border);">
|
||||
<div class="mb-2 fw-semibold" style="font-size:0.85rem;color:var(--text-muted);">
|
||||
<i class="fa-solid fa-phone fa-fw me-1 text-warning"></i>${esc(dup.mobile)}
|
||||
</div>
|
||||
${rowHtml}
|
||||
</div>`;
|
||||
}).join('');
|
||||
new bootstrap.Modal(document.getElementById('dupModal')).show();
|
||||
}
|
||||
|
||||
function cancelDuplicates() {
|
||||
bootstrap.Modal.getInstance(document.getElementById('dupModal')).hide();
|
||||
if (pendingFile) { dz.removeFile(pendingFile); pendingFile = null; }
|
||||
currentDuplicates = [];
|
||||
}
|
||||
|
||||
async function confirmDuplicates() {
|
||||
const resolutions = {};
|
||||
currentDuplicates.forEach((dup, gi) => {
|
||||
const sel = document.querySelector(`input[name="dup_${gi}"]:checked`);
|
||||
if (sel) resolutions[dup.mobile] = parseInt(sel.value, 10);
|
||||
});
|
||||
const btn = document.getElementById('dupConfirmBtn');
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin fa-fw"></i> Importing…';
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append('file', pendingFile, pendingFile.name);
|
||||
fd.append('mode', document.querySelector('input[name="importMode"]:checked').value);
|
||||
fd.append('resolutions', JSON.stringify(resolutions));
|
||||
const res = await fetch('/api/attendees.php', { method: 'POST', body: fd });
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error ?? 'Import failed');
|
||||
bootstrap.Modal.getInstance(document.getElementById('dupModal')).hide();
|
||||
dz.removeFile(pendingFile);
|
||||
pendingFile = null;
|
||||
currentDuplicates = [];
|
||||
const resultEl = document.getElementById('importResult');
|
||||
const parts = [];
|
||||
if (data.imported) parts.push(`<span class="text-success">${data.imported} added</span>`);
|
||||
if (data.updated) parts.push(`<span class="text-info">${data.updated} updated</span>`);
|
||||
if (data.skipped) {
|
||||
const reasons = [];
|
||||
if (data.skip_reasons?.not_attending) reasons.push(`${data.skip_reasons.not_attending} not attending`);
|
||||
if (data.skip_reasons?.no_mobile) reasons.push(`${data.skip_reasons.no_mobile} invalid/missing mobile`);
|
||||
const detail = reasons.length ? ` (${reasons.join(', ')})` : '';
|
||||
parts.push(`<span class="text-muted">${data.skipped} skipped${detail}</span>`);
|
||||
}
|
||||
resultEl.innerHTML = parts.length ? 'Import complete: ' + parts.join(', ') + '.' : 'Import complete.';
|
||||
if (data.rejected && data.rejected.length > 0) {
|
||||
showRejectedRecords(data.rejected);
|
||||
} else {
|
||||
rejectedRows = [];
|
||||
renderRejectedTable();
|
||||
}
|
||||
loadAttendees();
|
||||
} catch (e) {
|
||||
document.getElementById('importResult').innerHTML = `<span class="text-danger">Import failed: ${esc(e.message)}</span>`;
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<i class="fa-solid fa-check fa-fw"></i> Confirm Import';
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
<!-- ─── Edit attendee modal ─── -->
|
||||
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
|
||||
@@ -710,23 +273,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const r = await fetch('/api/admin.php', { redirect: 'manual' });
|
||||
if (r.type === 'opaqueredirect' || !r.ok) { window.location.reload(); return; }
|
||||
const d = await r.json();
|
||||
document.getElementById('sandboxBanner').style.display = d.sandbox_mode ? '' : 'none';
|
||||
document.querySelectorAll('.admin-nav-link').forEach(el => el.classList.toggle('d-none', !d.is_admin));
|
||||
const name = d.name || d.username;
|
||||
if (name) {
|
||||
document.querySelectorAll('.nav-username').forEach(el => { el.textContent = name; });
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
checkAuth();
|
||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') checkAuth(); });
|
||||
</script>
|
||||
|
||||
<nav class="bottom-nav" aria-label="Navigation">
|
||||
<a href="index.html" class="bottom-nav-item">
|
||||
<i class="fa-solid fa-house"></i>
|
||||
|
||||
+3
-114
@@ -121,123 +121,12 @@
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="assets/js/nav.js"></script>
|
||||
<script src="assets/js/app.js"></script>
|
||||
<script src="https://code.jquery.com/jquery-4.0.0.min.js"
|
||||
integrity="sha256-OaVG6prZf4v69dPg6PhVattBXkcOWQB62pdZ3ORyrao=" crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.datatables.net/2.3.8/js/dataTables.min.js"></script>
|
||||
<script>
|
||||
let logTable = null;
|
||||
let _lastDataKey = '';
|
||||
|
||||
function esc(str) {
|
||||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function errorDesc(msg) {
|
||||
if (!msg) return '';
|
||||
try {
|
||||
const parsed = JSON.parse(msg);
|
||||
// Top-level error (older Clickatell responses)
|
||||
if (parsed.error) return parsed.error;
|
||||
// Clickatell v2: { messages: [{ error, errorDescription }] }
|
||||
const m = Array.isArray(parsed.messages) ? parsed.messages[0] : null;
|
||||
if (m?.error) return m.error;
|
||||
if (m?.errorDescription) return m.errorDescription;
|
||||
return parsed.message || msg;
|
||||
} catch {
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
|
||||
function fmtDate(str) {
|
||||
if (!str) return '—';
|
||||
return new Date(str).toLocaleString('en-GB', {
|
||||
day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
async function loadLog(isRefresh = false) {
|
||||
const tbody = document.getElementById('logBody');
|
||||
|
||||
try {
|
||||
const data = await fetch('/api/delivery-log.php?all=1').then(r => r.json());
|
||||
const stats = data.stats ?? {};
|
||||
const entries = data.entries ?? [];
|
||||
|
||||
document.getElementById('stat-sent').textContent = stats.total_sent ?? '—';
|
||||
document.getElementById('stat-failed').textContent = stats.total_failed ?? '—';
|
||||
document.getElementById('stat-rate').textContent = stats.success_rate != null ? stats.success_rate + '%' : '—';
|
||||
|
||||
// Skip expensive DOM rebuild if nothing has changed
|
||||
const dataKey = `${entries.length}:${stats.total_sent}:${stats.total_failed}`;
|
||||
if (isRefresh && dataKey === _lastDataKey) return;
|
||||
_lastDataKey = dataKey;
|
||||
|
||||
// Preserve current page position before destroying the table
|
||||
const prevPage = logTable ? logTable.page() : 0;
|
||||
|
||||
// Destroy existing DataTable before rewriting DOM
|
||||
if (logTable) { logTable.destroy(); logTable = null; }
|
||||
|
||||
if (entries.length === 0) {
|
||||
tbody.innerHTML = `<tr><td colspan="5" class="text-muted text-center py-4">No messages sent yet.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = entries.map(e => {
|
||||
const statusBadge = e.status === 'failed'
|
||||
? `<span class="badge-failed" style="cursor:help;"${e.error_message ? ` data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="${esc(errorDesc(e.error_message))}"` : ''}>Failed</span>`
|
||||
: `<span class="badge-delivered">Sent</span>`;
|
||||
return `
|
||||
<tr>
|
||||
<td>${esc(e.attendee_name ?? '—')}</td>
|
||||
<td style="color:var(--text-muted);">${e.message_body
|
||||
? `<span style="cursor:help;border-bottom:1px dashed var(--text-muted);" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="${esc(e.message_body)}">${esc(e.template_name)}</span>`
|
||||
: esc(e.template_name)}</td>
|
||||
<td style="color:var(--text-muted);">${esc(e.mobile_number)}</td>
|
||||
<td>${statusBadge}</td>
|
||||
<td style="color:var(--text-muted);font-size:0.82rem;" data-order="${e.sent_at ?? ''}">${fmtDate(e.sent_at)}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
logTable = new DataTable('#logTable', {
|
||||
order: [[4, 'desc']],
|
||||
columnDefs: [{ orderable: false, targets: 3 }],
|
||||
pageLength: 25,
|
||||
drawCallback: () => {
|
||||
document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
|
||||
bootstrap.Tooltip.getOrCreateInstance(el);
|
||||
});
|
||||
},
|
||||
});
|
||||
if (isRefresh && prevPage > 0 && prevPage < logTable.page.info().pages) {
|
||||
logTable.page(prevPage).draw(false);
|
||||
}
|
||||
} catch {
|
||||
tbody.innerHTML = `<tr><td colspan="5" class="text-danger text-center py-4">Could not load delivery log.</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
loadLog();
|
||||
setInterval(() => loadLog(true), 10_000);
|
||||
</script>
|
||||
<script>
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const r = await fetch('/api/admin.php', { redirect: 'manual' });
|
||||
if (r.type === 'opaqueredirect' || !r.ok) { window.location.reload(); return; }
|
||||
const d = await r.json();
|
||||
document.getElementById('sandboxBanner').style.display = d.sandbox_mode ? '' : 'none';
|
||||
document.querySelectorAll('.admin-nav-link').forEach(el => el.classList.toggle('d-none', !d.is_admin));
|
||||
const name = d.name || d.username;
|
||||
if (name) {
|
||||
document.querySelectorAll('.nav-username').forEach(el => { el.textContent = name; });
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
checkAuth();
|
||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') checkAuth(); });
|
||||
</script>
|
||||
|
||||
|
||||
<nav class="bottom-nav" aria-label="Navigation">
|
||||
<a href="index.html" class="bottom-nav-item">
|
||||
<i class="fa-solid fa-house"></i>
|
||||
|
||||
+3
-132
@@ -231,138 +231,9 @@
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="assets/js/nav.js"></script>
|
||||
<script>
|
||||
function esc(str) {
|
||||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
async function openApiKeyModal() {
|
||||
document.getElementById('apiKeyInput').value = '';
|
||||
document.getElementById('apiKeyError').textContent = '';
|
||||
const statusEl = document.getElementById('apiKeyStatus');
|
||||
statusEl.textContent = 'Checking…';
|
||||
try {
|
||||
const [keyData, costData] = await Promise.all([
|
||||
fetch('/api/settings.php?key=clickatell_api_key').then(r => r.json()),
|
||||
fetch('/api/settings.php?key=clickatell_cost_per_sms').then(r => r.json()),
|
||||
]);
|
||||
statusEl.innerHTML = keyData.set
|
||||
? `API key set: <code>${esc(keyData.hint)}</code> — enter a new key to replace it.`
|
||||
: '<span class="text-warning">No API key configured.</span> Enter one below to enable SMS sending.';
|
||||
document.getElementById('costPerSmsInput').value = costData.value ?? '0.04849';
|
||||
} catch {
|
||||
statusEl.textContent = 'Could not load current settings.';
|
||||
}
|
||||
}
|
||||
|
||||
async function saveApiKey() {
|
||||
const key = document.getElementById('apiKeyInput').value.trim();
|
||||
const cost = document.getElementById('costPerSmsInput').value.trim();
|
||||
const errEl = document.getElementById('apiKeyError');
|
||||
const btn = document.getElementById('apiKeySaveBtn');
|
||||
errEl.textContent = '';
|
||||
if (!key && !cost) { errEl.textContent = 'Please enter at least one value.'; return; }
|
||||
const costNum = parseFloat(cost);
|
||||
if (cost && (isNaN(costNum) || costNum < 0)) { errEl.textContent = 'Cost must be a positive number.'; return; }
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const saves = [];
|
||||
if (key) saves.push(fetch('/api/settings.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'clickatell_api_key', value: key }) }));
|
||||
if (cost) saves.push(fetch('/api/settings.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'clickatell_cost_per_sms', value: cost }) }));
|
||||
const results = await Promise.all(saves);
|
||||
for (const res of results) { if (!res.ok) throw new Error((await res.json()).error ?? 'Save failed'); }
|
||||
bootstrap.Modal.getInstance(document.getElementById('apiKeyModal')).hide();
|
||||
loadStats();
|
||||
} catch (e) {
|
||||
errEl.textContent = e.message;
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
let spendView = 'balance';
|
||||
let spendData = { balance: null, currency: null, estimatedCost: null };
|
||||
|
||||
function formatCurrency(amount, currency) {
|
||||
if (amount == null || Number.isNaN(Number(amount))) return '—';
|
||||
const sym = currency === 'GBP' ? '£' : currency === 'USD' ? '$' : currency === 'EUR' ? '€' : (currency ?? '');
|
||||
return sym + Number(amount).toFixed(2);
|
||||
}
|
||||
|
||||
function renderSpendCard() {
|
||||
const labelEl = document.getElementById('stat-spend-label');
|
||||
const valueEl = document.getElementById('stat-spend');
|
||||
if (!labelEl || !valueEl) return;
|
||||
|
||||
if (spendView === 'cost') {
|
||||
labelEl.textContent = 'EST. COST';
|
||||
valueEl.textContent = formatCurrency(spendData.estimatedCost, spendData.currency);
|
||||
return;
|
||||
}
|
||||
|
||||
labelEl.textContent = 'Balance';
|
||||
valueEl.textContent = formatCurrency(spendData.balance, spendData.currency);
|
||||
}
|
||||
|
||||
function toggleSpendCard() {
|
||||
spendView = spendView === 'balance' ? 'cost' : 'balance';
|
||||
renderSpendCard();
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
const [att, log, bal, cost, admin] = await Promise.all([
|
||||
fetch('/api/attendees.php').then(r => r.json()),
|
||||
fetch('/api/delivery-log.php').then(r => r.json()),
|
||||
fetch('/api/balance.php').then(r => r.json()),
|
||||
fetch('/api/settings.php?key=clickatell_cost_per_sms').then(r => r.json()),
|
||||
fetch('/api/admin.php').then(r => r.json()),
|
||||
]);
|
||||
document.getElementById('stat-attendees').textContent = att.total ?? '—';
|
||||
document.getElementById('stat-sent').textContent = log.stats?.total_sent ?? '—';
|
||||
const rate = log.stats?.success_rate;
|
||||
document.getElementById('stat-rate').textContent = rate != null ? rate + '%' : '—';
|
||||
spendData.balance = bal.balance != null ? Number(bal.balance) : null;
|
||||
spendData.currency = bal.currency ?? 'GBP';
|
||||
|
||||
const realSent = Number(admin.delivery_log_real_sent);
|
||||
const costPerSms = Number(cost.value);
|
||||
spendData.estimatedCost = Number.isFinite(realSent) && Number.isFinite(costPerSms)
|
||||
? realSent * costPerSms
|
||||
: null;
|
||||
|
||||
renderSpendCard();
|
||||
} catch { /* DB unavailable — stats stay as dashes */ }
|
||||
}
|
||||
document.getElementById('spendCard')?.addEventListener('click', toggleSpendCard);
|
||||
document.getElementById('spendCard')?.addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleSpendCard();
|
||||
}
|
||||
});
|
||||
loadStats();
|
||||
setInterval(() => loadStats(), 10_000);
|
||||
</script>
|
||||
<script>
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const r = await fetch('/api/admin.php', { redirect: 'manual' });
|
||||
if (r.type === 'opaqueredirect' || !r.ok) { window.location.reload(); return; }
|
||||
const d = await r.json();
|
||||
document.getElementById('sandboxBanner').style.display = d.sandbox_mode ? '' : 'none';
|
||||
document.querySelectorAll('.admin-nav-link').forEach(el => el.classList.toggle('d-none', !d.is_admin));
|
||||
const adminSection = document.getElementById('adminSection');
|
||||
if (adminSection) adminSection.classList.toggle('d-none', !d.is_admin);
|
||||
const name = d.name || d.username;
|
||||
if (name) {
|
||||
document.querySelectorAll('.nav-username').forEach(el => { el.textContent = name; });
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
checkAuth();
|
||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') checkAuth(); });
|
||||
</script>
|
||||
<script src="assets/js/app.js"></script>
|
||||
|
||||
|
||||
<nav class="bottom-nav" aria-label="Navigation">
|
||||
<a href="index.html" class="bottom-nav-item active">
|
||||
<i class="fa-solid fa-house"></i>
|
||||
|
||||
+3
-282
@@ -214,288 +214,9 @@
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="assets/js/nav.js"></script>
|
||||
<script>
|
||||
// ── Mode toggle ──────────────────────────────────────────
|
||||
let currentMode = 'specific';
|
||||
|
||||
function setMode(mode) {
|
||||
currentMode = mode;
|
||||
document.getElementById('relativeFields').style.display = mode === 'relative' ? '' : 'none';
|
||||
document.getElementById('specificFields').style.display = mode === 'specific' ? '' : 'none';
|
||||
document.getElementById('modeRelative').classList.toggle('active-mode', mode === 'relative');
|
||||
document.getElementById('modeSpecific').classList.toggle('active-mode', mode === 'specific');
|
||||
}
|
||||
|
||||
// ── Load templates into select ───────────────────────────
|
||||
async function loadTemplateOptions() {
|
||||
const sel = document.getElementById('templateSelect');
|
||||
try {
|
||||
const data = await fetch('/api/templates.php').then(r => r.json());
|
||||
const templates = data.templates ?? [];
|
||||
if (templates.length === 0) {
|
||||
sel.innerHTML = '<option value="" disabled selected>No templates — create one first</option>';
|
||||
return;
|
||||
}
|
||||
sel.innerHTML = templates.map(t =>
|
||||
`<option value="${t.id}">${esc(t.name)}</option>`
|
||||
).join('');
|
||||
} catch {
|
||||
sel.innerHTML = '<option value="" disabled selected>Could not load templates</option>';
|
||||
}
|
||||
}
|
||||
|
||||
// ── Add a rule ───────────────────────────────────────────
|
||||
async function addSchedule() {
|
||||
const templateId = document.getElementById('templateSelect').value;
|
||||
if (!templateId) { alert('Please select a template.'); return; }
|
||||
|
||||
const payload = { template_id: parseInt(templateId), mode: currentMode };
|
||||
|
||||
if (currentMode === 'relative') {
|
||||
payload.offset_value = parseInt(document.getElementById('offsetValue').value) || 1;
|
||||
payload.offset_unit = document.getElementById('offsetUnit').value;
|
||||
} else {
|
||||
const dt = document.getElementById('specificDatetime').value;
|
||||
if (!dt) { alert('Please pick a date and time.'); return; }
|
||||
payload.specific_datetime = dt;
|
||||
}
|
||||
|
||||
const res = await fetch('/api/schedule.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
alert('Error: ' + (err.error ?? 'Unknown error'));
|
||||
return;
|
||||
}
|
||||
loadSchedule();
|
||||
}
|
||||
|
||||
// ── Edit modal ───────────────────────────────────────────
|
||||
let editMode = 'specific';
|
||||
|
||||
function setEditMode(mode) {
|
||||
editMode = mode;
|
||||
document.getElementById('editRelativeFields').style.display = mode === 'relative' ? '' : 'none';
|
||||
document.getElementById('editSpecificFields').style.display = mode === 'specific' ? '' : 'none';
|
||||
document.getElementById('editModeRelative').classList.toggle('active-mode', mode === 'relative');
|
||||
document.getElementById('editModeSpecific').classList.toggle('active-mode', mode === 'specific');
|
||||
}
|
||||
|
||||
async function openEditModal(id) {
|
||||
const rule = window._scheduleRules?.[id];
|
||||
if (!rule) return;
|
||||
document.getElementById('editId').value = rule.id;
|
||||
setEditMode(rule.mode);
|
||||
|
||||
if (rule.mode === 'specific') {
|
||||
// Convert stored datetime to datetime-local format (YYYY-MM-DDTHH:MM)
|
||||
const dt = new Date(rule.specific_datetime.replace(' ', 'T'));
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
document.getElementById('editSpecificDatetime').value =
|
||||
`${dt.getFullYear()}-${pad(dt.getMonth() + 1)}-${pad(dt.getDate())}T${pad(dt.getHours())}:${pad(dt.getMinutes())}`;
|
||||
} else {
|
||||
document.getElementById('editOffsetValue').value = rule.offset_value;
|
||||
document.getElementById('editOffsetUnit').value = rule.offset_unit;
|
||||
}
|
||||
|
||||
// Populate template select, mirroring the main select
|
||||
const mainSel = document.getElementById('templateSelect');
|
||||
const editSel = document.getElementById('editTemplateSelect');
|
||||
editSel.innerHTML = mainSel.innerHTML;
|
||||
editSel.value = rule.template_id;
|
||||
|
||||
bootstrap.Modal.getOrCreateInstance(document.getElementById('editModal')).show();
|
||||
}
|
||||
|
||||
async function saveEdit() {
|
||||
const id = parseInt(document.getElementById('editId').value);
|
||||
const templateId = parseInt(document.getElementById('editTemplateSelect').value);
|
||||
if (!templateId) { alert('Please select a template.'); return; }
|
||||
|
||||
const payload = { template_id: templateId, mode: editMode };
|
||||
|
||||
if (editMode === 'relative') {
|
||||
payload.offset_value = parseInt(document.getElementById('editOffsetValue').value) || 1;
|
||||
payload.offset_unit = document.getElementById('editOffsetUnit').value;
|
||||
} else {
|
||||
const dt = document.getElementById('editSpecificDatetime').value;
|
||||
if (!dt) { alert('Please pick a date and time.'); return; }
|
||||
payload.specific_datetime = dt;
|
||||
}
|
||||
|
||||
const res = await fetch(`/api/schedule.php?id=${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
alert('Error: ' + (err.error ?? 'Unknown error'));
|
||||
return;
|
||||
}
|
||||
bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
|
||||
loadSchedule();
|
||||
}
|
||||
|
||||
// ── Remove a rule ────────────────────────────────────────
|
||||
async function removeSchedule(id) {
|
||||
if (!confirm('Remove this scheduled rule?')) return;
|
||||
const res = await fetch(`/api/schedule.php?id=${id}`, { method: 'DELETE' });
|
||||
if (!res.ok) { alert('Could not remove rule.'); return; }
|
||||
loadSchedule();
|
||||
}
|
||||
|
||||
// ── Rendering ────────────────────────────────────────────
|
||||
function relativeTime(date) {
|
||||
const diffMs = date - Date.now();
|
||||
const diffMin = Math.round(diffMs / 60000);
|
||||
if (diffMin < 1) return 'now';
|
||||
if (diffMin < 60) return `in ${diffMin} minute${diffMin !== 1 ? 's' : ''}`;
|
||||
const diffHr = Math.round(diffMin / 60);
|
||||
if (diffHr < 24) return `in ${diffHr} hour${diffHr !== 1 ? 's' : ''}`;
|
||||
const diffDay = Math.round(diffHr / 24);
|
||||
return `in ${diffDay} day${diffDay !== 1 ? 's' : ''}`;
|
||||
}
|
||||
|
||||
function formatDateTime(date) {
|
||||
return date.toLocaleString('en-GB', {
|
||||
day: 'numeric', month: 'short', year: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
function ruleLabel(rule) {
|
||||
if (rule.mode === 'specific') {
|
||||
return 'Specific time: ' + formatDateTime(new Date(rule.specific_datetime));
|
||||
}
|
||||
const unit = { minutes: 'minute', hours: 'hour', days: 'day' }[rule.offset_unit] ?? rule.offset_unit;
|
||||
const val = rule.offset_value;
|
||||
return `${val} ${unit}${val !== 1 ? 's' : ''} before workshop`;
|
||||
}
|
||||
|
||||
function esc(str) {
|
||||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
async function loadSchedule() {
|
||||
const list = document.getElementById('scheduleList');
|
||||
const countEl = document.getElementById('scheduleCount');
|
||||
const pastList = document.getElementById('pastList');
|
||||
const pastCard = document.getElementById('pastCard');
|
||||
const pastCountEl = document.getElementById('pastCount');
|
||||
try {
|
||||
const data = await fetch('/api/schedule.php').then(r => r.json());
|
||||
const rules = data.rules ?? [];
|
||||
|
||||
// Store rules by id so edit button can look them up safely
|
||||
window._scheduleRules = {};
|
||||
rules.forEach(r => { window._scheduleRules[r.id] = r; });
|
||||
|
||||
const now = Date.now();
|
||||
const upcoming = [];
|
||||
const past = [];
|
||||
rules.forEach(rule => {
|
||||
if (rule.mode === 'specific') {
|
||||
const t = new Date(rule.specific_datetime.replace(' ', 'T')).getTime();
|
||||
(t > now ? upcoming : past).push(rule);
|
||||
} else {
|
||||
upcoming.push(rule);
|
||||
}
|
||||
});
|
||||
|
||||
// Sort upcoming: specific rules soonest first, relative rules after
|
||||
upcoming.sort((a, b) => {
|
||||
const aTime = a.mode === 'specific' ? new Date(a.specific_datetime.replace(' ', 'T')).getTime() : Infinity;
|
||||
const bTime = b.mode === 'specific' ? new Date(b.specific_datetime.replace(' ', 'T')).getTime() : Infinity;
|
||||
return aTime - bTime;
|
||||
});
|
||||
|
||||
countEl.textContent = `${upcoming.length} scheduled`;
|
||||
|
||||
if (upcoming.length === 0) {
|
||||
list.innerHTML = '<p class="text-muted" style="font-size:0.85rem;">No upcoming rules. Add one above.</p>';
|
||||
} else {
|
||||
list.innerHTML = upcoming.map(rule => renderRuleCard(rule, false)).join('');
|
||||
}
|
||||
|
||||
if (past.length > 0) {
|
||||
pastCard.style.display = '';
|
||||
pastCountEl.textContent = `${past.length} past`;
|
||||
pastList.innerHTML = past.map(rule => renderRuleCard(rule, true)).join('');
|
||||
} else {
|
||||
pastCard.style.display = 'none';
|
||||
}
|
||||
} catch {
|
||||
list.innerHTML = '<p class="text-danger" style="font-size:0.85rem;">Could not load schedule.</p>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderRuleCard(rule, isPast) {
|
||||
const label = ruleLabel(rule);
|
||||
const sendAt = rule.mode === 'specific' ? new Date(rule.specific_datetime.replace(' ', 'T')) : null;
|
||||
const timeTag = sendAt
|
||||
? isPast
|
||||
? `<span style="font-size:0.75rem;background:rgba(139,148,158,0.12);color:var(--text-muted);border-radius:6px;padding:0.15em 0.6em;"><i class="fa-solid fa-circle-check me-1"></i>${formatDateTime(sendAt)}</span>`
|
||||
: `<span style="font-size:0.75rem;background:rgba(79,142,247,0.12);color:var(--accent);border-radius:6px;padding:0.15em 0.6em;">${relativeTime(sendAt)}</span>`
|
||||
: '';
|
||||
const opacity = isPast ? 'opacity:0.6;' : '';
|
||||
return `
|
||||
<div style="background:var(--bg-surface);border:1px solid var(--border);border-radius:10px;padding:1rem;${opacity}">
|
||||
<div class="d-flex align-items-start justify-content-between gap-2 mb-1">
|
||||
<div>
|
||||
<div style="font-weight:600;font-size:0.9rem;">${esc(rule.template_name)}</div>
|
||||
<div class="text-muted" style="font-size:0.78rem;">${esc(label)}</div>
|
||||
</div>
|
||||
<div class="d-flex gap-2">
|
||||
${!isPast ? `<button class="btn btn-sm btn-secondary" onclick="openEditModal(${rule.id})"><i class="fa-solid fa-pencil fa-fw"></i></button>` : `<button class="btn btn-sm btn-secondary" onclick="openEditModal(${rule.id})" title="Reschedule"><i class="fa-solid fa-rotate-right fa-fw"></i></button>`}
|
||||
<button class="btn btn-sm btn-danger" onclick="removeSchedule(${rule.id})"><i class="fa-solid fa-trash fa-fw"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
${timeTag}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
loadTemplateOptions();
|
||||
loadSchedule();
|
||||
setInterval(loadSchedule, 60000);
|
||||
|
||||
// Set default datetime-local to now
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
const now = new Date();
|
||||
document.getElementById('specificDatetime').value =
|
||||
`${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
|
||||
</script>
|
||||
<script>
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const r = await fetch('/api/admin.php', { redirect: 'manual' });
|
||||
if (r.type === 'opaqueredirect' || !r.ok) { window.location.reload(); return; }
|
||||
const d = await r.json();
|
||||
document.getElementById('sandboxBanner').style.display = d.sandbox_mode ? '' : 'none';
|
||||
document.querySelectorAll('.admin-nav-link').forEach(el => el.classList.toggle('d-none', !d.is_admin));
|
||||
const name = d.name || d.username;
|
||||
if (name) {
|
||||
document.querySelectorAll('.nav-username').forEach(el => { el.textContent = name; });
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
checkAuth();
|
||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') checkAuth(); });
|
||||
|
||||
async function checkApiKey() {
|
||||
try {
|
||||
const r = await fetch('/api/settings.php?key=clickatell_api_key').then(res => res.json());
|
||||
const missing = !r.set;
|
||||
document.getElementById('noApiKeyBanner').style.display = missing ? '' : 'none';
|
||||
document.getElementById('addScheduleBtn').disabled = missing;
|
||||
} catch { }
|
||||
}
|
||||
checkApiKey();
|
||||
</script>
|
||||
<script src="assets/js/app.js"></script>
|
||||
|
||||
|
||||
<nav class="bottom-nav" aria-label="Navigation">
|
||||
<a href="index.html" class="bottom-nav-item">
|
||||
<i class="fa-solid fa-house"></i>
|
||||
|
||||
+3
-223
@@ -142,229 +142,9 @@
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="assets/js/nav.js"></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');
|
||||
let noApiKey = false;
|
||||
|
||||
// ── 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 ? ' <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 || noApiKey;
|
||||
resultEl.style.display = 'none';
|
||||
});
|
||||
|
||||
// ── Send ───────────────────────────────────────────────────
|
||||
function esc(str) {
|
||||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
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() === '' || noApiKey;
|
||||
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 checkAuth() {
|
||||
try {
|
||||
const r = await fetch('/api/admin.php', { redirect: 'manual' });
|
||||
if (r.type === 'opaqueredirect' || !r.ok) { window.location.reload(); return; }
|
||||
const d = await r.json();
|
||||
document.getElementById('sandboxBanner').style.display = d.sandbox_mode ? '' : 'none';
|
||||
document.querySelectorAll('.admin-nav-link').forEach(el => el.classList.toggle('d-none', !d.is_admin));
|
||||
const name = d.name || d.username;
|
||||
if (name) {
|
||||
document.querySelectorAll('.nav-username').forEach(el => { el.textContent = name; });
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
checkAuth();
|
||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') checkAuth(); });
|
||||
|
||||
async function checkApiKey() {
|
||||
try {
|
||||
const r = await fetch('/api/settings.php?key=clickatell_api_key').then(res => res.json());
|
||||
noApiKey = !r.set;
|
||||
document.getElementById('noApiKeyBanner').style.display = noApiKey ? '' : 'none';
|
||||
if (noApiKey) document.getElementById('sendBtn').disabled = true;
|
||||
} catch { }
|
||||
}
|
||||
checkApiKey();
|
||||
</script>
|
||||
<script src="assets/js/app.js"></script>
|
||||
|
||||
|
||||
<nav class="bottom-nav" aria-label="Navigation">
|
||||
<a href="index.html" class="bottom-nav-item">
|
||||
<i class="fa-solid fa-house"></i>
|
||||
|
||||
+3
-165
@@ -111,171 +111,9 @@
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="assets/js/nav.js"></script>
|
||||
<script>
|
||||
const MAX_CHARS = 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 };
|
||||
}
|
||||
|
||||
function updateCharCount(text) {
|
||||
const { length, limit, isUnicode } = smsEncoding(text);
|
||||
const remaining = limit - length;
|
||||
const el = document.getElementById('charCount');
|
||||
el.innerHTML = `${length}/${limit} characters${isUnicode ? ' <span style="color:#f87171;font-size:0.8em;"><i class="fa-solid fa-triangle-exclamation"></i> Unicode encoding — limit reduced to 70</span>' : ''}`;
|
||||
el.className = `d-block mb-3 ${remaining <= 10 ? (remaining <= 0 ? 'text-danger' : 'text-warning') : 'text-muted'}`;
|
||||
}
|
||||
|
||||
function updatePreview() {
|
||||
const template = document.getElementById('template').value;
|
||||
const previewEl = document.getElementById('preview');
|
||||
const previewSection = previewEl.closest('section');
|
||||
if (template.trim() === '') {
|
||||
previewSection.style.visibility = 'hidden';
|
||||
previewEl.textContent = '';
|
||||
} else {
|
||||
previewSection.style.visibility = 'visible';
|
||||
previewEl.textContent = template
|
||||
.replaceAll('{name}', 'Jordan')
|
||||
.replaceAll('{workshop}', 'Axe Throwing')
|
||||
.replaceAll('{workshop_time}', '13:30');
|
||||
}
|
||||
updateCharCount(template);
|
||||
}
|
||||
|
||||
async function saveTemplate() {
|
||||
const name = document.getElementById('templateName').value.trim();
|
||||
const body = document.getElementById('template').value.trim();
|
||||
const editId = document.getElementById('editId').value;
|
||||
if (!name || !body) { alert('Please enter a template name and message.'); return; }
|
||||
|
||||
const isEdit = editId !== '';
|
||||
const url = isEdit ? `/api/templates.php?id=${editId}` : '/api/templates.php';
|
||||
const method = isEdit ? 'PUT' : 'POST';
|
||||
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, body }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
alert('Error: ' + (err.error ?? 'Unknown error'));
|
||||
return;
|
||||
}
|
||||
cancelEdit();
|
||||
loadTemplates();
|
||||
}
|
||||
|
||||
function editTemplate(id, name, body) {
|
||||
document.getElementById('editId').value = id;
|
||||
document.getElementById('templateName').value = name;
|
||||
document.getElementById('template').value = body;
|
||||
document.getElementById('formTitle').textContent = 'Edit Template';
|
||||
document.getElementById('saveBtnLabel').textContent = 'Update Template';
|
||||
document.getElementById('cancelEditBtn').classList.remove('d-none');
|
||||
document.getElementById('template').focus();
|
||||
updatePreview();
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}
|
||||
|
||||
function cancelEdit() {
|
||||
document.getElementById('editId').value = '';
|
||||
document.getElementById('templateName').value = '';
|
||||
document.getElementById('template').value = '';
|
||||
document.getElementById('formTitle').textContent = 'New Template';
|
||||
document.getElementById('saveBtnLabel').textContent = 'Save Template';
|
||||
document.getElementById('cancelEditBtn').classList.add('d-none');
|
||||
updatePreview();
|
||||
}
|
||||
|
||||
async function deleteTemplate(id) {
|
||||
if (!confirm('Delete this template?')) return;
|
||||
const res = await fetch(`/api/templates.php?id=${id}`, { method: 'DELETE' });
|
||||
if (!res.ok) { alert('Could not delete template.'); return; }
|
||||
loadTemplates();
|
||||
}
|
||||
|
||||
function esc(str) {
|
||||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
async function loadTemplates() {
|
||||
const list = document.getElementById('templateList');
|
||||
const countEl = document.getElementById('templateCount');
|
||||
list.innerHTML = '<p class="text-muted" style="font-size:0.85rem;">Loading…</p>';
|
||||
try {
|
||||
const data = await fetch('/api/templates.php').then(r => r.json());
|
||||
const templates = data.templates ?? [];
|
||||
countEl.textContent = templates.length + ' template' + (templates.length !== 1 ? 's' : '');
|
||||
if (templates.length === 0) {
|
||||
list.innerHTML = '<p class="text-muted" style="font-size:0.85rem;">No templates saved yet. Create one above.</p>';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = templates.map(t => {
|
||||
const chars = t.body.length;
|
||||
const date = new Date(t.updated_at).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
|
||||
return `
|
||||
<div style="background:var(--bg-surface);border:1px solid var(--border);border-radius:10px;padding:1rem;">
|
||||
<div class="d-flex align-items-start justify-content-between gap-2 mb-2">
|
||||
<div>
|
||||
<div style="font-weight:600;font-size:0.9rem;">${esc(t.name)}</div>
|
||||
<div class="text-muted" style="font-size:0.78rem;">Last edited ${date}</div>
|
||||
</div>
|
||||
<div class="d-flex gap-2">
|
||||
<button class="btn btn-sm btn-accent"
|
||||
onclick='editTemplate(${t.id}, ${JSON.stringify(t.name)}, ${JSON.stringify(t.body)})'>
|
||||
<i class="fa-solid fa-pen fa-fw"></i>
|
||||
</button>
|
||||
<button class="btn btn-sm btn-danger"
|
||||
onclick="deleteTemplate(${t.id})">
|
||||
<i class="fa-solid fa-trash fa-fw"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<section class="bubble-on-surface">
|
||||
<div class="from-them">${esc(t.body.replaceAll('{name}', 'Jordan').replaceAll('{workshop}', 'Axe Throwing').replaceAll('{workshop_time}', '13:30'))}</div>
|
||||
</section>
|
||||
<div class="d-flex align-items-center gap-2 mt-2">
|
||||
<span style="font-size:0.75rem;background:rgba(79,142,247,0.12);color:var(--accent);border-radius:6px;padding:0.15em 0.55em;">${chars}/160 chars</span>
|
||||
${parseInt(t.scheduled_count) > 0 ? `<span style="font-size:0.75rem;background:rgba(74,222,128,0.12);color:#4ade80;border-radius:6px;padding:0.15em 0.55em;"><i class="fa-solid fa-clock me-1"></i>Scheduled</span>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
} catch {
|
||||
list.innerHTML = '<p class="text-danger" style="font-size:0.85rem;">Could not load templates.</p>';
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('template').addEventListener('input', updatePreview);
|
||||
updatePreview();
|
||||
loadTemplates();
|
||||
</script>
|
||||
<script>
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const r = await fetch('/api/admin.php', { redirect: 'manual' });
|
||||
if (r.type === 'opaqueredirect' || !r.ok) { window.location.reload(); return; }
|
||||
const d = await r.json();
|
||||
document.getElementById('sandboxBanner').style.display = d.sandbox_mode ? '' : 'none';
|
||||
document.querySelectorAll('.admin-nav-link').forEach(el => el.classList.toggle('d-none', !d.is_admin));
|
||||
const name = d.name || d.username;
|
||||
if (name) {
|
||||
document.querySelectorAll('.nav-username').forEach(el => { el.textContent = name; });
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
checkAuth();
|
||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') checkAuth(); });
|
||||
</script>
|
||||
<script src="assets/js/app.js"></script>
|
||||
|
||||
|
||||
<nav class="bottom-nav" aria-label="Navigation">
|
||||
<a href="index.html" class="bottom-nav-item">
|
||||
<i class="fa-solid fa-house"></i>
|
||||
|
||||
Reference in New Issue
Block a user