progress.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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, clock_paused, clock_paused_at, clock_pause_reason 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. $isPaused = (int)($app['clock_paused'] ?? 0) === 1;
  72. $pauseReason = trim((string)($app['clock_pause_reason'] ?? ''));
  73. $decisionDate = null;
  74. // 1) Look for an explicit 'Council Decision Due' stage date
  75. $decisionStage = null;
  76. foreach ($stages as $s) {
  77. if (stripos($s['title'] ?? '', 'decision') !== false && !empty($s['stage_date'])) {
  78. $decisionStage = $s;
  79. break;
  80. }
  81. }
  82. if ($decisionStage) {
  83. $decisionDate = new DateTime($decisionStage['stage_date'], new DateTimeZone('Australia/Hobart'));
  84. } elseif (!empty($app['required_by'])) {
  85. $decisionDate = new DateTime($app['required_by'], new DateTimeZone('Australia/Hobart'));
  86. } elseif (!empty($app['submission_date'])) {
  87. $decisionDate = (new DateTime($app['submission_date'], new DateTimeZone('Australia/Hobart')))->modify('+42 days');
  88. }
  89. // set a friendly “end of business day” time so the countdown isn’t midnight-awkward
  90. if ($decisionDate) { $decisionDate->setTime(17, 0, 0); }
  91. $decisionIso = $decisionDate ? $decisionDate->format('c') : '';
  92. // --- Create correspondence entry ---
  93. if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_correspondence') {
  94. $tz = new DateTimeZone('Australia/Hobart');
  95. $typeAllow = ['incoming','outgoing','note'];
  96. $channelAllow = ['email','phone','portal','letter','meeting','other'];
  97. $visibilityAllow= ['client','internal'];
  98. $type = in_array($_POST['type'] ?? 'note', $typeAllow, true) ? $_POST['type'] : 'note';
  99. $channel = in_array($_POST['channel'] ?? 'other', $channelAllow, true) ? $_POST['channel'] : 'other';
  100. $visibility = in_array($_POST['visibility'] ?? 'client', $visibilityAllow, true) ? $_POST['visibility'] : 'client';
  101. $subject = trim($_POST['subject'] ?? '') ?: null;
  102. $author = trim($_POST['author'] ?? '') ?: null;
  103. $pin = isset($_POST['pin']) ? 1 : 0;
  104. $bodyRaw = trim($_POST['body'] ?? '');
  105. if ($bodyRaw === '') { $bodyRaw = '(no content)'; }
  106. // event_at: prefer user input, else "now"
  107. $eventAtRaw = trim($_POST['event_at'] ?? '');
  108. try {
  109. $eventAt = $eventAtRaw ? new DateTime($eventAtRaw, $tz) : new DateTime('now', $tz);
  110. } catch (Exception $e) {
  111. $eventAt = new DateTime('now', $tz);
  112. }
  113. $stmt = $pdo->prepare("
  114. INSERT INTO application_correspondence
  115. (application_id, event_at, type, channel, subject, body, author, visibility, pin)
  116. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  117. ");
  118. $stmt->execute([
  119. $app_id,
  120. $eventAt->format('Y-m-d H:i:s'),
  121. $type,
  122. $channel,
  123. $subject,
  124. $bodyRaw,
  125. $author,
  126. $visibility,
  127. $pin
  128. ]);
  129. // Redirect to avoid resubmission and jump to the timeline section
  130. header("Location: ".$_SERVER['REQUEST_URI']."#correspondence");
  131. exit;
  132. }
  133. // Fetch timeline (newest first; pinned first)
  134. $stmt = $pdo->prepare("
  135. SELECT id, event_at, type, channel, subject, body, author, visibility, pin, created_at
  136. FROM application_correspondence
  137. WHERE application_id = ?
  138. ORDER BY pin DESC, event_at DESC, id DESC
  139. LIMIT 200
  140. ");
  141. $stmt->execute([$app_id]);
  142. $correspondence = $stmt->fetchAll(PDO::FETCH_ASSOC);
  143. /* NEW: attachment counts (and optional details) */
  144. $fileCounts = [];
  145. $filesByCorr = []; // if you also want to list the files
  146. if (!empty($correspondence)) {
  147. $ids = array_column($correspondence, 'id');
  148. $ph = implode(',', array_fill(0, count($ids), '?'));
  149. // Count files per correspondence
  150. $qc = $pdo->prepare("
  151. SELECT correspondence_id, COUNT(*) AS n
  152. FROM application_correspondence_files
  153. WHERE correspondence_id IN ($ph)
  154. GROUP BY correspondence_id
  155. ");
  156. $qc->execute($ids);
  157. foreach ($qc->fetchAll(PDO::FETCH_ASSOC) as $r) {
  158. $fileCounts[(int)$r['correspondence_id']] = (int)$r['n'];
  159. }
  160. // OPTIONAL: load file details if you want links
  161. $qd = $pdo->prepare("
  162. SELECT correspondence_id, original_name, file_url
  163. FROM application_correspondence_files
  164. WHERE correspondence_id IN ($ph)
  165. ORDER BY id ASC
  166. ");
  167. $qd->execute($ids);
  168. foreach ($qd->fetchAll(PDO::FETCH_ASSOC) as $f) {
  169. $cid = (int)$f['correspondence_id'];
  170. if (!isset($filesByCorr[$cid])) $filesByCorr[$cid] = [];
  171. $filesByCorr[$cid][] = $f;
  172. }
  173. }
  174. // ------------------ HELPERS ------------------
  175. function render_body_html(string $text): string {
  176. // escape first
  177. $s = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
  178. // linkify http(s)
  179. $s = preg_replace('~(https?://[^\s<]+)~i', '<a href="$1" target="_blank" rel="noopener">$1</a>', $s);
  180. // newlines to <br>
  181. return nl2br($s);
  182. }
  183. function stage_icon_for(string $title): string {
  184. $t = strtolower($title);
  185. if (str_contains($t,'submit')) return 'bi-upload';
  186. if (str_contains($t,'ack')) return 'bi-inbox';
  187. if (str_contains($t,'fee') || str_contains($t,'paid')) return 'bi-cash-coin';
  188. if (str_contains($t,'valid') || str_contains($t,'confirm')) return 'bi-check2-circle';
  189. if (str_contains($t,'advert')) return 'bi-megaphone';
  190. if (str_contains($t,'decision')) return 'bi-check-circle-fill';
  191. return 'bi-flag';
  192. }
  193. // Admin bypass: valid HTTP Basic Auth skips the client token check
  194. $_au = $cfg['admin_user'] ?? '';
  195. $_ap = $cfg['admin_pass'] ?? '';
  196. $isAdmin = $_au !== '' && $_ap !== ''
  197. && isset($_SERVER['PHP_AUTH_USER'])
  198. && $_SERVER['PHP_AUTH_USER'] === $_au
  199. && ($_SERVER['PHP_AUTH_PW'] ?? '') === $_ap;
  200. if (!$isAdmin) {
  201. // --- Require signed token from Contracts Admin link ---
  202. $clientid = $_GET['clientid'] ?? '';
  203. $token = $_GET['token'] ?? '';
  204. if (!preg_match('/^[A-Za-z0-9_-]+$/', $clientid)) {
  205. http_response_code(400);
  206. exit('Bad link (clientid).');
  207. }
  208. if ($token === '') {
  209. header('WWW-Authenticate: Basic realm="Modulos Contracts Admin"');
  210. http_response_code(403);
  211. exit('Missing token.');
  212. }
  213. // Build expected token from the .md front matter secret
  214. $expected = progress_expected_token($clientid, $app_id);
  215. if (!$expected || !hash_equals($expected, $token)) {
  216. http_response_code(403);
  217. exit('Invalid or expired link.');
  218. }
  219. }
  220. unset($_au, $_ap);
  221. ?>
  222. <!doctype html>
  223. <html lang="en">
  224. <head>
  225. <meta charset="utf-8">
  226. <meta name="viewport" content="width=device-width, initial-scale=1">
  227. <title> <?= htmlspecialchars($app['reference']) ?> – Application Progress</title>
  228. <link rel="shortcut icon" href="../../internal/images/blueprint.ico" type="image/x-icon">
  229. <meta name="robots" content="noindex">
  230. <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">
  231. <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js" integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q" crossorigin="anonymous"></script>
  232. <link href="../../internal/css/blueprint.css" rel="stylesheet">
  233. <link href="../../internal/css/print.css" rel="stylesheet" media="print">
  234. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
  235. <link href="progress.css" rel="stylesheet">
  236. <style>
  237. .popover-attachments {
  238. max-width: 360px;
  239. }
  240. .popover-attachments .popover-body {
  241. padding: .5rem .75rem;
  242. }
  243. /* wrapper so lots of steps can scroll horizontally on small screens */
  244. .timeline-wrap {
  245. overflow-x: auto;
  246. -webkit-overflow-scrolling: touch;
  247. padding-bottom: .25rem;
  248. /* keep scrollbar off arrows */
  249. }
  250. /* your snippet */
  251. #timeline {
  252. list-style: none;
  253. display: flex;
  254. width: 100%;
  255. margin: 0;
  256. }
  257. #timeline .icon {
  258. font-size: 14px;
  259. }
  260. #timeline li {
  261. flex: 1 1 0;
  262. min-width: 0;
  263. }
  264. #timeline li a {
  265. color: #FFF;
  266. display: block;
  267. background: #3498db;
  268. text-decoration: none;
  269. position: relative;
  270. height: 40px;
  271. line-height: 40px;
  272. padding: 0 12px 0 8px;
  273. text-align: center;
  274. margin-right: 23px;
  275. white-space: nowrap;
  276. }
  277. #timeline li:nth-child(even) a {
  278. background-color: #2980b9;
  279. }
  280. #timeline li:nth-child(even) a:before {
  281. border-color: #2980b9;
  282. border-left-color: transparent;
  283. }
  284. #timeline li:nth-child(even) a:after {
  285. border-left-color: #2980b9;
  286. }
  287. #timeline li:first-child a {
  288. padding-left: 15px;
  289. border-radius: 0;
  290. }
  291. #timeline li:first-child a:before {
  292. border: none;
  293. }
  294. #timeline li:last-child a {
  295. padding-right: 15px;
  296. border-radius: 0;
  297. }
  298. #timeline li:last-child a:after {
  299. border: none;
  300. }
  301. #timeline li a:before,
  302. #timeline li a:after {
  303. content: "";
  304. position: absolute;
  305. top: 0;
  306. border: 0 solid #3498db;
  307. border-width: 20px 10px;
  308. width: 0;
  309. height: 0;
  310. }
  311. #timeline li a:before {
  312. left: -20px;
  313. border-left-color: transparent;
  314. }
  315. #timeline li a:after {
  316. left: 100%;
  317. border-color: transparent;
  318. border-left-color: #3498db;
  319. }
  320. #timeline li a:hover {
  321. background-color: #1abc9c;
  322. }
  323. #timeline li a:hover:before {
  324. border-color: #1abc9c;
  325. border-left-color: transparent;
  326. }
  327. #timeline li a:hover:after {
  328. border-left-color: #1abc9c;
  329. }
  330. #timeline li a:active {
  331. background-color: #16a085;
  332. }
  333. #timeline li a:active:before {
  334. border-color: #16a085;
  335. border-left-color: transparent;
  336. }
  337. #timeline li a:active:after {
  338. border-left-color: #16a085;
  339. }
  340. /* Icon tweaks inside the pill */
  341. #timeline li a .bi {
  342. font-size: 1rem;
  343. vertical-align: -1px;
  344. margin-right: .35rem;
  345. }
  346. #timeline li a small {
  347. opacity: .9;
  348. margin-left: .35rem;
  349. }
  350. /* Stack on small screens (match original breakpoint) */
  351. @media (max-width: 1399px) {
  352. #timeline {
  353. display: block;
  354. }
  355. /* stop flex row */
  356. #timeline li {
  357. flex: 0 0 100%;
  358. max-width: 100%;
  359. margin: .5rem 0;
  360. }
  361. #timeline li a {
  362. height: auto;
  363. line-height: 1.3;
  364. padding: .65rem .9rem;
  365. /* comfy pill */
  366. border-radius: .25rem;
  367. }
  368. /* remove arrow heads when stacked */
  369. #timeline li a:before,
  370. #timeline li a:after {
  371. content: none !important;
  372. border: 0 !important;
  373. }
  374. }
  375. /* ---- STATE COLOURS (match original) ---- */
  376. #timeline li.is-current a {
  377. background: #97846E;
  378. /* brown */
  379. color: #EADFD7;
  380. /* cream text */
  381. }
  382. #timeline li.is-current a:before {
  383. border-color: #97846E;
  384. border-left-color: transparent;
  385. }
  386. #timeline li.is-current a:after {
  387. border-left-color: #97846E;
  388. }
  389. /* “Complete” = green pill + dark green text */
  390. #timeline li.is-complete a {
  391. background: #d1e7dd;
  392. color: #0f5132;
  393. }
  394. #timeline li.is-complete a:before {
  395. border-color: #d1e7dd;
  396. border-left-color: transparent;
  397. }
  398. #timeline li.is-complete a:after {
  399. border-left-color: #d1e7dd;
  400. }
  401. /* “Pending / Upcoming” greys */
  402. #timeline li.is-pending a {
  403. background: #e9ecef;
  404. color: #055160;
  405. /* same as original */
  406. }
  407. #timeline li.is-pending a:before {
  408. border-color: #e9ecef;
  409. border-left-color: transparent;
  410. }
  411. #timeline li.is-pending a:after {
  412. border-left-color: #e9ecef;
  413. }
  414. /* optional alias if you ever emit `is-upcoming` */
  415. #timeline li.is-upcoming a {
  416. background: #dee2e6;
  417. color: #495057;
  418. }
  419. #timeline li.is-upcoming a:before {
  420. border-color: #dee2e6;
  421. border-left-color: transparent;
  422. }
  423. #timeline li.is-upcoming a:after {
  424. border-left-color: #dee2e6;
  425. }
  426. /* Ensure state colours don’t change on hover */
  427. #timeline li.is-current a:hover,
  428. #timeline li.is-complete a:hover,
  429. #timeline li.is-pending a:hover,
  430. #timeline li.is-upcoming a:hover {
  431. background: inherit;
  432. color: inherit;
  433. }
  434. #timeline li.is-current a:hover:before,
  435. #timeline li.is-complete a:hover:before,
  436. #timeline li.is-pending a:hover:before,
  437. #timeline li.is-upcoming a:hover:before {
  438. border-color: inherit;
  439. border-left-color: transparent;
  440. }
  441. #timeline li.is-current a:hover:after,
  442. #timeline li.is-complete a:hover:after,
  443. #timeline li.is-pending a:hover:after,
  444. #timeline li.is-upcoming a:hover:after {
  445. border-left-color: currentColor;
  446. /* overridden below for exact bg match */
  447. }
  448. /* Keep triangle colour exactly the same as the pill bg */
  449. #timeline li.is-current a:hover:after {
  450. border-left-color: #97846E;
  451. }
  452. #timeline li.is-complete a:hover:after {
  453. border-left-color: #d1e7dd;
  454. }
  455. #timeline li.is-pending a:hover:after {
  456. border-left-color: #e9ecef;
  457. }
  458. #timeline li.is-upcoming a:hover:after {
  459. border-left-color: #dee2e6;
  460. }
  461. /* Dates row colours (xxl-only row in your markup) */
  462. .step-dates li.is-complete {
  463. color: #0f5132;
  464. }
  465. .step-dates li.is-current {
  466. color: #7c6a57;
  467. font-weight: 600;
  468. }
  469. .step-dates li.is-pending,
  470. .step-dates li.is-upcoming {
  471. color: #6c757d;
  472. }
  473. /* Stack rules you already added still apply */
  474. @media (max-width: 1399px) {
  475. #timeline {
  476. display: block;
  477. }
  478. #timeline li {
  479. flex: 0 0 100%;
  480. max-width: 100%;
  481. margin: .5rem 0;
  482. }
  483. #timeline li a {
  484. height: auto;
  485. line-height: 1.3;
  486. padding: .65rem .9rem;
  487. border-radius: .25rem;
  488. }
  489. #timeline li a:before,
  490. #timeline li a:after {
  491. content: none !important;
  492. border: 0 !important;
  493. }
  494. }
  495. </style>
  496. </head>
  497. <body>
  498. <!--
  499. <nav class="navbar bg-dark border-bottom border-body d-print-none" data-bs-theme="dark"><div class="container"><a class="navbar-brand text-white" href="#"><img src="../internal/images/blueprint-logo-light.png" width="30" height="24" class="d-inline-block align-text-top" alt="Modulos">
  500. Modulos Design
  501. </a></div></nav>
  502. -->
  503. <main class="container my-4">
  504. <div class="bg-white p-4 p-md-5 rounded-0 shadow-sm">
  505. <div class="row align-items-center page-header">
  506. <div class="col-12 col-md-6 text-start">
  507. <!-- CUSTOMER DETAILS HERE -->
  508. </div>
  509. <div class="col-12 col-md-6 text-end pt-2">
  510. <h3 class="fw-bold mb-1 text-dark">Development Application</h3>
  511. <h3 class="fw-bold mb-1 text-dark">Application No: <?= htmlspecialchars($app['reference']) ?> </h3>
  512. <h5 class="mb-0 text-muted">Started: <?= date("d M Y", strtotime($app['created_at'])) ?> </h5>
  513. </div>
  514. </div>
  515. <hr class="my-4">
  516. <div class="row my-4">
  517. <div class="col-12 align-self-center">
  518. <div class="steps"> <?php
  519. // Build a flexible steps array straight from DB rows (ordered by position)
  520. $steps = [];
  521. foreach ($stages as $row) {
  522. $steps[] = [
  523. 'title' => trim($row['title'] ?? '') ?: ('Stage ' . (string)($row['position'] + 1)),
  524. 'status' => in_array(strtolower($row['status'] ?? ''), ['complete','current','pending'], true)
  525. ? strtolower($row['status'])
  526. : 'pending',
  527. 'date' => $row['stage_date'] ?: ($row['updated_at'] ?: ($row['created_at'] ?? null)),
  528. ];
  529. }
  530. // Ensure we always have a “current”
  531. $hasCurrent = false;
  532. foreach ($steps as $s) { if (($s['status'] ?? '') === 'current') { $hasCurrent = true; break; } }
  533. if (!$hasCurrent && !empty($steps)) {
  534. $lastComplete = -1;
  535. foreach ($steps as $i => $s) if (($s['status'] ?? '') === 'complete') $lastComplete = $i;
  536. if ($lastComplete >= 0) $steps[$lastComplete]['status'] = 'current';
  537. else $steps[0]['status'] = 'current';
  538. }
  539. // formatter
  540. $fmtDate = function ($v) {
  541. $t = $v ? strtotime($v) : 0;
  542. return $t ? date('D d M y', $t) : '';
  543. };
  544. ?> <div class="timeline-wrap text-center my-4">
  545. <ul id="timeline" class="mb-0 w-100 "> <?php foreach ($steps as $s):
  546. $state = 'is-' . ($s['status'] ?? 'pending');
  547. $titleSafe = htmlspecialchars($s['title'], ENT_QUOTES, 'UTF-8');
  548. $dateText = $fmtDate($s['date']);
  549. $iconClass = stage_icon_for($s['title']);
  550. $isComplete = ($s['status'] === 'complete');
  551. $isCurrent = ($s['status'] === 'current');
  552. $prefix = (!$isComplete && !$isCurrent && $dateText) ? 'Due ' : '';
  553. $tooltip = $titleSafe . ($dateText ? ' — ' . $prefix . $dateText : '');
  554. ?>
  555. <li class="
  556. <?= $state ?>">
  557. <a href="#" title="
  558. <?= $tooltip ?>">
  559. <span class="bi
  560. <?= $iconClass ?>">
  561. </span> <?= $titleSafe ?> <?php if ($dateText): ?> <small class="d-block d-xxl-none opacity-75 ms-4"> <?= htmlspecialchars($prefix . $dateText, ENT_QUOTES, 'UTF-8') ?> </small> <?php endif; ?> </a>
  562. </li> <?php endforeach; ?> </ul>
  563. <ul class="step-dates d-none d-xxl-flex"> <?php foreach ($steps as $s):
  564. $state = 'is-' . ($s['status'] ?? 'pending');
  565. $dateText = $fmtDate($s['date']);
  566. $isComplete = ($s['status'] === 'complete');
  567. $isCurrent = ($s['status'] === 'current');
  568. $prefix = (!$isComplete && !$isCurrent && $dateText) ? 'Due ' : '';
  569. ?>
  570. <li class="
  571. <?= htmlspecialchars($state, ENT_QUOTES, 'UTF-8') ?>"> <?= $dateText ? htmlspecialchars($prefix . $dateText, ENT_QUOTES, 'UTF-8') : '&nbsp;' ?> </li> <?php endforeach; ?> </ul>
  572. </div>
  573. <div class="row px-5">
  574. <div class="col-12"> <?php if (!empty($decisionIso)): ?> <?php if ($isPaused): ?> <div class="alert alert-warning d-flex align-items-center" role="alert">
  575. <i class="bi bi-pause-circle me-2"></i>
  576. <div> Statutory clock paused by council request. <?php if ($pauseReason !== ''): ?> <span class="text-muted">Reason: <?= htmlspecialchars($pauseReason) ?> </span> <?php endif; ?> </div>
  577. </div>
  578. <!-- No ticking countdown shown while paused --> <?php else: ?> <div class="countdown" data-target-date="
  579. <?= htmlspecialchars($decisionIso) ?>">
  580. </div> <?php endif; ?> <?php endif; ?> </div>
  581. </div>
  582. <div class="row"> <?php if (empty($stages)): ?> <div class="col-12">
  583. <div class="alert alert-warning">This application has not started yet.</div>
  584. </div> <?php endif; ?> </div>
  585. <hr class="my-4">
  586. <div class="row">
  587. <div class="col-12 text-center">
  588. <h4>Timeline of Correspondence</h4>
  589. </div>
  590. </div>
  591. <div class="row py-3">
  592. <div class="col">
  593. <div class="timeline"> <?php
  594. $badgeMap = [
  595. 'email_incoming' => 'bi-envelope-arrow-up',
  596. 'email_outgoing' => 'bi-send-check',
  597. 'phone_incoming' => 'bi-telephone-inbound',
  598. 'phone_outgoing' => 'bi-telephone-outbound',
  599. 'note' => 'bi-journal-text'
  600. ];
  601. $fallbackByChannel = [
  602. 'email' => 'bi-envelope',
  603. 'phone' => 'bi-telephone',
  604. 'meeting' => 'bi-people',
  605. 'other' => 'bi-chat-dots'
  606. ];
  607. $typeLabel = ['incoming'=>'Incoming','outgoing'=>'Outgoing','note'=>'Note'];
  608. $chLabel = ['email'=>'Email','phone'=>'Phone','meeting'=>'Meeting','other'=>'Other'];
  609. foreach ($correspondence as $row):
  610. $id = (int)$row['id'];
  611. $typeVal = strtolower(trim($row['type'] ?? 'note'));
  612. $channelVal = strtolower(trim($row['channel'] ?? 'other'));
  613. $key = ($typeVal === 'note') ? 'note' : "{$channelVal}_{$typeVal}";
  614. $icon = $badgeMap[$key] ?? ($fallbackByChannel[$channelVal] ?? 'bi-journal-text');
  615. $when = (new DateTime($row['event_at'], new DateTimeZone('Australia/Hobart')))->format('d M Y, h:ia');
  616. $visBadge = $row['visibility']==='internal' ? '
  617. <span class="badge rounded-pill text-bg-secondary ms-2">Internal</span>' : '';
  618. $typeClass = 'type-'.preg_replace('/[^a-z]/','', $typeVal);
  619. $numFiles = $fileCounts[$id] ?? 0; // <- NEW
  620. $hasFiles = $numFiles > 0; // <- NEW
  621. ?> <div class="timeline-item
  622. <?= $row['pin'] ? 'pinned' : '' ?>">
  623. <div class="timeline-badge">
  624. <i class="bi
  625. <?= $icon ?>">
  626. </i>
  627. </div>
  628. <div class="timeline-panel
  629. <?= $typeClass ?>">
  630. <div class="timeline-heading d-flex justify-content-between align-items-start">
  631. <div>
  632. <h6 class="mb-1"> <?= $when ?> • <?= $typeLabel[$typeVal] ?? ucfirst($typeVal) ?> via <?= $chLabel[$channelVal] ?? ucfirst($channelVal) ?> <?= $visBadge ?> <?php if ($row['pin']): ?> <i class="bi bi-pin-angle-fill text-warning ms-1" title="Pinned"></i> <?php endif; ?> <?php if (!empty($filesByCorr[$id])): ?> <span class="ms-2 att-pop" role="button" tabindex="0" data-bs-toggle="popover" data-bs-trigger="hover focus" data-bs-placement="top" data-bs-custom-class="popover-attachments" data-content-id="att-popover-
  633. <?= $id ?>" title="Attachments (
  634. <?= (int)$numFiles ?>)">
  635. <i class="bi bi-paperclip"></i>
  636. </span> <?php endif; ?> </h6>
  637. <small class="text-muted"> <?= htmlspecialchars($row['subject'] ?: ucfirst($typeVal)) ?> <?= $row['author'] ? ' • by: '.htmlspecialchars($row['author']) : '' ?> </small>
  638. </div>
  639. </div>
  640. <div class="timeline-body mt-2 small"> <?= render_body_html($row['body']) ?> </div>
  641. </div>
  642. </div> <?php endforeach; ?> <?php if (empty($correspondence)): ?> <div class="text-muted">No correspondence recorded yet.</div> <?php endif; ?> </div>
  643. </div>
  644. </div>
  645. </div> <?php foreach ($filesByCorr as $cid => $files): ?> <div id="att-popover-
  646. <?= (int)$cid ?>" class="d-none"> <?php foreach ($files as $f): ?> <div class="py-1">
  647. <a href="
  648. <?= htmlspecialchars($f['file_url'], ENT_QUOTES) ?>" target="_blank" rel="noopener">
  649. <i class="bi bi-file-earmark-pdf"></i> <?= htmlspecialchars($f['original_name'], ENT_QUOTES) ?> </a>
  650. </div> <?php endforeach; ?> </div> <?php endforeach; ?>
  651. </main>
  652. <script>
  653. const countdownEls = document.querySelectorAll(".countdown")
  654. countdownEls.forEach(countdownEl => createCountdown(countdownEl))
  655. function createCountdown(countdownEl) {
  656. const target = new Date(countdownEl.dataset.targetDate);
  657. const parts = {
  658. days: {
  659. text: ["days", "day"],
  660. dots: 30
  661. },
  662. hours: {
  663. text: ["hours", "hour"],
  664. dots: 24
  665. },
  666. minutes: {
  667. text: ["minutes", "minute"],
  668. dots: 60
  669. },
  670. seconds: {
  671. text: ["seconds", "second"],
  672. dots: 60
  673. },
  674. }
  675. Object.entries(parts).forEach(([key, value]) => {
  676. const partEl = document.createElement("div");
  677. partEl.classList.add("part", key);
  678. partEl.style.setProperty("--dots", value.dots);
  679. value.element = partEl;
  680. const remainingEl = document.createElement("div");
  681. remainingEl.classList.add("remaining");
  682. remainingEl.innerHTML = `
  683. <span class="number"></span>
  684. <span class="text"></span>`
  685. partEl.append(remainingEl);
  686. for (let i = 0; i < value.dots; i++) {
  687. const dotContainerEl = document.createElement("div");
  688. dotContainerEl.style.setProperty("--dot-idx", i);
  689. dotContainerEl.classList.add("dot-container")
  690. const dotEl = document.createElement("div");
  691. dotEl.classList.add("dot")
  692. dotContainerEl.append(dotEl);
  693. partEl.append(dotContainerEl);
  694. }
  695. countdownEl.append(partEl);
  696. })
  697. getRemainingTime(target, parts)
  698. }
  699. function getRemainingTime(target, parts, first = true) {
  700. const now = new Date()
  701. if (first) console.log({
  702. target,
  703. now
  704. })
  705. const remaining = {}
  706. let seconds = Math.floor((target - (now)) / 1000);
  707. let minutes = Math.floor(seconds / 60);
  708. let hours = Math.floor(minutes / 60);
  709. let days = Math.floor(hours / 24);
  710. hours = hours - (days * 24);
  711. minutes = minutes - (days * 24 * 60) - (hours * 60);
  712. seconds = seconds - (days * 24 * 60 * 60) - (hours * 60 * 60) - (minutes * 60);
  713. Object.entries({
  714. days,
  715. hours,
  716. minutes,
  717. seconds
  718. }).forEach(([key, value]) => {
  719. const remaining = parts[key].element.querySelector(".number");
  720. const text = parts[key].element.querySelector(".text");
  721. remaining.innerText = value;
  722. text.innerText = parts[key].text[Number(value == 1)]
  723. const dots = parts[key].element.querySelectorAll(".dot")
  724. dots.forEach((dot, idx) => {
  725. dot.dataset.active = idx <= value;
  726. dot.dataset.lastactive = idx == value;
  727. })
  728. })
  729. if (now <= target) {
  730. window.requestAnimationFrame(() => {
  731. getRemainingTime(target, parts, false)
  732. });
  733. }
  734. }
  735. document.getElementById('tryParse')?.addEventListener('click', function(e) {
  736. e.preventDefault();
  737. const body = document.getElementById('corrBody').value || '';
  738. const subj = /(?:^|\n)Subject:\s*(.+)/i.exec(body);
  739. const from = /(?:^|\n)From:\s*(.+)/i.exec(body);
  740. const date = /(?:^|\n)Date:\s*(.+)/i.exec(body);
  741. if (subj) document.getElementById('corrSubject').value = subj[1].trim();
  742. if (from) document.getElementById('corrAuthor').value = from[1].trim();
  743. if (date) {
  744. const guess = new Date(date[1]);
  745. if (!isNaN(guess.getTime())) {
  746. // to local datetime-local string
  747. const pad = n => String(n).padStart(2, '0');
  748. const v = guess.getFullYear() + '-' + pad(guess.getMonth() + 1) + '-' + pad(guess.getDate()) + 'T' + pad(guess.getHours()) + ':' + pad(guess.getMinutes());
  749. const el = document.querySelector('input[name="event_at"]');
  750. if (el) el.value = v;
  751. }
  752. }
  753. });
  754. document.addEventListener('DOMContentLoaded', () => {
  755. document.querySelectorAll('[data-bs-toggle="popover"][data-content-id]').forEach(el => {
  756. const id = el.getAttribute('data-content-id');
  757. const tpl = document.getElementById(id);
  758. const content = tpl ? tpl.innerHTML : '';
  759. new bootstrap.Popover(el, {
  760. html: true,
  761. content,
  762. container: 'body',
  763. sanitize: true, // keep Bootstrap’s sanitizer on
  764. trigger: 'hover focus' // hover on desktop, tap/focus on mobile
  765. });
  766. });
  767. });
  768. </script>
  769. </body>
  770. </html>