breadcrumb.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. error_reporting(E_ALL);
  3. ini_set("display_errors", 1);
  4. date_default_timezone_set("Australia/Hobart");
  5. // Adjust path if your contracts live elsewhere.
  6. if (!defined('CONTRACTS_DIR')) {
  7. define('CONTRACTS_DIR', realpath(__DIR__ . '/contracts'));
  8. }
  9. function contract_path_for_client(string $clientid): string {
  10. $id = preg_replace('/[^A-Za-z0-9_-]/', '', $clientid);
  11. return rtrim(CONTRACTS_DIR, '/\\') . DIRECTORY_SEPARATOR . $id . '.md';
  12. }
  13. /** Very small front-matter puller; same idea as contracts admin */
  14. function extract_front_matter_fields_progress(string $file): array {
  15. $out = [];
  16. $txt = @file_get_contents($file);
  17. if (!$txt) return $out;
  18. if (!preg_match('/^---\s*\R(.*?)\R---/s', $txt, $m)) return $out;
  19. $fm = $m[1];
  20. // admin.secret or admin_secret
  21. if (preg_match('/^\s*admin\s*:\s*$(.*?)^(?=\S)/ms', $fm."\nX", $block)) {
  22. $adminBlock = $block[1];
  23. if (preg_match('/^\s*secret\s*:\s*["\']?([^"\']+)["\']?/mi', $adminBlock, $mm)) {
  24. $out['admin_secret'] = trim($mm[1]);
  25. }
  26. }
  27. if (empty($out['admin_secret']) && preg_match('/^\s*admin_secret\s*:\s*["\']?([^"\']+)["\']?/mi', $fm, $mm)) {
  28. $out['admin_secret'] = trim($mm[1]);
  29. }
  30. return $out;
  31. }
  32. /** Build the exact token we expect for the public progress page */
  33. function progress_expected_token(string $clientid, $appId): ?string {
  34. $path = contract_path_for_client($clientid);
  35. $fm = extract_front_matter_fields_progress($path);
  36. $secret = $fm['admin_secret'] ?? '';
  37. if ($secret === '') return null;
  38. return hash_hmac('sha256', 'progress|' . (string)$appId, $secret);
  39. }
  40. $cfg = require __DIR__ . '/config.php';
  41. $dsn = 'mysql:host=' . $cfg['db_host'] . ';dbname=' . $cfg['db_name'] . ';charset=utf8mb4';
  42. $options = [
  43. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  44. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  45. ];
  46. try {
  47. $pdo = new PDO($dsn, $cfg['db_username'], $cfg['db_password'], $options);
  48. } catch (PDOException $e) {
  49. exit('Database connection failed: ' . $e->getMessage());
  50. }
  51. $app_id_raw = $_GET['id'] ?? '';
  52. $token = $_GET['token'] ?? '';
  53. $app_id = preg_match('/^\d+$/', $app_id_raw) ? $app_id_raw : '0';
  54. // Verify token (optional: match your token logic)
  55. $stmt = $pdo->prepare("SELECT client_email, reference, created_at, submission_date, required_by FROM applications WHERE id = ?");
  56. $stmt->execute([$app_id]);
  57. $app = $stmt->fetch(PDO::FETCH_ASSOC);
  58. if (!$app) {
  59. http_response_code(404);
  60. exit("Application not found.");
  61. }
  62. // Fetch stages
  63. $stmt = $pdo->prepare("SELECT * FROM application_stages WHERE application_id = ? ORDER BY position ASC");
  64. $stmt->execute([$app_id]);
  65. $stages = $stmt->fetchAll(PDO::FETCH_ASSOC);
  66. $totalStages = 7;
  67. $currentStage = count(array_filter($stages, function ($s) {
  68. return strtolower(trim($s['status'] ?? '')) === 'complete';
  69. }));
  70. $progress = round(($currentStage / $totalStages) * 100);
  71. $decisionDate = null;
  72. // 1) Look for an explicit 'Council Decision Due' stage date
  73. $decisionStage = null;
  74. foreach ($stages as $s) {
  75. if (stripos($s['title'] ?? '', 'decision') !== false && !empty($s['stage_date'])) {
  76. $decisionStage = $s;
  77. break;
  78. }
  79. }
  80. if ($decisionStage) {
  81. $decisionDate = new DateTime($decisionStage['stage_date'], new DateTimeZone('Australia/Hobart'));
  82. } elseif (!empty($app['required_by'])) {
  83. $decisionDate = new DateTime($app['required_by'], new DateTimeZone('Australia/Hobart'));
  84. } elseif (!empty($app['submission_date'])) {
  85. $decisionDate = (new DateTime($app['submission_date'], new DateTimeZone('Australia/Hobart')))->modify('+42 days');
  86. }
  87. // set a friendly “end of business day” time so the countdown isn’t midnight-awkward
  88. if ($decisionDate) { $decisionDate->setTime(17, 0, 0); }
  89. $decisionIso = $decisionDate ? $decisionDate->format('c') : '';
  90. // --- Create correspondence entry ---
  91. if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_correspondence') {
  92. $tz = new DateTimeZone('Australia/Hobart');
  93. $typeAllow = ['incoming','outgoing','note'];
  94. $channelAllow = ['email','phone','portal','letter','meeting','other'];
  95. $visibilityAllow= ['client','internal'];
  96. $type = in_array($_POST['type'] ?? 'note', $typeAllow, true) ? $_POST['type'] : 'note';
  97. $channel = in_array($_POST['channel'] ?? 'other', $channelAllow, true) ? $_POST['channel'] : 'other';
  98. $visibility = in_array($_POST['visibility'] ?? 'client', $visibilityAllow, true) ? $_POST['visibility'] : 'client';
  99. $subject = trim($_POST['subject'] ?? '') ?: null;
  100. $author = trim($_POST['author'] ?? '') ?: null;
  101. $pin = isset($_POST['pin']) ? 1 : 0;
  102. $bodyRaw = trim($_POST['body'] ?? '');
  103. if ($bodyRaw === '') { $bodyRaw = '(no content)'; }
  104. // event_at: prefer user input, else "now"
  105. $eventAtRaw = trim($_POST['event_at'] ?? '');
  106. try {
  107. $eventAt = $eventAtRaw ? new DateTime($eventAtRaw, $tz) : new DateTime('now', $tz);
  108. } catch (Exception $e) {
  109. $eventAt = new DateTime('now', $tz);
  110. }
  111. $stmt = $pdo->prepare("
  112. INSERT INTO application_correspondence
  113. (application_id, event_at, type, channel, subject, body, author, visibility, pin)
  114. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  115. ");
  116. $stmt->execute([
  117. $app_id,
  118. $eventAt->format('Y-m-d H:i:s'),
  119. $type,
  120. $channel,
  121. $subject,
  122. $bodyRaw,
  123. $author,
  124. $visibility,
  125. $pin
  126. ]);
  127. // Redirect to avoid resubmission and jump to the timeline section
  128. header("Location: ".$_SERVER['REQUEST_URI']."#correspondence");
  129. exit;
  130. }
  131. // Fetch timeline (newest first; pinned first)
  132. $stmt = $pdo->prepare("
  133. SELECT id, event_at, type, channel, subject, body, author, visibility, pin, created_at
  134. FROM application_correspondence
  135. WHERE application_id = ?
  136. ORDER BY pin DESC, event_at DESC, id DESC
  137. LIMIT 200
  138. ");
  139. $stmt->execute([$app_id]);
  140. $correspondence = $stmt->fetchAll(PDO::FETCH_ASSOC);
  141. /* NEW: attachment counts (and optional details) */
  142. $fileCounts = [];
  143. $filesByCorr = []; // if you also want to list the files
  144. if (!empty($correspondence)) {
  145. $ids = array_column($correspondence, 'id');
  146. $ph = implode(',', array_fill(0, count($ids), '?'));
  147. // Count files per correspondence
  148. $qc = $pdo->prepare("
  149. SELECT correspondence_id, COUNT(*) AS n
  150. FROM application_correspondence_files
  151. WHERE correspondence_id IN ($ph)
  152. GROUP BY correspondence_id
  153. ");
  154. $qc->execute($ids);
  155. foreach ($qc->fetchAll(PDO::FETCH_ASSOC) as $r) {
  156. $fileCounts[(int)$r['correspondence_id']] = (int)$r['n'];
  157. }
  158. // OPTIONAL: load file details if you want links
  159. $qd = $pdo->prepare("
  160. SELECT correspondence_id, original_name, file_url
  161. FROM application_correspondence_files
  162. WHERE correspondence_id IN ($ph)
  163. ORDER BY id ASC
  164. ");
  165. $qd->execute($ids);
  166. foreach ($qd->fetchAll(PDO::FETCH_ASSOC) as $f) {
  167. $cid = (int)$f['correspondence_id'];
  168. if (!isset($filesByCorr[$cid])) $filesByCorr[$cid] = [];
  169. $filesByCorr[$cid][] = $f;
  170. }
  171. }
  172. // ------------------ HELPERS ------------------
  173. function render_body_html(string $text): string {
  174. // escape first
  175. $s = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
  176. // linkify http(s)
  177. $s = preg_replace('~(https?://[^\s<]+)~i', '<a href="$1" target="_blank" rel="noopener">$1</a>', $s);
  178. // newlines to <br>
  179. return nl2br($s);
  180. }
  181. // --- Require signed token from Contracts Admin link ---
  182. $clientid = $_GET['clientid'] ?? '';
  183. $token = $_GET['token'] ?? '';
  184. if (!preg_match('/^[A-Za-z0-9_-]+$/', $clientid)) {
  185. http_response_code(400);
  186. exit('Bad link (clientid).');
  187. }
  188. if ($token === '') {
  189. http_response_code(403);
  190. exit('Missing token.');
  191. }
  192. // Build expected token from the .md front matter secret
  193. $expected = progress_expected_token($clientid, $app_id);
  194. if (!$expected || !hash_equals($expected, $token)) {
  195. http_response_code(403);
  196. exit('Invalid or expired link.');
  197. }
  198. ?>
  199. <!doctype html>
  200. <html lang="en">
  201. <head>
  202. <meta charset="utf-8">
  203. <meta name="viewport" content="width=device-width, initial-scale=1">
  204. <title><?= htmlspecialchars($app['reference']) ?> – Application Progress</title>
  205. <link rel="shortcut icon" href="../../internal/images/blueprint.ico" type="image/x-icon">
  206. <meta name="robots" content="noindex">
  207. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr" crossorigin="anonymous">
  208. <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js" integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q" crossorigin="anonymous"></script>
  209. <link href="../../internal/css/blueprint.css" rel="stylesheet">
  210. <link href="../../internal/css/print.css" rel="stylesheet" media="print">
  211. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
  212. <link href="progress.css" rel="stylesheet">
  213. <style>
  214. .popover-attachments { max-width: 360px; }
  215. .popover-attachments .popover-body { padding: .5rem .75rem; }
  216. </style>
  217. </head>
  218. <body>
  219. <!--
  220. <nav class="navbar bg-dark border-bottom border-body d-print-none" data-bs-theme="dark">
  221. <div class="container">
  222. <a class="navbar-brand text-white" href="#">
  223. <img src="../internal/images/blueprint-logo-light.png" width="30" height="24" class="d-inline-block align-text-top" alt="Modulos">
  224. Modulos Design
  225. </a>
  226. </div>
  227. </nav>
  228. -->
  229. <main class="container my-4">
  230. <div class="bg-white p-4 p-md-5 rounded-0 shadow-sm">
  231. <div class="row align-items-center page-header">
  232. <div class="col-12 col-md-6 text-start">
  233. <!-- CUSTOMER DETAILS HERE -->
  234. </div>
  235. <div class="col-12 col-md-6 text-end pt-2">
  236. <h3 class="fw-bold mb-1 text-dark">Development Application</h3>
  237. <h3 class="fw-bold mb-1 text-dark">Application No: <?= htmlspecialchars($app['reference']) ?></h3>
  238. <h5 class="mb-0 text-muted">Started: <?= date("d M Y", strtotime($app['created_at'])) ?></h5>
  239. </div>
  240. </div>
  241. <hr class="my-4">
  242. <div class="row my-4">
  243. <div class="col-12 align-self-center">
  244. <div class="steps">
  245. <?php
  246. $labels = ['Submit','Acknowledge','Paid','Confirmed','Advertise','Complete','Decision'];
  247. $N = count($labels);
  248. // Build status + date arrays by position
  249. $statusByIndex = array_fill(0, $N, 'pending');
  250. $dateByIndex = array_fill(0, $N, null);
  251. foreach ($stages as $row) {
  252. $idx = (int)($row['position'] ?? -1);
  253. if ($idx < 0 || $idx >= $N) continue;
  254. $st = strtolower(trim($row['status'] ?? 'pending'));
  255. if (!in_array($st, ['complete','current','pending'], true)) $st = 'pending';
  256. $statusByIndex[$idx] = $st;
  257. $dateByIndex[$idx] = $row['stage_date'] ?: ($row['updated_at'] ?: ($row['created_at'] ?? null));
  258. }
  259. // If no explicit "current", highlight the *last complete* stage
  260. $hasCurrent = false;
  261. foreach ($statusByIndex as $st) { if (strpos($st, 'current') !== false) { $hasCurrent = true; break; } }
  262. if (!$hasCurrent) {
  263. $lastComplete = -1;
  264. for ($i = 0; $i < $N; $i++) if ($statusByIndex[$i] === 'complete') $lastComplete = $i;
  265. if ($lastComplete >= 0) {
  266. $statusByIndex[$lastComplete] = 'current'; // keep green, add highlight
  267. } else {
  268. $statusByIndex[0] = trim($statusByIndex[0] . ' current'); // nothing complete yet
  269. }
  270. }
  271. $fmt = function (?string $s): string {
  272. if (!$s) return '';
  273. $t = strtotime($s);
  274. return $t ? date('d M Y', $t) : '';
  275. };
  276. ?>
  277. <!-- Top row: arrows + inline (mobile-only) dates -->
  278. <ul class="step-menu">
  279. <?php for ($i = 0; $i < $N; $i++):
  280. $class = htmlspecialchars($statusByIndex[$i]);
  281. $dateText = $fmt($dateByIndex[$i]);
  282. $isComplete = (strpos($class, 'complete') !== false);
  283. $prefix = (!$isComplete && $dateText) ? 'Due ' : '';
  284. ?>
  285. <li class="<?= $class ?>">
  286. <?= htmlspecialchars($labels[$i]) ?>
  287. <?php if ($dateText): ?>
  288. <div class="date-inline small mt-1 d-xxl-none"><?= htmlspecialchars($prefix . $dateText) ?></div>
  289. <?php endif; ?>
  290. </li>
  291. <?php endfor; ?>
  292. </ul>
  293. <!-- Bottom row: desktop-only date line, aligned with arrows -->
  294. <ul class="step-dates d-none d-xxl-flex">
  295. <?php for ($i = 0; $i < $N; $i++):
  296. $rawClass = trim((string)($statusByIndex[$i] ?? ''));
  297. $tokens = preg_split('/\s+/', $rawClass, -1, PREG_SPLIT_NO_EMPTY);
  298. $isComplete = in_array('complete', $tokens, true);
  299. $isCurrent = in_array('current', $tokens, true);
  300. $dateText = $fmt($dateByIndex[$i]);
  301. $prefix = (!$isComplete && !$isCurrent && $dateText) ? 'Due ' : '';
  302. ?>
  303. <li class="<?= htmlspecialchars($rawClass, ENT_QUOTES, 'UTF-8') ?>">
  304. <?= $dateText ? htmlspecialchars($prefix . $dateText, ENT_QUOTES, 'UTF-8') : '&nbsp;' ?>
  305. </li>
  306. <?php endfor; ?>
  307. </ul>
  308. </div>
  309. </div>
  310. </div>
  311. <div class="row py-3">
  312. <div class="col-12">
  313. <?php if (!empty($decisionIso)): ?>
  314. <div class="countdown" data-target-date="<?php echo $decisionIso; ?>"></div>
  315. <?php endif; ?>
  316. </div>
  317. </div>
  318. <div class="row">
  319. <?php if (empty($stages)): ?>
  320. <div class="col-12">
  321. <div class="alert alert-warning">This application has not started yet.</div>
  322. </div>
  323. <?php endif; ?>
  324. </div>
  325. <hr class="my-4">
  326. <div class="row">
  327. <div class="col-12 text-center">
  328. <h4>Timeline of Correspondence</h4>
  329. </div>
  330. </div>
  331. <div class="row py-3">
  332. <div class="col">
  333. <div class="timeline">
  334. <?php
  335. $badgeMap = [
  336. 'email_incoming' => 'bi-envelope-arrow-up',
  337. 'email_outgoing' => 'bi-send-check',
  338. 'phone_incoming' => 'bi-telephone-inbound',
  339. 'phone_outgoing' => 'bi-telephone-outbound',
  340. 'note' => 'bi-journal-text'
  341. ];
  342. $fallbackByChannel = [
  343. 'email' => 'bi-envelope',
  344. 'phone' => 'bi-telephone',
  345. 'meeting' => 'bi-people',
  346. 'other' => 'bi-chat-dots'
  347. ];
  348. $typeLabel = ['incoming'=>'Incoming','outgoing'=>'Outgoing','note'=>'Note'];
  349. $chLabel = ['email'=>'Email','phone'=>'Phone','meeting'=>'Meeting','other'=>'Other'];
  350. foreach ($correspondence as $row):
  351. $id = (int)$row['id'];
  352. $typeVal = strtolower(trim($row['type'] ?? 'note'));
  353. $channelVal = strtolower(trim($row['channel'] ?? 'other'));
  354. $key = ($typeVal === 'note') ? 'note' : "{$channelVal}_{$typeVal}";
  355. $icon = $badgeMap[$key] ?? ($fallbackByChannel[$channelVal] ?? 'bi-journal-text');
  356. $when = (new DateTime($row['event_at'], new DateTimeZone('Australia/Hobart')))->format('d M Y, h:ia');
  357. $visBadge = $row['visibility']==='internal' ? '<span class="badge rounded-pill text-bg-secondary ms-2">Internal</span>' : '';
  358. $typeClass = 'type-'.preg_replace('/[^a-z]/','', $typeVal);
  359. $numFiles = $fileCounts[$id] ?? 0; // <- NEW
  360. $hasFiles = $numFiles > 0; // <- NEW
  361. ?>
  362. <div class="timeline-item <?= $row['pin'] ? 'pinned' : '' ?>">
  363. <div class="timeline-badge"><i class="bi <?= $icon ?>"></i></div>
  364. <div class="timeline-panel <?= $typeClass ?>">
  365. <div class="timeline-heading d-flex justify-content-between align-items-start">
  366. <div>
  367. <h6 class="mb-1">
  368. <?= $when ?> • <?= $typeLabel[$typeVal] ?? ucfirst($typeVal) ?>
  369. via <?= $chLabel[$channelVal] ?? ucfirst($channelVal) ?>
  370. <?= $visBadge ?>
  371. <?php if ($row['pin']): ?>
  372. <i class="bi bi-pin-angle-fill text-warning ms-1" title="Pinned"></i>
  373. <?php endif; ?>
  374. <?php if (!empty($filesByCorr[$id])): ?>
  375. <span class="ms-2 att-pop"
  376. role="button"
  377. tabindex="0"
  378. data-bs-toggle="popover"
  379. data-bs-trigger="hover focus"
  380. data-bs-placement="top"
  381. data-bs-custom-class="popover-attachments"
  382. data-content-id="att-popover-<?= $id ?>"
  383. title="Attachments (<?= (int)$numFiles ?>)">
  384. <i class="bi bi-paperclip"></i>
  385. </span>
  386. <?php endif; ?>
  387. </h6>
  388. <small class="text-muted">
  389. <?= htmlspecialchars($row['subject'] ?: ucfirst($typeVal)) ?>
  390. <?= $row['author'] ? ' • by: '.htmlspecialchars($row['author']) : '' ?>
  391. </small>
  392. </div>
  393. </div>
  394. <div class="timeline-body mt-2 small">
  395. <?= render_body_html($row['body']) ?>
  396. </div>
  397. </div>
  398. </div>
  399. <?php endforeach; ?>
  400. <?php if (empty($correspondence)): ?>
  401. <div class="text-muted">No correspondence recorded yet.</div>
  402. <?php endif; ?>
  403. </div>
  404. </div>
  405. </div>
  406. </div>
  407. </main>
  408. <script>
  409. const countdownEls = document.querySelectorAll(".countdown")
  410. countdownEls.forEach(countdownEl => createCountdown(countdownEl))
  411. function createCountdown(countdownEl){
  412. const target = new Date(new Date(countdownEl.dataset.targetDate).toLocaleString('en', ))
  413. const parts = {
  414. days: {text: ["days","day"], dots: 30},
  415. hours: {text: ["hours","hour"], dots: 24},
  416. minutes: {text: ["minutes","minute"], dots: 60},
  417. seconds: {text: ["seconds","second"], dots: 60},
  418. }
  419. Object.entries(parts).forEach(([key, value])=>{
  420. const partEl = document.createElement("div");
  421. partEl.classList.add("part", key);
  422. partEl.style.setProperty("--dots", value.dots);
  423. value.element = partEl;
  424. const remainingEl = document.createElement("div");
  425. remainingEl.classList.add("remaining");
  426. remainingEl.innerHTML = `<span class="number"></span><span class="text"></span>`
  427. partEl.append(remainingEl);
  428. for(let i = 0; i < value.dots; i++){
  429. const dotContainerEl = document.createElement("div");
  430. dotContainerEl.style.setProperty("--dot-idx", i);
  431. dotContainerEl.classList.add("dot-container")
  432. const dotEl = document.createElement("div");
  433. dotEl.classList.add("dot")
  434. dotContainerEl.append(dotEl);
  435. partEl.append(dotContainerEl);
  436. }
  437. countdownEl.append(partEl);
  438. })
  439. getRemainingTime(target, parts)
  440. }
  441. function getRemainingTime(target, parts, first=true){
  442. const now = new Date()
  443. if(first) console.log({target, now})
  444. const remaining = {}
  445. let seconds = Math.floor((target - (now))/1000);
  446. let minutes = Math.floor(seconds/60);
  447. let hours = Math.floor(minutes/60);
  448. let days = Math.floor(hours/24);
  449. hours = hours-(days*24);
  450. minutes = minutes-(days*24*60)-(hours*60);
  451. seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);
  452. Object.entries({days, hours, minutes, seconds}).forEach(([key, value])=>{
  453. const remaining = parts[key].element.querySelector(".number");
  454. const text = parts[key].element.querySelector(".text");
  455. remaining.innerText = value;
  456. text.innerText = parts[key].text[Number(value==1)]
  457. const dots = parts[key].element.querySelectorAll(".dot")
  458. dots.forEach((dot, idx)=>{
  459. dot.dataset.active = idx <= value;
  460. dot.dataset.lastactive = idx == value;
  461. })
  462. })
  463. if(now <= target){
  464. window.requestAnimationFrame(()=>{
  465. getRemainingTime(target, parts, false)
  466. });
  467. }
  468. }
  469. document.getElementById('tryParse')?.addEventListener('click', function(e){
  470. e.preventDefault();
  471. const body = document.getElementById('corrBody').value || '';
  472. const subj = /(?:^|\n)Subject:\s*(.+)/i.exec(body);
  473. const from = /(?:^|\n)From:\s*(.+)/i.exec(body);
  474. const date = /(?:^|\n)Date:\s*(.+)/i.exec(body);
  475. if (subj) document.getElementById('corrSubject').value = subj[1].trim();
  476. if (from) document.getElementById('corrAuthor').value = from[1].trim();
  477. if (date) {
  478. const guess = new Date(date[1]);
  479. if (!isNaN(guess.getTime())) {
  480. // to local datetime-local string
  481. const pad = n => String(n).padStart(2,'0');
  482. const v = guess.getFullYear() + '-' + pad(guess.getMonth()+1) + '-' + pad(guess.getDate())
  483. + 'T' + pad(guess.getHours()) + ':' + pad(guess.getMinutes());
  484. const el = document.querySelector('input[name="event_at"]');
  485. if (el) el.value = v;
  486. }
  487. }
  488. });
  489. document.addEventListener('DOMContentLoaded', () => {
  490. document.querySelectorAll('[data-bs-toggle="popover"][data-content-id]').forEach(el => {
  491. const id = el.getAttribute('data-content-id');
  492. const tpl = document.getElementById(id);
  493. const content = tpl ? tpl.innerHTML : '';
  494. new bootstrap.Popover(el, {
  495. html: true,
  496. content,
  497. container: 'body',
  498. sanitize: true, // keep Bootstrap’s sanitizer on
  499. trigger: 'hover focus' // hover on desktop, tap/focus on mobile
  500. });
  501. });
  502. });
  503. </script>
  504. </body>
  505. </html>