client-brief.php 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144
  1. <?php
  2. /* -------------------------------------------------------------------------- */
  3. /* CONFIGURATION */
  4. /* -------------------------------------------------------------------------- */
  5. date_default_timezone_set("Australia/Hobart");
  6. //error_reporting(E_ERROR | E_PARSE);
  7. error_reporting(E_ALL);
  8. ini_set('display_errors', 1);
  9. require_once 'connection.php';
  10. include_once "vendor/autoload.php";
  11. if (session_status() !== PHP_SESSION_ACTIVE) session_start();
  12. if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
  13. $csrf = $_SESSION['csrf'];
  14. $accessToken = 'pat-na1-64db9489-15fe-461d-b64c-941c4d80ba8a';
  15. #$enquiry_date = date("l dS M \'y");
  16. $drg = isset($_GET['drg']) ? $_GET['drg'] : '';
  17. if (!empty($_GET['drg'])) {
  18. include "table.php";
  19. }
  20. // CHECK NEXT AVAILABLE Drawing NUMBER
  21. $nextQ = mysqli_query($con, "SELECT MAX(drg) AS maxdrg FROM details");
  22. if (!$nextQ) { printf("Error: %s\n", mysqli_error($con)); exit; }
  23. $MQrow = mysqli_fetch_assoc($nextQ);
  24. $maxQ = isset($MQrow['maxdrg']) ? ((int)$MQrow['maxdrg'] + 1) : 1;
  25. /* -------------------------------------------------------------------------- */
  26. /* API MODE */
  27. /* -------------------------------------------------------------------------- */
  28. if (!defined('SITE_ROOT')) define('SITE_ROOT', dirname(__DIR__));
  29. // ===== LOA markdown creation helpers and API =====
  30. if (!defined('CONTRACTS_DIR')) define('CONTRACTS_DIR', SITE_ROOT . '/contracts/contracts');
  31. // ===== LOA config (must match contracts-admin/loa.php) =====
  32. if (!defined('LOA_DIR')) define('LOA_DIR', SITE_ROOT . '/contracts/loa');
  33. if (!defined('LOA_BASE_URL')) define('LOA_BASE_URL', 'https://modulosdesign.com.au/contracts'); // where loa.php lives
  34. if (!defined('LOA_TOKEN_SECRET')) define('LOA_TOKEN_SECRET', 'd1Epy6ryzgLYjLEBlpiHFrgST8JbAjgksjj3hIO5zCK5DChqYpWUdr8jeWR7xEgd'); // same as loa.php
  35. if (!function_exists('json_response')) {
  36. function json_response(array $data, int $code = 200) {
  37. header('Content-Type: application/json; charset=utf-8');
  38. http_response_code($code);
  39. echo json_encode($data);
  40. }
  41. }
  42. if (!function_exists('safe_clientid')) {
  43. function safe_clientid(string $s): string {
  44. // collapse whitespace to hyphen, strip invalid chars
  45. $s = preg_replace('/\s+/', '-', $s);
  46. $s = preg_replace('/[^A-Za-z0-9\-_]+/', '-', $s);
  47. $s = preg_replace('/-+/', '-', $s);
  48. return trim($s, '-_');
  49. }
  50. }
  51. if (!function_exists('contract_path')) {
  52. function contract_path(string $clientid): string {
  53. return rtrim(CONTRACTS_DIR, '/\\') . DIRECTORY_SEPARATOR . $clientid . '.md';
  54. }
  55. }
  56. function loa_path(string $job): string {
  57. $id = preg_replace('/\D+/', '', $job); // digits only to match loa.php
  58. return rtrim(LOA_DIR, '/\\') . DIRECTORY_SEPARATOR . $id . '.md';
  59. }
  60. function loa_public_url(string $job): string {
  61. $jobClean = preg_replace('/\D+/', '', $job); // digits only
  62. $token = hash_hmac('sha256', 'loa|' . $jobClean, LOA_TOKEN_SECRET);
  63. return rtrim(LOA_BASE_URL, '/') . '/loa.php?job=' . rawurlencode($jobClean) . '&token=' . rawurlencode($token);
  64. }
  65. /** Minimal front-matter pulls for LOA */
  66. function extract_loa_fields(string $file): array {
  67. $out = ['client_name'=>'','client_email'=>'','property_address'=>''];
  68. $txt = @file_get_contents($file);
  69. if (!$txt) return $out;
  70. if (!preg_match('/^---\s*\R(.*?)\R---/s', $txt, $m)) return $out;
  71. $fm = $m[1]; $ctx = null;
  72. foreach (preg_split('/\R/', $fm) as $line) {
  73. if (preg_match('/^\s*client\s*:\s*$/', $line)) { $ctx='client'; continue; }
  74. if (preg_match('/^\s*property\s*:\s*$/', $line)) { $ctx='property'; continue; }
  75. if ($ctx==='client') {
  76. if (preg_match('/^\s*name\s*:\s*(.+)$/', $line, $mm)) $out['client_name'] = trim($mm[1], " \t\"'");
  77. if (preg_match('/^\s*email\s*:\s*(.+)$/', $line, $mm)) $out['client_email']= trim($mm[1], " \t\"'");
  78. } elseif ($ctx==='property') {
  79. if (preg_match('/^\s*address\s*:\s*(.+)$/', $line, $mm)) $out['property_address']= trim($mm[1], " \t\"'");
  80. }
  81. }
  82. return $out;
  83. }
  84. /** Tiny contract front-matter extractor used by lookup */
  85. function extract_front_matter_fields(string $file): array {
  86. $out = [];
  87. $txt = @file_get_contents($file);
  88. if (!$txt) return $out;
  89. if (!preg_match('/^---\s*\R(.*?)\R---/s', $txt, $m)) return $out;
  90. $fm = $m[1];
  91. if (preg_match('/^\s*client\s*:\s*$(.*?)^(?=\S)/ms', $fm."\nX", $block)) {
  92. $clientBlock = $block[1];
  93. if (preg_match('/^\s*name\s*:\s*["\']?([^"\'\r\n]+)["\']?/mi', $clientBlock, $mm)) $out['client_name'] = trim($mm[1]);
  94. if (preg_match('/^\s*email\s*:\s*["\']?([^"\'\r\n]+)["\']?/mi', $clientBlock, $mm)) $out['client_email'] = trim($mm[1]);
  95. if (preg_match('/^\s*address\s*:\s*["\']?([^"\'\r\n]+)["\']?/mi',$clientBlock, $mm)) $out['client_address']= trim($mm[1]);
  96. }
  97. if (preg_match('/^\s*project\s*:\s*["\']?([^"\'\r\n]+)["\']?/mi', $fm, $mm)) $out['project'] = trim($mm[1]);
  98. if (preg_match('/^\s*job\s*:\s*["\']?([^"\'\r\n]+)["\']?/mi', $fm, $mm)) $out['job'] = trim($mm[1]);
  99. return $out;
  100. }
  101. /** Find best-known client + address for a job (checks existing LOA, then contracts) */
  102. function lookup_job_for_loa(string $job): array {
  103. $job = preg_replace('/\D+/', '', (string)($_POST['job'] ?? $drg ?? ''));
  104. $empty = ['client_name'=>'','client_email'=>'','property_address'=>'','source'=>null];
  105. // Prefer existing LOA
  106. $loaFile = loa_path($job);
  107. if (is_file($loaFile)) {
  108. return extract_loa_fields($loaFile) + ['source'=>'loa'];
  109. }
  110. // Scan contracts for a matching job or filename
  111. foreach (glob(rtrim(CONTRACTS_DIR,'/\\').'/*.md') as $file) {
  112. $fm = extract_front_matter_fields($file);
  113. $fname_id = preg_replace('/\.md$/i','',basename($file));
  114. if (($fm['job'] ?? '') === $job || $fname_id === $job) {
  115. $addr = $fm['client_address'] ?? '';
  116. return [
  117. 'client_name' => $fm['client_name'] ?? '',
  118. 'client_email' => $fm['client_email'] ?? '',
  119. 'property_address' => $addr,
  120. 'source' => 'contract',
  121. 'clientid' => $fname_id,
  122. ];
  123. }
  124. }
  125. return $empty;
  126. }
  127. /* ------------------------ FUNCTIONS ------------------------ */
  128. /** Build a starter Markdown file with YAML front matter. */
  129. if (!function_exists('build_markdown_template')) {
  130. function build_markdown_template(string $clientid, ?string $name, ?string $email, ?string $design_style, ?string $phone, ?string $site_address): string {
  131. $today = date('Y-m-d');
  132. $name = $name ?? '';
  133. $email = $email ?? '';
  134. $design_style = $design_style ?? '';
  135. $phone = $phone ?? '';
  136. $site_address = $site_address ?? '';
  137. // Generate secure random credentials
  138. $adminUser = bin2hex(random_bytes(4)); // 8 hex chars
  139. $adminPass = bin2hex(random_bytes(8)); // 16 hex chars
  140. $adminSecret = bin2hex(random_bytes(16)); // 32 hex chars
  141. $frontMatter = <<<YAML
  142. ---
  143. client:
  144. id: "{$clientid}"
  145. name: "{$name}"
  146. email: "{$email}"
  147. phone: "{$phone}"
  148. address: "{$site_address}"
  149. project: "{$design_style}"
  150. dates:
  151. prepared: "{$today}"
  152. dev:
  153. name: 'Modulos Design'
  154. email: 'ben@modulos.com.au'
  155. phone: '0402 984 082'
  156. address: '34 Coplestone Street, Scottsdale, Tas 7260'
  157. version: 1
  158. quote:
  159. number: "{$clientid}"
  160. admin:
  161. user: "{$adminUser}"
  162. pass: "{$adminPass}"
  163. secret: "{$adminSecret}"
  164. ---
  165. YAML;
  166. $body = <<<MD
  167. # Contract of work
  168. This Contract is made and entered into as of the date above by and between **[dev.name]** and **[client.name]** (hereinafter referred to as "Client").
  169. ##### 1. Scope of Services
  170. MD;
  171. return $frontMatter . $body;
  172. }
  173. }
  174. function yaml_q($v){ return '"'.str_replace(['\\','"'], ['\\\\','\\"'], (string)$v).'"'; }
  175. /** Upsert a top-level key like: job: "123" */
  176. function yaml_upsert_top(string $yaml, string $key, string $val): string {
  177. if ($val === '' || $val === null) return $yaml;
  178. $re = '/^\s*'.preg_quote($key,'/').'\s*:\s*.*/mi';
  179. if (preg_match($re, $yaml)) return preg_replace($re, $key.': '.yaml_q($val), $yaml, 1);
  180. return rtrim($yaml)."\n".$key.': '.yaml_q($val)."\n";
  181. }
  182. /** Upsert keys inside a block (client:, property:, dates:) with two-space indentation */
  183. function yaml_upsert_block(string $yaml, string $block, array $pairs): string {
  184. $blockRe = '/(^\s*'.preg_quote($block,'/').'\s*:\s*\R(?:[ \t].*\R)*)(?=^\S|\z)/m';
  185. if (preg_match($blockRe, $yaml, $m, PREG_OFFSET_CAPTURE)) {
  186. $start = $m[0][1]; $len = strlen($m[0][0]); $blk = $m[0][0];
  187. foreach ($pairs as $k=>$v) {
  188. if ($v === '' || $v === null) continue;
  189. $lineRe = '/^\s*'.preg_quote($k,'/').'\s*:\s*.*/mi';
  190. $rep = ' '.$k.': '.yaml_q($v);
  191. $blk = preg_replace($lineRe, $rep, $blk, 1, $count);
  192. if ($count === 0) $blk = rtrim($blk)."\n".$rep."\n";
  193. }
  194. return substr_replace($yaml, $blk, $start, $len);
  195. } else {
  196. $out = rtrim($yaml)."\n".$block.":\n";
  197. foreach ($pairs as $k=>$v) if ($v !== '' && $v !== null) $out .= ' '.$k.': '.yaml_q($v)."\n";
  198. return $out;
  199. }
  200. }
  201. /** Given a full .md file, update its front matter and return updated text */
  202. function update_front_matter_text(string $md, array $kv_top, array $kv_blocks): string {
  203. if (!preg_match('/^---\R(.*?)\R---(\R|$)/s', $md, $m, PREG_OFFSET_CAPTURE)) {
  204. // add a front matter header if missing
  205. $yaml = "";
  206. foreach ($kv_top as $k=>$v) $yaml = yaml_upsert_top($yaml, $k, $v);
  207. foreach ($kv_blocks as $b=>$p) $yaml = yaml_upsert_block($yaml, $b, $p);
  208. return "---\n".rtrim($yaml)."\n---\n".ltrim($md);
  209. }
  210. $yaml = $m[1][0];
  211. $start = $m[0][1];
  212. $len = strlen($m[0][0]);
  213. foreach ($kv_top as $k=>$v) $yaml = yaml_upsert_top($yaml, $k, $v);
  214. foreach ($kv_blocks as $b=>$p) $yaml = yaml_upsert_block($yaml, $b, $p);
  215. $newHeader = "---\n".rtrim($yaml)."\n---\n";
  216. return substr_replace($md, $newHeader, $start, $len);
  217. }
  218. /* -------------------------------------------------------------------------- */
  219. /* API MODE */
  220. /* -------------------------------------------------------------------------- */
  221. $__action = $_GET['action'] ?? $_POST['action'] ?? null;
  222. if ($__action === 'loa_create') {
  223. try {
  224. $job = safe_clientid($_POST['job'] ?? (string)($drg ?? ''));
  225. if (!$job) { json_response(['ok'=>false,'error'=>'Missing job #'], 400); exit; }
  226. // Form inputs (fall back to blanks)
  227. $name = trim($_POST['client_name'] ?? '');
  228. $email = trim($_POST['client_email'] ?? '');
  229. $clientPhone = trim($_POST['client_phone'] ?? ($_POST['client_mobile'] ?? ''));
  230. $clientAddress = trim($_POST['client_address'] ?? ($_POST['postal_address'] ?? ''));
  231. $addr = trim($_POST['property_address'] ?? ($_POST['site_address'] ?? ''));
  232. $propPid = trim($_POST['property_pid'] ?? ($_POST['property_id'] ?? ''));
  233. $propTitleRaw = trim($_POST['property_title'] ?? ($_POST['title_id'] ?? ''));
  234. // Split things like "140687/4", "140687 - 4", "140687 4"
  235. $propVol = ''; $propFolio = '';
  236. if ($propTitleRaw !== '') {
  237. if (preg_match('/^\s*([A-Za-z0-9]+)\s*[\/\-\s]\s*([A-Za-z0-9]+)\s*$/', $propTitleRaw, $mm)) {
  238. $propVol = $mm[1];
  239. $propFolio = $mm[2];
  240. } else {
  241. // If it doesn't split, keep the whole thing in vol so you don't lose info
  242. $propVol = $propTitleRaw;
  243. }
  244. }
  245. $dateStart = trim($_POST['start_date'] ?? '');
  246. $dateEnd = trim($_POST['end_date'] ?? '');
  247. $overwrite = (int)($_POST['overwrite'] ?? 0);
  248. $dst = loa_path($job);
  249. if (!is_dir(LOA_DIR)) @mkdir(LOA_DIR, 0775, true);
  250. // What we want in the YAML
  251. $top = ['job' => $job];
  252. $blocks = [
  253. 'client' => [
  254. 'name' => $name,
  255. 'email' => $email,
  256. 'phone' => $clientPhone,
  257. 'address' => $clientAddress,
  258. ],
  259. 'property' => [
  260. 'address' => $addr,
  261. 'pid' => $propPid,
  262. 'title' => $propTitleRaw,
  263. ],
  264. 'dates' => [
  265. 'start' => $dateStart,
  266. 'end' => $dateEnd,
  267. ],
  268. ];
  269. // Create new or update existing
  270. if (!file_exists($dst)) {
  271. // Load template, then inject values into its front matter
  272. $tplPath = rtrim(LOA_DIR,'/\\').'/default-authorisation.md';
  273. $tpl = @file_get_contents($tplPath);
  274. if ($tpl === false || $tpl === '') $tpl = "# Authorisation\n";
  275. $out = update_front_matter_text($tpl, $top, $blocks);
  276. if (@file_put_contents($dst, $out, LOCK_EX) === false) {
  277. json_response(['ok'=>false,'error'=>'Write failed'], 500); exit;
  278. }
  279. json_response(['ok'=>true,'job'=>$job,'path'=>$dst,'public_url'=>loa_public_url($job),'created'=>true]);
  280. } else {
  281. if ($overwrite) {
  282. // Overwrite from template
  283. $tplPath = rtrim(LOA_DIR,'/\\').'/default-authorisation.md';
  284. $tpl = @file_get_contents($tplPath);
  285. if ($tpl === false || $tpl === '') $tpl = "# Authorisation\n";
  286. $out = update_front_matter_text($tpl, $top, $blocks);
  287. } else {
  288. // Update front matter only in the existing file
  289. $existing = @file_get_contents($dst) ?: '';
  290. $out = update_front_matter_text($existing, $top, $blocks);
  291. }
  292. if (@file_put_contents($dst, $out, LOCK_EX) === false) {
  293. json_response(['ok'=>false,'error'=>'Write failed'], 500); exit;
  294. }
  295. json_response([
  296. 'ok'=>true,'job'=>$job,'path'=>$dst,'public_url'=>loa_public_url($job),
  297. 'created'=>false,'updated_frontmatter'=>!$overwrite
  298. ]);
  299. }
  300. } catch (Throwable $e) {
  301. json_response(['ok'=>false,'error'=>$e->getMessage()], 500);
  302. }
  303. exit;
  304. }
  305. // ===== end LOA helpers and API =====
  306. // Create the LOA markdown from default-authorisation.md
  307. if ($__action === 'loa_create') {
  308. try {
  309. $job = safe_clientid($_POST['job'] ?? (string)($drg ?? ''));
  310. if (!$job) { json_response(['ok'=>false,'error'=>'Missing job #'], 400); exit; }
  311. // Prefer explicit POST values; otherwise use current form values already on the page
  312. $name = trim($_POST['client_name'] ?? (trim(($firstname ?? '').' '.($lastname ?? '')) ?: ($joint_name ?? '')));
  313. $email = trim($_POST['client_email'] ?? ($client_email ?? ''));
  314. $addr = trim($_POST['property_address'] ?? ($site_address ?? ''));
  315. $overwrite = (int)($_POST['overwrite'] ?? 0);
  316. $dst = loa_path($job);
  317. if (!is_dir(LOA_DIR)) @mkdir(LOA_DIR, 0775, true);
  318. if (file_exists($dst) && !$overwrite) {
  319. json_response(['ok'=>false,'error'=>'File already exists','path'=>$dst], 409); exit;
  320. }
  321. // Load template (fallback to minimal front-matter if missing)
  322. $tplPath = rtrim(LOA_DIR,'/\\').'/default-authorisation.md';
  323. $tpl = @file_get_contents($tplPath);
  324. if ($tpl === false || $tpl === '') {
  325. $q = fn($v) => '"'.str_replace(['\\','"'], ['\\\\','\\"'], (string)$v).'"';
  326. $tpl = "---\njob: ".$q($job)."\nclient:\n name: ".$q($name)."\n email: ".$q($email)."\nproperty:\n address: ".$q($addr)."\n---\n# Authorisation\n";
  327. } else {
  328. // Light YAML substitutions
  329. $tpl = preg_replace_callback('/^---\R(.*?)\R---/s', function($m) use($job,$name,$email,$addr){
  330. $yaml = $m[1];
  331. $q = fn($v) => '"'.str_replace(['\\','"'], ['\\\\','\\"'], (string)$v).'"';
  332. // job
  333. $yaml = preg_replace('/^\s*job\s*:\s*.*/mi', 'job: '.$q($job), $yaml, 1, $jobCount);
  334. if ($jobCount === 0) $yaml = "job: ".$q($job)."\n".$yaml;
  335. // ensure blocks exist
  336. if (!preg_match('/^\s*client\s*:/mi', $yaml)) $yaml = "client:\n name:\n email:\n".$yaml;
  337. if (!preg_match('/^\s*property\s*:/mi', $yaml)) $yaml = "property:\n address:\n".$yaml;
  338. // client.name/email
  339. $yaml = preg_replace_callback('/(^\s*client\s*:\s*\R(?:.*\R)*?)(?=^\S|\z)/ms', function($b) use($q,$name,$email){
  340. $blk = $b[0];
  341. $blk = preg_replace('/^\s*name\s*:\s*.*/mi', ' name: '.$q($name), $blk, 1, $c1);
  342. if ($c1===0) $blk = rtrim($blk)."\n name: ".$q($name)."\n";
  343. $blk = preg_replace('/^\s*email\s*:\s*.*/mi', ' email: '.$q($email), $blk, 1, $c2);
  344. if ($c2===0) $blk = rtrim($blk)."\n email: ".$q($email)."\n";
  345. return $blk;
  346. }, $yaml, 1);
  347. // property.address
  348. $yaml = preg_replace_callback('/(^\s*property\s*:\s*\R(?:.*\R)*?)(?=^\S|\z)/ms', function($b) use($q,$addr){
  349. $blk = $b[0];
  350. $blk = preg_replace('/^\s*address\s*:\s*.*/mi', ' address: '.$q($addr), $blk, 1, $p1);
  351. if ($p1===0) $blk = rtrim($blk)."\n address: ".$q($addr)."\n";
  352. return $blk;
  353. }, $yaml, 1);
  354. return "---\n".$yaml."\n---";
  355. }, $tpl, 1) ?? $tpl;
  356. }
  357. if (@file_put_contents($dst, $tpl, LOCK_EX) === false) {
  358. json_response(['ok'=>false,'error'=>'Write failed'], 500); exit;
  359. }
  360. json_response(['ok'=>true,'job'=>$job,'path'=>$dst,'public_url'=>loa_public_url($job)]);
  361. } catch (Throwable $e) {
  362. json_response(['ok'=>false,'error'=>$e->getMessage()], 500);
  363. }
  364. exit;
  365. }
  366. // Optional: auto-fill data for a job (used by other screens / future)
  367. if ($__action === 'loa_lookup') {
  368. $job = safe_clientid($_GET['job'] ?? $_POST['job'] ?? '');
  369. $data = $job ? lookup_job_for_loa($job) : ['client_name'=>'','client_email'=>'','property_address'=>'','source'=>null];
  370. $found = (bool)($data['client_name'] || $data['client_email'] || $data['property_address']);
  371. json_response(['ok'=>true,'found'=>$found,'data'=>$data]);
  372. exit;
  373. }
  374. /* -------------------------------------------------------------------------- */
  375. /* HELPER FUNCTIONS */
  376. /* -------------------------------------------------------------------------- */
  377. use Google\Client;
  378. use Google\Service\Drive;
  379. function createFolder(string $access_token, string $folder_name, string $parent_folder_id = ''): ?string
  380. {
  381. try {
  382. $client = new Google\Client();
  383. $client->setAccessToken($access_token);
  384. $driveService = new Drive($client);
  385. $metadata = new Drive\DriveFile([
  386. 'name' => $folder_name,
  387. 'mimeType' => 'application/vnd.google-apps.folder',
  388. ]);
  389. if ($parent_folder_id) {
  390. $metadata->setParents([$parent_folder_id]);
  391. }
  392. $file = $driveService->files->create($metadata, ['fields' => 'id,name,webViewLink']);
  393. return $file->id;
  394. } catch (Exception $e) {
  395. error_log('createFolder error: ' . $e->getMessage());
  396. return null;
  397. }
  398. }
  399. function createDealHubSpot($newDealData)
  400. {
  401. global $accessToken;
  402. $endpoint = 'https://api.hubapi.com/crm/v3/objects/deals';
  403. $curl = curl_init();
  404. curl_setopt_array($curl, [
  405. CURLOPT_URL => $endpoint,
  406. CURLOPT_RETURNTRANSFER => true,
  407. CURLOPT_POST => true,
  408. CURLOPT_POSTFIELDS => json_encode($newDealData),
  409. CURLOPT_HTTPHEADER => [
  410. 'Authorization: Bearer ' . $accessToken, // Use OAuth 2.0 token OR 'Authorization: Bearer ' . $apiKey for API key
  411. 'Content-Type: application/json'
  412. ]
  413. ]);
  414. $response = curl_exec($curl);
  415. curl_close($curl);
  416. return $response;
  417. }
  418. function updateDealHubSpot($dealId, $data)
  419. {
  420. global $accessToken;
  421. $endpoint = 'https://api.hubapi.com/crm/v3/objects/deals/' . $dealId;
  422. $curl = curl_init();
  423. curl_setopt_array($curl, [
  424. CURLOPT_URL => $endpoint,
  425. CURLOPT_RETURNTRANSFER => true,
  426. CURLOPT_CUSTOMREQUEST => 'PATCH',
  427. CURLOPT_POSTFIELDS => json_encode($data),
  428. CURLOPT_HTTPHEADER => [
  429. 'Authorization: Bearer ' . $accessToken, // Use OAuth 2.0 token OR 'Authorization: Bearer ' . $apiKey for API key
  430. 'Content-Type: application/json'
  431. ]
  432. ]);
  433. $response = curl_exec($curl);
  434. curl_close($curl);
  435. return $response;
  436. }
  437. function addContactToHubSpot($newContactData) {
  438. global $accessToken;
  439. $endpoint = 'https://api.hubapi.com/crm/v3/objects/contacts';
  440. $curl = curl_init();
  441. curl_setopt_array($curl, [
  442. CURLOPT_URL => $endpoint,
  443. CURLOPT_RETURNTRANSFER => true,
  444. CURLOPT_POST => true,
  445. CURLOPT_POSTFIELDS => json_encode($newContactData),
  446. CURLOPT_HTTPHEADER => [
  447. 'Authorization: Bearer ' . $accessToken,
  448. 'Content-Type: application/json'
  449. ]
  450. ]);
  451. $response = curl_exec($curl);
  452. curl_close($curl);
  453. return $response;
  454. }
  455. function searchContact($query) {
  456. global $accessToken;
  457. $endpoint = 'https://api.hubapi.com/crm/v3/objects/contacts/search';
  458. $queryJson = json_encode($query);
  459. $ch = curl_init($endpoint);
  460. curl_setopt($ch, CURLOPT_POST, 1);
  461. curl_setopt($ch, CURLOPT_POSTFIELDS, $queryJson);
  462. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $accessToken, 'Content-Type: application/json'));
  463. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  464. $response = curl_exec($ch);
  465. if (curl_errno($ch)) {
  466. echo 'Error making cURL request: ' . curl_error($ch);
  467. }
  468. curl_close($ch);
  469. return $response;
  470. }
  471. function updateContact($contactId, $data) {
  472. global $accessToken;
  473. $endpoint = 'https://api.hubapi.com/crm/v3/objects/contacts/' . $contactId;
  474. $curl = curl_init();
  475. curl_setopt_array($curl, [
  476. CURLOPT_URL => $endpoint,
  477. CURLOPT_RETURNTRANSFER => true,
  478. CURLOPT_CUSTOMREQUEST => 'PUT',
  479. CURLOPT_POSTFIELDS => json_encode($data),
  480. CURLOPT_HTTPHEADER => [
  481. 'Authorization: Bearer ' . $accessToken,
  482. 'Content-Type: application/json'
  483. ]
  484. ]);
  485. $response = curl_exec($curl);
  486. curl_close($curl);
  487. return $response;
  488. }
  489. function format_E164($num)
  490. {
  491. $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
  492. try {
  493. $phoneProto = $phoneUtil->parse($num, "AU");
  494. return [
  495. "phone_number" => $phoneUtil->format($phoneProto, \libphonenumber\PhoneNumberFormat::INTERNATIONAL),
  496. "phone_type" => $phoneUtil->getNumberType($phoneProto)
  497. ];
  498. } catch (\libphonenumber\NumberParseException $e) {
  499. return null;
  500. }
  501. }
  502. if (!empty($drg) and !empty($_POST['add_client_to_crm']) and empty($contactId)) {
  503. try {
  504. $query = [
  505. "filterGroups" => [
  506. [
  507. "filters" => [
  508. [
  509. "value" => $_POST['firstname'] . "*",
  510. "propertyName" => 'firstname',
  511. "operator" => "EQ"
  512. ],
  513. [
  514. "value" => $_POST['lastname'] . "*",
  515. "propertyName" => "lastname",
  516. "operator" => "EQ"
  517. ],
  518. [
  519. "value" => $_POST['client_mobile'] . "*",
  520. "propertyName" => "phone",
  521. "operator" => "EQ"
  522. ]
  523. ]
  524. ]
  525. ],
  526. ];
  527. $response = json_decode(searchContact($query), true);
  528. if ($response['total'] > 0) {
  529. echo "<h4 style=\"text-align: center;color: red;padding: 10px;\">Customer: {$_POST['firstname']} {$_POST['lastname']} already exists in crm, with id: {$response['results'][0]['id']}</h4>";
  530. } else {
  531. $newContactData = [
  532. 'properties' => [
  533. 'firstname' => $_POST['firstname'],
  534. 'lastname' => $_POST['lastname'],
  535. 'description' => 'Added via Online Client Brief Form # ' . $drg,
  536. 'company' => $_POST['joint_name'],
  537. 'email' => $_POST['client_email'],
  538. 'address' => $_POST['postal_address'],
  539. 'city' => $_POST['postal_address_town'],
  540. 'zip' => $_POST['postal_address_postcode'],
  541. 'country' => 'AU',
  542. 'state' => $_POST['postal_address_state'],
  543. 'hubspot_owner_id' => '585959844',
  544. ]
  545. ];
  546. if($phone) {
  547. if($phone["phone_type"] == \libphonenumber\PhoneNumberType::MOBILE)
  548. $newContactData["properties"]["mobilephone"] = $phone["phone_number"];
  549. else
  550. $newContactData["properties"]["phone"] = $phone["phone_number"];
  551. }
  552. $response = addContactToHubSpot($newContactData);
  553. file_put_contents("crmadd.log", $response);
  554. $createdContact = json_decode($response, true);
  555. if ($createdContact['id'] > 0) {
  556. $crm_id = intval($createdContact['id']);
  557. $result = mysqli_query($con, "UPDATE details SET crm_id = '{$crm_id}' WHERE drg = '{$drg}'");
  558. if (!$result) {
  559. printf("Error: %s\n", mysqli_error($con));
  560. exit();
  561. } else {
  562. echo "<div class='container alert alert-success alert-dismissible d-print-none' role='alert'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><h4 style=\"text-align: center;\">Customer: {$_POST['firstname']} {$_POST['lastname']} added to crm, with id: {$crm_id}</h4></div>";
  563. $isHideDismissableAlert = 1;
  564. }
  565. }
  566. }
  567. } catch (\Exception $err) {
  568. echo '<pre>' . $err->getMessage() . '</pre>';
  569. die();
  570. }
  571. } elseif (!empty($drg) and !empty($_POST['edit_client_in_crm']) and !empty($contactId)) {
  572. try {
  573. $data = [
  574. 'properties' => [
  575. 'firstname' => $_POST['firstname'],
  576. 'lastname' => $_POST['lastname'],
  577. 'company' => $_POST['joint_name'],
  578. 'email' => $_POST['client_email'],
  579. 'address' => $_POST['postal_address'],
  580. 'city' => $_POST['postal_address_town'],
  581. 'zip' => $_POST['postal_address_postcode'],
  582. 'country' => 'AU',
  583. 'state' => $_POST['postal_address_state'],
  584. 'hubspot_owner_id' => '585959844',
  585. ]
  586. ];
  587. if($phone) {
  588. if($phone["phone_type"] == \libphonenumber\PhoneNumberType::MOBILE)
  589. $data["properties"]["mobilephone"] = $phone["phone_number"];
  590. else
  591. $data["properties"]["phone"] = $phone["phone_number"];
  592. }
  593. $query = [
  594. "filterGroups" => [
  595. [
  596. "filters" => [
  597. [
  598. "value" => $_POST['firstname'] . "*",
  599. "propertyName" => 'firstname',
  600. "operator" => "EQ"
  601. ],
  602. [
  603. "value" => $_POST['lastname'] . "*",
  604. "propertyName" => "lastname",
  605. "operator" => "EQ"
  606. ],
  607. [
  608. "value" => $_POST['client_mobile'] . "*",
  609. "propertyName" => "phone",
  610. "operator" => "EQ"
  611. ]
  612. ]
  613. ]
  614. ],
  615. ];
  616. $response = json_decode(searchContact($query), true);
  617. if ($response['total'] > 0) {
  618. $response = updateContact($contactId, $data);
  619. $result = mysqli_query($con, "UPDATE details SET crm_id = '{$response['id']}' WHERE drg = '{$drg}'");
  620. file_put_contents("crmupdate.log", $response);
  621. $response = json_decode($response, true);
  622. if ($response['id'] > 0) {
  623. echo "<div class='container alert alert-success alert-dismissible d-print-none' role='alert'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><h4 style=\"text-align: center;\">Customer: {$_POST['firstname']} {$_POST['lastname']} updated in crm</h4></div>";
  624. $isHideDismissableAlert = 1;
  625. }
  626. } else {
  627. $response = addContactToHubSpot($newContactData);
  628. file_put_contents("crmadd.log", $response);
  629. $createdContact = json_decode($response, true);
  630. if ($createdContact['id'] > 0) {
  631. $crm_id = intval($createdContact['id']);
  632. echo "<div class='container alert alert-success alert-dismissible d-print-none' role='alert'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><h4 style=\"text-align: center;\">Customer: {$_POST['firstname']} {$_POST['lastname']} added to crm, with id: {$crm_id}</h4></div>";
  633. $isHideDismissableAlert = 1;
  634. }
  635. }
  636. } catch (\Exception $err) {
  637. echo '<pre>Crm Id: ' . $contactId . ', response: ' . $err->getMessage() . '</pre>';
  638. die();
  639. }
  640. }
  641. // Create Deal from Enquiry Form
  642. if (!empty($quid) and !empty($_POST['add_deal_to_hubspot']) and empty($dealId)) {
  643. try {
  644. $newDealData = [
  645. 'associations' => [
  646. [
  647. 'types' => [
  648. [
  649. 'associationCategory' => 'HUBSPOT_DEFINED',
  650. 'associationTypeId' => 3,
  651. ]
  652. ],
  653. 'to' => [
  654. 'id' => $_POST['crm_id']
  655. ],
  656. ]
  657. ],
  658. 'properties' => [
  659. 'dealname' => $_POST['quid'] . ' - ' . $_POST['client'],
  660. 'dealtype' => 'newbusiness', // New or Existing Business - do we do a sql lookup and see if there is some won jobs for this customer ??
  661. 'hubspot_owner_id' => $_POST['hubspot_owner_id'],
  662. 'createdate' => $_POST['enquiry_date'],
  663. //assign deal to contact with hubspot contact id
  664. //'associatedCompanyIds' => $_POST['company_id'],
  665. 'pipeline' => '64401721',
  666. 'dealstage' => '126963334',
  667. 'width' => str_replace('m', '', $_POST['width']),
  668. 'length' => str_replace('m', '', $_POST['length']),
  669. 'height' => str_replace('m', '', $_POST['height']),
  670. 'quote_type' => $_POST['quote_type'],
  671. 'type' => $_POST['product'],
  672. 'roof_type' => $_POST['roof_style'],
  673. 'sides' => $_POST['side_walls'],
  674. 'ends' => $_POST['end_walls'],
  675. 'internal' => $_POST['internal_walls'],
  676. 'qty_bays' => $_POST['bay_qty'],
  677. //'bay_width' => $_POST['bay_width'],
  678. //'uneven_bays' => $_POST['bay_uneven'],
  679. 'quote' => $_POST['quid'],
  680. ]
  681. ];
  682. $response = createDealHubSpot($newDealData);
  683. file_put_contents("crmdeal.log", $response);
  684. $createdDeal = json_decode($response, true);
  685. if ($createdDeal['id'] > 0) {
  686. $dealId = intval($createdDeal['id']);
  687. $result = mysqli_query($con, "UPDATE details SET dealId = '{$dealId}' WHERE drg = '{$drg}'");
  688. echo "<div class='container alert alert-success alert-dismissible d-print-none' role='alert'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><h4 style=\"text-align: center;\">Deal: {$quid} - {$client} added to hubspot</h4></div>";
  689. $isHideDismissableAlert = 1;
  690. }
  691. } catch (\Exception $err) {
  692. echo '<pre>' . $err->getMessage() . '</pre>';
  693. die();
  694. }
  695. } elseif (!empty($drg) and !empty($_POST['update_deal_in_hubspot']) and !empty($dealId)) {
  696. try {
  697. $updateDealData = [
  698. 'properties' => [
  699. 'dealname' => $_POST['drg'] . ' - ' . $_POST['client'],
  700. 'hubspot_owner_id' => $_POST['hubspot_owner_id'],
  701. 'createdate' => $_POST['enquiry_date'],
  702. //assign deal to contact with hubspot contact id
  703. //'associatedCompanyIds' => $_POST['company_id'],
  704. 'quote_type' => $_POST['quote_type'],
  705. 'type' => $_POST['product'],
  706. ],
  707. 'associations' => [
  708. 'types' => [
  709. 'association_category' => 'HUBSPOT_DEFINED',
  710. 'association_type_id' => 3
  711. ],
  712. 'to' => [
  713. 'id' => $_POST['crm_id']
  714. ]
  715. ]
  716. ];
  717. $response = updateDealHubSpot($dealId, $updateDealData);
  718. file_put_contents("crmdeal.log", $response);
  719. $updatedDeal = json_decode($response, true);
  720. if ($updatedDeal['id'] > 0) {
  721. $dealId = intval($updatedDeal['id']);
  722. echo "<div class='container alert alert-success alert-dismissible d-print-none' role='alert'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><h4 style=\"text-align: center;\">Deal: {$quid} - {$client} added to hubspot</h4></div>";
  723. $isHideDismissableAlert = 1;
  724. }
  725. } catch (\Exception $err) {
  726. echo '<pre>' . $err->getMessage() . '</pre>';
  727. die();
  728. }
  729. }
  730. if (!empty($_GET['drg'])) {
  731. $contact_button = '';
  732. if ($crm_id > 5) {
  733. $contact_button = '<button type="button" class="btn btn-sm bg-brown-five brown-three" data-bs-toggle="modal" data-bs-target="#crmUpdateModal"><i class="fab fa-hubspot"></i> Update Hubspot</button>';
  734. } else {
  735. $contact_button = '<button type="submit" class="btn btn-sm bg-brown-five brown-three" name="add_client_to_crm" value="1" form="client-brief" ><i class="bi bi-briefcase-fill"></i> Save Customer</button>';
  736. }
  737. }
  738. ?>
  739. <!doctype html>
  740. <html lang="en">
  741. <head>
  742. <meta charset="utf-8">
  743. <meta name="viewport" content="width=device-width, initial-scale=1">
  744. <title><?php echo $drg; ?> - Client Brief</title>
  745. <link rel="shortcut icon" href="images/blueprint.ico" type="image/x-icon">
  746. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
  747. <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  748. <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  749. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
  750. <link href="css/blueprint.css" rel="stylesheet">
  751. <link href="css/print.css" rel="stylesheet" media="print">
  752. <script type="text/javascript" src="https://use.fontawesome.com/1e2844bb90.js"></script>
  753. <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
  754. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-throttle-debounce/1.1/jquery.ba-throttle-debounce.min.js" integrity="sha512-JZSo0h5TONFYmyLMqp8k4oPhuo6yNk9mHM+FY50aBjpypfofqtEWsAgRDQm94ImLCzSaHeqNvYuD9382CEn2zw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  755. </head>
  756. <body>
  757. <nav class="navbar bg-brown-dark brown-light border-bottom border-body d-print-none" data-bs-theme="dark">
  758. <div class="container-fluid">
  759. <a class="navbar-brand brown-light" href="#">
  760. <img src="images/blueprint-logo-light.png" alt="Logo" width="30" height="24" class="d-inline-block align-text-top">
  761. Modulos Design
  762. </a>
  763. </div>
  764. </nav>
  765. <div class="container">
  766. <div class="row pt-2">
  767. <div class="col-sm-4 col-md-4 pt-3">
  768. <img class="img-fluid logo pt-2" src="images/blueprint-full-logo-medium.png" alt="Modulos Design">
  769. </div>
  770. <div class="col-sm-4 col-md-4 m-auto text-center">
  771. <h3 class="architect text-center">Job: <?php echo $drg; ?></h3>
  772. </div>
  773. <div class="col-sm-4 col-md-4 text-end pt-3">
  774. <h2 class="fw-bold text-end mb-1">Client Brief Form</h2>
  775. <h4 class="text-end mb-1">
  776. <span class="fw-bold brown-two"><?php echo $enquiry_date; ?></span>
  777. </h4>
  778. </div>
  779. </div>
  780. <hr>
  781. <form id="client-brief" data-remote="true" method="post" accept-charset="UTF-8">
  782. <input type="hidden" name="csrf" id="csrf" value="<?php echo $csrf; ?>">
  783. <div class="row">
  784. <div class="col-12 col-md-6">
  785. <div class="row ">
  786. <div class="col ">
  787. <h4 class="fw-bold">Client Details</h4>
  788. </div>
  789. </div>
  790. <div class="mb-1">
  791. <div class="row ">
  792. <div class="col-12 col-md-6">
  793. <label for="firstname" class="form-label form-label-sm p-0 m-0">Clients Name</label>
  794. <input type="text" class="form-control form-control-sm savable-text-field architect brown-four" name="firstname" id="firstname" tabindex="1" value="<?php echo htmlspecialchars($firstname ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="First Name" autocomplete="given-name">
  795. </div>
  796. <div class="col-12 col-md-6">
  797. <label for="lastname" class="form-label form-label-sm p-0 m-0"></label>
  798. <input type="text" class="form-control form-control-sm savable-text-field architect brown-four" name="lastname" id="lastname" tabindex="2" value="<?php echo htmlspecialchars($lastname ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Last Name" autocomplete="family-name">
  799. </div>
  800. </div>
  801. </div>
  802. <div class="mb-1">
  803. <label for="joint_name" class="form-label form-label-sm p-0 m-0">T/As - Joint Names</label>
  804. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="joint_name" id="joint_name" value="<?php echo htmlspecialchars($joint_name ?? '', ENT_QUOTES, 'UTF-8'); ?>" tabindex="3">
  805. </div>
  806. <div class="mb-1">
  807. <label for="postal_address" class="form-label form-label-sm p-0 m-0">Clients Postal Address</label>
  808. <input type="text" class="form-control form-control-sm fw-bold savable-text-field architect brown-three map-autocomplete" id="postal_address" name="postal_address" value="<?php echo htmlspecialchars($postal_address ?? '', ENT_QUOTES, 'UTF-8'); ?>" onFocus="geolocate(this)" tabindex="4" autocomplete="on">
  809. </div>
  810. <div class="mb-1">
  811. <div class="row ">
  812. <div class="col-md-6">
  813. <label for="phoneNumber" class="form-label form-label-sm p-0 m-0">Clients Mobile</label>
  814. <input type="phone" class="form-control form-control-sm savable-text-field architect brown-three" minlength="12" id="phoneNumber" name="client_mobile" value="<?php echo htmlspecialchars($client_mobile ?? '', ENT_QUOTES, 'UTF-8'); ?>" required onkeyup="check(); return false;" tabindex="5" autocomplete="tel">
  815. </div>
  816. <div class="col-12 col-md-3 d-print-none">
  817. <label for="crm_id" class="form-label form-label-sm p-0 m-0">CID</label>
  818. <input type="text" class="form-control form-control-sm savable-text-field brown-three" id="crm_id" name="crm_id" value="<?php echo $crm_id; ?>" >
  819. </div>
  820. <div class="col-12 col-md-3 d-print-none">
  821. <label for="dealId" class="form-label form-label-sm p-0 m-0">DID</label>
  822. <input type="text" class="form-control form-control-sm savable-text-field brown-three" id="dealId" name="dealId" value="<?php echo $dealId; ?>" >
  823. </div>
  824. </div>
  825. </div>
  826. <div class="mb-1">
  827. <label for="client_email" class="form-label form-label-sm p-0 m-0">Email address</label>
  828. <input type="email" class="form-control form-control-sm savable-text-field architect brown-three" name="client_email" id="client_email" value="<?php echo htmlspecialchars($client_email ?? '', ENT_QUOTES, 'UTF-8'); ?>" tabindex="6" autocomplete="email">
  829. </div>
  830. <hr>
  831. <div class="row ">
  832. <div class="col ">
  833. <h4 class="fw-bold">Proposed Site Details</h4>
  834. </div>
  835. </div>
  836. <div class="mb-1">
  837. <label for="site_address" class="form-label form-label-sm p-0 m-0">Site Address</label>
  838. <input type="text" class="form-control form-control-sm fw-bold savable-text-field architect brown-four map-autocomplete" id="site_address" name="site_address" value="<?php echo htmlspecialchars($site_address ?? '', ENT_QUOTES, 'UTF-8'); ?>" onFocus="geolocate(this)" tabindex="7">
  839. <input type="hidden" class="savable-text-field" id="site_lat" name="site_lat" value="<?php echo htmlspecialchars($site_lat ?? '', ENT_QUOTES, 'UTF-8'); ?>">
  840. <input type="hidden" class="savable-text-field" id="site_lng" name="site_lng" value="<?php echo htmlspecialchars($site_lng ?? '', ENT_QUOTES, 'UTF-8'); ?>">
  841. </div>
  842. <div class="row g-3">
  843. <div class="col-12 col-md-6">
  844. <label for="property_id" class="form-label form-label-sm p-0 m-0">Property ID:</label>
  845. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="property_id" id="property_id" value="<?php echo htmlspecialchars($property_id ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Pid">
  846. </div>
  847. <div class="col-12 col-md-6">
  848. <label for="title_id" class="form-label form-label-sm p-0 m-0">Title Reference:</label>
  849. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="title_id" id="title_id" value="<?php echo htmlspecialchars($title_id ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Title/Vol">
  850. </div>
  851. </div>
  852. <div class="mb-1">
  853. <label for="registered_owner" class="form-label form-label-sm p-0 m-0">Registered Title Owners:</label>
  854. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="registered_owner" id="registered_owner" value="<?php echo htmlspecialchars($registered_owner ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="">
  855. </div>
  856. <div class="row g-3">
  857. <div class="col-12 col-md-5">
  858. <label for="council" class="form-label form-label-sm p-0 m-0">Council:</label>
  859. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="council" id="council" value="<?php echo htmlspecialchars($council ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Local Council">
  860. </div>
  861. <div class="col-12 col-md-3">
  862. <label for="elevation" class="form-label form-label-sm p-0 m-0">Elev (AHD):</label>
  863. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="elevation" id="elevation" value="<?php echo htmlspecialchars($elevation ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Elevation (m)">
  864. </div>
  865. <div class="col-12 col-md-4">
  866. <label for="elevation" class="form-label form-label-sm p-0 m-0">Land Area (m2):</label>
  867. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="total_area" id="total_area" value="<?php echo htmlspecialchars($total_area ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="">
  868. </div>
  869. </div>
  870. <div class="row g-3">
  871. <div class="col-12 col-md-4">
  872. <label for="planning_zones" class="form-label form-label-sm p-0 m-0">Planning Zones:</label>
  873. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="planning_zones" id="planning_zones" value="<?php echo htmlspecialchars($planning_zones ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Planning Zones">
  874. </div>
  875. <div class="col-12 col-md-8">
  876. <label for="planning_scheme" class="form-label form-label-sm p-0 m-0">Planning Scheme:</label>
  877. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="planning_scheme" id="planning_scheme" value="<?php echo htmlspecialchars($planning_scheme ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Planning Scheme">
  878. </div>
  879. </div>
  880. <div class="row g-3">
  881. <div class="col-12">
  882. <label for="planning_codes" class="form-label form-label-sm p-0 m-0">Planning Codes:</label>
  883. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="planning_codes" id="planning_codes" value="<?php echo htmlspecialchars($planning_codes ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Planning Codes">
  884. </div>
  885. </div>
  886. <hr>
  887. <div class="row ">
  888. <div class="col ">
  889. <h4 class="fw-bold">Design Brief</h4>
  890. </div>
  891. </div>
  892. <div class="mb-1">
  893. <label for="design_style" class="form-label form-label-sm p-0 m-0">Type of Design</label>
  894. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="design_style" id="design_style" value="<?php echo htmlspecialchars($design_style ?? '', ENT_QUOTES, 'UTF-8'); ?>" >
  895. </div>
  896. <div class="row g-3">
  897. <div class="col-12 col-md-6">
  898. <label for="build_type" class="form-label form-label-sm p-0 m-0">Build Type:</label>
  899. <select type="text" name="build_type" id="build_type" class="form-select form-select-sm savable-dropdown-field architect brown-three" aria-required="true" aria-invalid="false">
  900. <option><?php echo $build_type; ?></option>
  901. <option >New Residential</option>
  902. <option >Residential Extension</option>
  903. <option >New Commercial</option>
  904. <option >Commercial Extension</option>
  905. <option >Shed or Ancillary Dwelling</option>
  906. <option >Pool</option>
  907. <option >Interior Design</option>
  908. <option >Other</option>
  909. </select>
  910. </div>
  911. <div class="col-12 col-md-6">
  912. <label for="scope" class="form-label form-label-sm p-0 m-0">Our Scope</label>
  913. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" id="scope" name="scope" value="<?php echo htmlspecialchars($scope ?? '', ENT_QUOTES, 'UTF-8'); ?>" >
  914. </div>
  915. </div>
  916. </div>
  917. <div class="col-12 col-md-6">
  918. <div class="row d-print-none">
  919. <div class="col-12 col-md my-1 d-grid">
  920. <?php echo $contact_button; ?>
  921. </div>
  922. <div class="col-12 col-md my-1 d-grid">
  923. <button type="button" class="btn btn-sm bg-brown-dark brown-three" data-bs-toggle="modal" data-bs-target="#emailTemplateModal"><i class="bi bi-clipboard"></i> Planning request text</button>
  924. </div>
  925. <div class="col-12 col-md my-1 d-grid">
  926. <button type="button" class="btn btn-sm bg-brown-three brown-five" id="createFolder"><i class="bi bi-folder-fill"></i> Create Job</button>
  927. </div>
  928. <div class="col-12 col-md my-1 d-grid">
  929. <button type="button" class="btn btn-sm bg-brown-three brown-five" onclick="fetchAndExtractData()"><i class="bi bi-folder-fill"></i> Planbuild</button>
  930. <!-- <button type="button" class="btn btn-sm bg-brown-light brown-five bd-brown-five"><i class="bi bi-award-fill"></i> Request Title</button> -->
  931. </div>
  932. </div>
  933. <div class="row d-print-none">
  934. <div class="col">
  935. <hr class="mvt-3">
  936. </div>
  937. </div>
  938. <div class="row ">
  939. <div class="col-12">
  940. <h5 class="fw-bold">Brief Checklist</h5>
  941. <p class="extra-light small">Have the following documents being provided?</p>
  942. </div>
  943. </div>
  944. <div class="row ">
  945. <div class="col-6 col-md-4">
  946. <div class="form-check form-check-inline savable-checkbox">
  947. <input class="form-check-input savable-checkbox-field"
  948. type="checkbox"
  949. name="copy_title" id="copy_title"
  950. value="1"
  951. <?php if ('1' == $copy_title) { echo 'checked'; } ?>
  952. >
  953. <label class="form-check-label" for="copy_title">Copy of Title</label>
  954. </div>
  955. </div>
  956. <div class="col-6 col-md-4">
  957. <div class="form-check form-check-inline savable-checkbox">
  958. <input class="form-check-input savable-checkbox-field"
  959. type="checkbox"
  960. name="original_plans" id="original_plans"
  961. value="1"
  962. <?php if ('1' == $original_plans) { echo 'checked'; } ?>
  963. >
  964. <label class="form-check-label" for="original_plans">Original Plans</label>
  965. </div>
  966. </div>
  967. <div class="col-6 col-md-4">
  968. <div class="form-check form-check-inline savable-checkbox">
  969. <input class="form-check-input savable-checkbox-field"
  970. type="checkbox"
  971. name="concepts_styles" id="concepts_styles"
  972. value="1"
  973. <?php if ('1' == $concepts_styles) { echo 'checked'; } ?>
  974. >
  975. <label class="form-check-label" for="concepts_styles">Concepts & Styles</label>
  976. </div>
  977. </div>
  978. </div>
  979. <div class="row ">
  980. <div class="col-6 col-md-4">
  981. <div class="form-check form-check-inline savable-checkbox">
  982. <input class="form-check-input savable-checkbox-field"
  983. type="checkbox"
  984. name="loa_signed" id="loa_signed"
  985. value="1"
  986. <?php if ('1' == $loa_signed) { echo 'checked'; } ?>
  987. >
  988. <label class="form-check-label" for="loa_signed">LOA signed</label>
  989. </div>
  990. </div>
  991. <div class="col-6 col-md-4">
  992. <div class="form-check form-check-inline savable-checkbox">
  993. <input class="form-check-input savable-checkbox-field"
  994. type="checkbox"
  995. name="da_application" id="da_application"
  996. value="1"
  997. <?php if ('1' == $da_application) { echo 'checked'; } ?>
  998. >
  999. <label class="form-check-label" for="da_application">DA Application</label>
  1000. </div>
  1001. </div>
  1002. <div class="col-6 col-md-4">
  1003. <div class="form-check form-check-inline savable-checkbox">
  1004. <input class="form-check-input savable-checkbox-field"
  1005. type="checkbox"
  1006. name="ba_application" id="ba_application"
  1007. value="1"
  1008. <?php if ('1' == $ba_application) { echo 'checked'; } ?>
  1009. >
  1010. <label class="form-check-label" for="ba_application">BA Application</label>
  1011. </div>
  1012. </div>
  1013. </div>
  1014. <hr>
  1015. <div class="row ">
  1016. <div class="col ">
  1017. <h5 class="fw-bold">Design Outputs</h5>
  1018. <p class="extra-light small"></p>
  1019. </div>
  1020. </div>
  1021. <div class="row ">
  1022. <div class="col-6 col-md-4">
  1023. <div class="form-check form-check-inline savable-checkbox">
  1024. <input class="form-check-input savable-checkbox-field"
  1025. type="checkbox"
  1026. name="concepts_3d" id="concepts_3d"
  1027. value="1"
  1028. <?php if ('1' == $concepts_3d) { echo 'checked'; } ?>
  1029. >
  1030. <label class="form-check-label" for="concepts_3d">3D Concepts</label>
  1031. </div>
  1032. </div>
  1033. <div class="col-6 col-md-4">
  1034. <div class="form-check form-check-inline savable-checkbox">
  1035. <input class="form-check-input savable-checkbox-field"
  1036. type="checkbox"
  1037. name="draft_floorPlan" id="draft_floorPlan"
  1038. value="1"
  1039. <?php if ('1' == $draft_floorPlan) { echo 'checked'; } ?>
  1040. >
  1041. <label class="form-check-label" for="draft_floorPlan">Draft Floor Plan</label>
  1042. </div>
  1043. </div>
  1044. <div class="col-6 col-md-4">
  1045. <div class="form-check form-check-inline savable-checkbox">
  1046. <input class="form-check-input savable-checkbox-field"
  1047. type="checkbox"
  1048. name="fire_report" id="fire_report"
  1049. value="1"
  1050. <?php if ('1' == $fire_report) { echo 'checked'; } ?>
  1051. >
  1052. <label class="form-check-label" for="fire_report">Fire Report</label>
  1053. </div>
  1054. </div>
  1055. </div>
  1056. <div class="row ">
  1057. <div class="col-6 col-md-4">
  1058. <div class="form-check form-check-inline savable-checkbox">
  1059. <input class="form-check-input savable-checkbox-field"
  1060. type="checkbox"
  1061. name="energy_report" id="energy_report"
  1062. value="1"
  1063. <?php if ('1' == $energy_report) { echo 'checked'; } ?>
  1064. >
  1065. <label class="form-check-label" for="energy_report">Energy Report</label>
  1066. </div>
  1067. </div>
  1068. <div class="col-6 col-md-4">
  1069. <div class="form-check form-check-inline savable-checkbox">
  1070. <input class="form-check-input savable-checkbox-field"
  1071. type="checkbox"
  1072. name="tender_set" id="tender_set"
  1073. value="1"
  1074. <?php if ('1' == $tender_set) { echo 'checked'; } ?>
  1075. >
  1076. <label class="form-check-label" for="tender_set">Tender Doc Set</label>
  1077. </div>
  1078. </div>
  1079. <div class="col-6 col-md-4">
  1080. <div class="form-check form-check-inline savable-checkbox">
  1081. <input class="form-check-input savable-checkbox-field"
  1082. type="checkbox"
  1083. name="quantity_survey" id="quantity_survey"
  1084. value="1"
  1085. <?php if ('1' == $quantity_survey) { echo 'checked'; } ?>
  1086. >
  1087. <label class="form-check-label" for="quantity_survey">Quantity Survey</label>
  1088. </div>
  1089. </div>
  1090. </div>
  1091. <hr>
  1092. <div class="row ">
  1093. <div class="col ">
  1094. <h5 class="fw-bold">Presentations</h5>
  1095. <p class="extra-light small"></p>
  1096. </div>
  1097. </div>
  1098. <div class="row ">
  1099. <div class="col-6 col-md-4">
  1100. <div class="form-check form-check-inline savable-checkbox">
  1101. <input class="form-check-input savable-checkbox-field"
  1102. type="checkbox"
  1103. name="vr_concepts" id="vr_concepts"
  1104. value="1"
  1105. <?php if ('1' == $vr_concepts) { echo 'checked'; } ?>
  1106. >
  1107. <label class="form-check-label" for="vr_concepts">VR Concepts</label>
  1108. </div>
  1109. </div>
  1110. <div class="col-6 col-md-4">
  1111. <div class="form-check form-check-inline savable-checkbox">
  1112. <input class="form-check-input savable-checkbox-field"
  1113. type="checkbox"
  1114. name="render_set" id="render_set"
  1115. value="1"
  1116. <?php if ('1' == $render_set) { echo 'checked'; } ?>
  1117. >
  1118. <label class="form-check-label" for="render_set">Full Rended Set</label>
  1119. </div>
  1120. </div>
  1121. <div class="col-6 col-md-4">
  1122. <div class="form-check form-check-inline savable-checkbox">
  1123. <input class="form-check-input savable-checkbox-field"
  1124. type="checkbox"
  1125. name="model_3d" id="model_3d"
  1126. value="1"
  1127. <?php if ('1' == $model_3d) { echo 'checked'; } ?>
  1128. >
  1129. <label class="form-check-label" for="model_3d">3D Model</label>
  1130. </div>
  1131. </div>
  1132. </div>
  1133. <hr>
  1134. <div class="row ">
  1135. <div class="col ">
  1136. <h5 class="fw-bold">Create Documents</h5>
  1137. <p class="extra-light small"></p>
  1138. </div>
  1139. </div>
  1140. <div class="row d-print-none mb-2">
  1141. <div class="col d-inline-flex gap-1">
  1142. <button type="button" class="btn btn-sm bg-brown-three brown-five" id="createLOA"><i class="bi bi-file-earmark-text-fill"></i> Create LOA</button>
  1143. </div>
  1144. </div>
  1145. <div class="row d-print-none">
  1146. <div class="col d-inline-flex gap-1">
  1147. <button type="button" class="btn btn-sm bg-brown-five brown-three" id="createContract"><i class="bi bi-file-earmark-text-fill"></i> Create Contract</button>
  1148. <div class="form-check d-inline-flex align-items-center ms-2">
  1149. <input class="form-check-input" type="checkbox" id="updateFrontMatter">
  1150. <label class="form-check-label ms-1" for="updateFrontMatter">
  1151. Update contact details if file exists
  1152. </label>
  1153. </div>
  1154. </div>
  1155. </div>
  1156. <hr>
  1157. <div class="row ">
  1158. <div class="col ">
  1159. <h4 class="fw-bold">Investment Details</h4>
  1160. </div>
  1161. </div>
  1162. <div class="row g-3">
  1163. <div class="col-12 col-md-6">
  1164. <label for="budget_low" class="form-label form-label-sm p-0 m-0">Budget Range (Lower)</label>
  1165. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="budget_low" id="budget_low" value="<?php echo htmlspecialchars($budget_low ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="$300,000">
  1166. </div>
  1167. <div class="col-12 col-md-6">
  1168. <label for="budget_high" class="form-label form-label-sm p-0 m-0">Budget Range (Upper)</label>
  1169. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="budget_high" id="budget_high" value="<?php echo htmlspecialchars($budget_high ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="$2,000,000">
  1170. </div>
  1171. </div>
  1172. <div class="mb-1">
  1173. <label for="finance_status" class="form-label form-label-sm p-0 m-0">Finance</label>
  1174. <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="finance_status" id="finance_status" value="<?php echo htmlspecialchars($finance_status ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Have you had a loan (pre)approved ?">
  1175. </div>
  1176. <hr>
  1177. <div class="row ">
  1178. <div class="col ">
  1179. <h4 class="fw-bold">Services Used</h4>
  1180. </div>
  1181. </div>
  1182. <div class="row g-3">
  1183. <div class="col-12">
  1184. <select class="form-control form-control-sm" id="building_surveyors_select" name="building_surveyors">
  1185. <label for="building_surveyors">Building Surveyor:</label>
  1186. <option selected="" disabled="">Select Building Surveyor</option>
  1187. <option class='' data-id='Building Surveying Services Pty Ltd|Wayne Wilson|0487 911 123|building@buildingsurveyingservices.com.au|7 Marlborough Street, Longford, Tas, 7301' id='' value='building@buildingsurveyingservices.com.au' >Building Surveying Services - Wayne Wilson</option>
  1188. <option class='' data-id='Plumb Building Surveying|Matthew Dewse|0476 830 336|hello@plumbbuildingsurveying.au|PO Box 120, Kings Meadows, Tas, 7249' id='' value='hello@plumbbuildingsurveying.au' >Plumb Building Surveying - Matthew Dewse</option>
  1189. <option class='' data-id='Local Group|Barry Magnus|0455 681 912|bmagnus@localgroup.com.au|81 Elizabeth Street, Launceston , Tas, 7250' id='' value='bmagnus@localgroup.com.au' >Local Group - Barry Magnus</option>
  1190. <option class='' data-id='Worthington Building Surveying|Peter Worthington|0475 854 904|peter@worthbuilding.com.au|, Frankford, Tas, 7275' id='' value='peter@worthbuilding.com.au' >Worthington Building Surveying - Peter Worthington</option>
  1191. </select>
  1192. <input type="hidden" id="building_surveyors_meta" name="building_surveyors_meta" value="<?php echo $building_surveyors_meta ?? ''; ?>">
  1193. </div>
  1194. <div class="col-12 col-md-6">
  1195. </div>
  1196. </div>
  1197. <div class="row mb-1">
  1198. <div class="col-12 col-md-6">
  1199. <div class="row mb-1">
  1200. <div class="col-12 col-md-6">
  1201. </div>
  1202. </div>
  1203. </div>
  1204. </div>
  1205. </div>
  1206. </div>
  1207. <hr>
  1208. <div class="row">
  1209. <div class="col">
  1210. <div class="mb-1">
  1211. <label for="details" class="form-label form-label-sm p-0 m-0">Details</label>
  1212. <textarea class="form-control form-control-sm savable-text-field small architect" name="details" id="details" rows="6"><?php echo htmlspecialchars($details ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
  1213. </div>
  1214. </div>
  1215. </div>
  1216. <hr>
  1217. <div class="row d-print-none">
  1218. <div class="col-6">
  1219. <!--Add buttons to initiate auth sequence and sign out-->
  1220. <button id="authorize_button" type="button" class="btn btn-sm bg-brown-three brown-five">Authorize</button>
  1221. <button id="signout_button" type="button" class="btn btn-sm bg-brown-three brown-five">Sign Out</button>
  1222. </div>
  1223. </div>
  1224. <hr>
  1225. <footer class="footer">
  1226. <p class="text-center">&copy; 2023 - Modulos Design</p>
  1227. </footer>
  1228. </form>
  1229. </div>
  1230. <!-- Planbuild/LIST preview modal -->
  1231. <div class="modal fade" id="planbuildPreview" tabindex="-1" role="dialog" aria-labelledby="planbuildPreviewLabel" aria-hidden="true">
  1232. <div class="modal-dialog modal-lg" role="document">
  1233. <div class="modal-content">
  1234. <div class="modal-header">
  1235. <h5 class="modal-title" id="planbuildPreviewLabel">Property info from LIST</h5>
  1236. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  1237. </div>
  1238. <div class="modal-body">
  1239. <div id="pb-errors" class="alert alert-danger d-none"></div>
  1240. <div class="row">
  1241. <div class="col-md-6">
  1242. <dl class="row small mb-0">
  1243. <dt class="col-5">PID</dt><dd class="col-7" id="pb_pid">–</dd>
  1244. <dt class="col-5">Title</dt><dd class="col-7" id="pb_title">–</dd>
  1245. <dt class="col-5">Total Area</dt><dd class="col-7" id="pb_area">–</dd>
  1246. <dt class="col-5">Total Area sqm</dt><dd class="col-7" id="area_sqm">–</dd>
  1247. <dt class="col-5">Total Area ha</dt><dd class="col-7" id="area_ha">–</dd>
  1248. <dt class="col-5">Locality</dt><dd class="col-7" id="pb_locality">–</dd>
  1249. </dl>
  1250. </div>
  1251. <div class="col-md-6">
  1252. <dl class="row small mb-0">
  1253. <dt class="col-5">Planning Scheme</dt><dd class="col-7" id="pb_scheme">–</dd>
  1254. <dt class="col-5">Zones</dt><dd class="col-7" id="pb_zones">–</dd>
  1255. <dt class="col-5">Code Overlays</dt><dd class="col-7" id="pb_codes">–</dd>
  1256. </dl>
  1257. </div>
  1258. </div>
  1259. <hr>
  1260. <div class="row">
  1261. <div class="col-md-6">
  1262. <dl class="row small mb-0">
  1263. <dt class="col-5">tenure</dt><dd class="col-7" id="tenure">–</dd>
  1264. <dt class="col-5">lpi</dt><dd class="col-7" id="lpi">–</dd>
  1265. <dt class="col-5">list_guid</dt><dd class="col-7" id="list_guid">–</dd>
  1266. </dl>
  1267. </div>
  1268. <div class="col-md-6">
  1269. </div>
  1270. </div>
  1271. </div>
  1272. <div class="modal-footer">
  1273. <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
  1274. <button type="button" class="btn btn-primary" id="pb-apply">Apply to form</button>
  1275. </div>
  1276. </div>
  1277. </div>
  1278. </div>
  1279. <!-- Prefilled email text modal -->
  1280. <div class="modal fade" id="emailTemplateModal" tabindex="-1" role="dialog" aria-labelledby="emailTemplateLabel" aria-hidden="true">
  1281. <div class="modal-dialog modal-lg" role="document">
  1282. <div class="modal-content">
  1283. <div class="modal-header">
  1284. <h5 class="modal-title" id="emailTemplateLabel">Email text to council</h5>
  1285. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  1286. </div>
  1287. <div class="modal-body">
  1288. <ul class="nav nav-tabs" role="tablist">
  1289. <li class="nav-item">
  1290. <a class="nav-link" data-bs-toggle="tab" href="#tabText" role="tab">Plain text</a>
  1291. </li>
  1292. <li class="nav-item">
  1293. <a class="nav-link active" data-bs-toggle="tab" href="#tabHtml" role="tab">HTML email</a>
  1294. </li>
  1295. </ul>
  1296. <div class="tab-content">
  1297. <div class="tab-pane fade p-3" id="tabText" role="tabpanel">
  1298. <textarea id="emailText" class="form-control small" rows="10" readonly style="font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;"></textarea>
  1299. <p class="text-muted small mt-2 mb-0">
  1300. Uses fields: Site Address, Registered Title Owners, Property ID, Title Reference
  1301. </p>
  1302. </div>
  1303. <div class="tab-pane fade active show p-3" id="tabHtml" role="tabpanel">
  1304. <div id="emailHtmlPreview" class="border rounded p-3" style="background:#ffffff; color:#000000; font-family:Arial,Helvetica,sans-serif; font-size:14px; line-height:1.5;"></div>
  1305. <!--<textarea id="emailHtmlSource" class="form-control small mt-2" rows="8" readonly></textarea>
  1306. <p class="text-muted small mt-2 mb-0">
  1307. Preview above. Copy the HTML if you paste into an HTML-capable composer such as Gmail or Outlook.
  1308. </p>-->
  1309. </div>
  1310. </div>
  1311. </div>
  1312. <div class="modal-footer">
  1313. <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
  1314. <button type="button" class="btn btn-outline-secondary" id="copyEmailText">Copy text</button>
  1315. <button type="button" class="btn btn-outline-secondary" id="copyEmailHtml">Copy HTML</button>
  1316. <a href="#" class="btn btn-primary" id="openMailto">Open email draft</a>
  1317. </div>
  1318. </div>
  1319. </div>
  1320. </div>
  1321. <script type="text/javascript">
  1322. const drg = <?php echo (int)($drg ?? 0); ?>;
  1323. const folder_name = <?php echo json_encode(($drg ?? '') . ' - ' . ($site_address_street ?? '')); ?>;
  1324. $(function () {
  1325. document.querySelectorAll('[data-bs-toggle="popover"]')
  1326. .forEach(el => new bootstrap.Popover(el));
  1327. });
  1328. $(function () {
  1329. $(".datetime").each(function(){
  1330. $(this).datepicker({ format: 'yyyy-mm-dd', autoclose: true, todayBtn: true, todayHighlight: true });
  1331. });
  1332. });
  1333. $(function () {
  1334. $(".datemonth").each(function(){
  1335. $(this).datepicker({ format: 'MM yy', autoclose: true, todayBtn: true, todayHighlight: true });
  1336. });
  1337. });
  1338. // Create LOA from current form fields
  1339. $('#createLOA').on('click', async function () {
  1340. const job = String(drg || '').trim();
  1341. if (!job) { alert('Missing Job #'); return; }
  1342. const clientName = ($('#joint_name').val().trim()) ||
  1343. [$('#firstname').val().trim(), $('#lastname').val().trim()].filter(Boolean).join(' ');
  1344. const clientEmail = $('#client_email').val().trim();
  1345. const propertyAddr = $('#site_address').val().trim();
  1346. // NEW fields
  1347. const clientPhone = $('#phoneNumber').val().trim();
  1348. const clientAddress = $('#postal_address').val().trim();
  1349. const propertyPid = $('#property_id').val().trim();
  1350. const propertyTitle = $('#title_id').val().trim(); // server will split vol/folio if possible
  1351. //const startDate = $('#start_date').val?.().trim?.() || ''; // include if you add inputs
  1352. //const endDate = $('#end_date').val?.().trim?.() || '';
  1353. async function doCreate(overwrite) {
  1354. const fd = new FormData();
  1355. fd.append('action', 'loa_create');
  1356. fd.append('job', job);
  1357. fd.append('client_name', clientName);
  1358. fd.append('client_email', clientEmail);
  1359. fd.append('property_address', propertyAddr);
  1360. // NEW fields
  1361. fd.append('client_phone', clientPhone);
  1362. fd.append('client_address', clientAddress);
  1363. fd.append('property_pid', propertyPid);
  1364. fd.append('property_title', propertyTitle);
  1365. //fd.append('start_date', startDate);
  1366. //fd.append('end_date', endDate);
  1367. fd.append('overwrite', overwrite ? 1 : 0);
  1368. fd.append('csrf', $('#csrf').val());
  1369. const res = await fetch(location.pathname + '?action=loa_create', { method: 'POST', body: fd });
  1370. return res.json();
  1371. }
  1372. try {
  1373. let js = await doCreate(false);
  1374. // If file exists, the server will just update front matter (no prompt).
  1375. // If you still want an overwrite option:
  1376. if (!js.ok && js.error && js.error.toLowerCase().includes('exists')) {
  1377. if (confirm('An LOA already exists. Overwrite the whole file from template?')) {
  1378. js = await doCreate(true);
  1379. } else return;
  1380. }
  1381. if (js.ok) {
  1382. const msg = 'LOA saved for Job #' + job + (js.public_url ? '\n\nOpen signing page now?' : '');
  1383. if (confirm(msg) && js.public_url) window.open(js.public_url, '_blank', 'noopener');
  1384. } else {
  1385. alert(js.error || 'Failed to create/update LOA');
  1386. }
  1387. } catch (e) {
  1388. alert('Error creating LOA: ' + e.message);
  1389. }
  1390. });
  1391. // simple phone length “checker” (kept as-is)
  1392. function check() {
  1393. var mobile = document.getElementById('phoneNumber');
  1394. if(!mobile) return;
  1395. if(mobile.value.length !== 12){ /* no-op */ }
  1396. }
  1397. const isHideDismissableAlert = <?php echo json_encode($isHideDismissableAlert ?? 0); ?>;
  1398. window.autocompletes = {};
  1399. var placeSearch, clickedGeolocationField = null;
  1400. var componentForm = {
  1401. street_number: 'short_name',
  1402. route: 'long_name',
  1403. locality: 'long_name',
  1404. administrative_area_level_1: 'short_name',
  1405. postal_code: 'short_name'
  1406. };
  1407. $(document).ready(function() {
  1408. if (isHideDismissableAlert > 0) {
  1409. $(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function () {
  1410. document.querySelectorAll('.alert-dismissible').forEach(el => {
  1411. bootstrap.Alert.getOrCreateInstance(el).close();
  1412. });
  1413. });
  1414. }
  1415. if (drg > 0) {
  1416. const debouncedStore = $.debounce(500, function(name, value) { storeField(name, value); });
  1417. $('.savable-text-field').on('keyup', function(e) {
  1418. const key = e.keyCode || e.which;
  1419. const systemKeys = [9,13,16,17,18,37,38,39,40,91];
  1420. if (systemKeys.includes(key)) return;
  1421. debouncedStore($(this).prop('name'), $(this).val());
  1422. });
  1423. }
  1424. $('.savable-date-field').on('change', function () {
  1425. storeField($(this).prop('name'), $(this).val());
  1426. });
  1427. $('.savable-dropdown-field').on('change', function () {
  1428. const name = $(this).prop('name');
  1429. const value = $(this).val();
  1430. storeField(name, value);
  1431. $(this).removeClass('form-control-danger');
  1432. if (this.id === 'building_surveyors_select') {
  1433. const meta = this.options[this.selectedIndex]?.dataset?.id || '';
  1434. $('#building_surveyors_meta').val(meta);
  1435. storeField('building_surveyors_meta', meta);
  1436. }
  1437. });
  1438. $('.savable-checkbox-field').on('change', function () {
  1439. storeField($(this).prop('name'), $(this).is(":checked") ? 1 : 0);
  1440. });
  1441. $('.savable-radio-field').on('change', function () {
  1442. storeField($(this).prop('name'), $(this).val());
  1443. });
  1444. // phone mask
  1445. const phoneInput = document.getElementById('phoneNumber');
  1446. if (phoneInput) {
  1447. phoneInput.addEventListener('keyup', function(evt){
  1448. phoneInput.value = phoneFormat(phoneInput.value);
  1449. });
  1450. }
  1451. }); // <--- correctly closes $(document).ready
  1452. String.prototype.toProperCase = function () {
  1453. return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
  1454. };
  1455. var rectangle, map, infoWindow, rectPoly, journey = '', rotate = '';
  1456. function stateDisplay(shortCode) {
  1457. if (!shortCode) return '';
  1458. const s = shortCode.toUpperCase();
  1459. const map = { TAS: 'Tas', VIC: 'Vic', QLD: 'Qld', NSW: 'NSW', WA: 'WA', SA: 'SA', ACT: 'ACT', NT: 'NT' };
  1460. return map[s] || shortCode;
  1461. }
  1462. // Google Places — global so callback can find it
  1463. window.initAutocomplete = function initAutocomplete() {
  1464. const inputs = document.getElementsByClassName('map-autocomplete');
  1465. for (let i = 0; i < inputs.length; i++) {
  1466. const el = inputs[i];
  1467. const ac = new google.maps.places.Autocomplete(
  1468. el,
  1469. { types: ['address'], componentRestrictions: { country: 'au' } }
  1470. );
  1471. ac.setFields(['address_component', 'geometry']);
  1472. window.autocompletes[el.id] = ac; // store for geolocate()
  1473. ac.addListener('place_changed', () => fillInAddress(el, ac));
  1474. }
  1475. };
  1476. function fillInAddress(targetInput, ac) {
  1477. const place = ac.getPlace();
  1478. if (!place || !place.address_components) return;
  1479. const parts = { street_number: '', route: '', locality: '', state: '', postal_code: '' };
  1480. for (const comp of place.address_components) {
  1481. const type = comp.types[0];
  1482. if (type === 'street_number') parts.street_number = comp.short_name || '';
  1483. if (type === 'route') parts.route = comp.long_name || '';
  1484. if (type === 'locality') parts.locality = comp.long_name || '';
  1485. if (type === 'administrative_area_level_1') parts.state = comp.short_name || '';
  1486. if (type === 'postal_code') parts.postal_code = comp.short_name || '';
  1487. }
  1488. if (parts.street_number && parts.route && parts.locality && parts.state && parts.postal_code) {
  1489. const formatted = `${parts.street_number} ${parts.route}, ${parts.locality}, ${stateDisplay(parts.state)}, ${parts.postal_code}`;
  1490. targetInput.value = formatted;
  1491. if (typeof storeField === 'function') {
  1492. try { storeField(targetInput.name || targetInput.id, formatted); } catch (e) {}
  1493. }
  1494. if (targetInput.id === 'site_address' && typeof writeIfReady === 'function') {
  1495. try { writeIfReady(); } catch (e) {}
  1496. }
  1497. // NEW: council lookup for TAS
  1498. if (parts.state && parts.state.toUpperCase() === 'TAS') {
  1499. const url = `classes/council_lookup.php?town=${encodeURIComponent(parts.locality)}&postcode=${encodeURIComponent(parts.postal_code)}&state=TAS`;
  1500. fetch(url)
  1501. .then(r => r.json())
  1502. .then(data => {
  1503. if (data && data.ok && data.council) {
  1504. const councilEl = document.getElementById('council');
  1505. if (councilEl) {
  1506. councilEl.value = data.council;
  1507. }
  1508. if (typeof storeField === 'function') {
  1509. storeField('council', data.council);
  1510. }
  1511. // If you also want to store the shapeFile, uncomment:
  1512. // if (data.shapeFile) storeField('shapeFile', data.shapeFile);
  1513. }
  1514. })
  1515. .catch(() => { /* silent fail is fine */ });
  1516. }
  1517. // store lat/lng if available
  1518. if (place.geometry && place.geometry.location) {
  1519. const lat = place.geometry.location.lat();
  1520. const lng = place.geometry.location.lng();
  1521. $('#site_lat').val(lat);
  1522. $('#site_lng').val(lng);
  1523. storeField('site_lat', lat);
  1524. storeField('site_lng', lng);
  1525. }
  1526. if (typeof storeField === 'function') {
  1527. try { storeField(targetInput.name || targetInput.id, formatted); } catch (e) {}
  1528. }
  1529. }
  1530. }
  1531. function geolocate(el) {
  1532. if (!el || !el.id) return;
  1533. clickedGeolocationField = el.name;
  1534. const ac = window.autocompletes[el.id];
  1535. if (!ac) return;
  1536. if (navigator.geolocation) {
  1537. navigator.geolocation.getCurrentPosition(function(position) {
  1538. const circle = new google.maps.Circle({
  1539. center: { lat: position.coords.latitude, lng: position.coords.longitude },
  1540. radius: position.coords.accuracy
  1541. });
  1542. ac.setBounds(circle.getBounds());
  1543. });
  1544. }
  1545. }
  1546. function getElevation(lat, lng) {
  1547. var elevationApiKey = 'AIzaSyB-QceOYrDe9otynMmQ9iNF3yEZzbpsanM';
  1548. var elevationApiUrl = `https://maps.googleapis.com/maps/api/elevation/json?locations=${lat},${lng}&key=${elevationApiKey}`;
  1549. fetch(elevationApiUrl)
  1550. .then(function (response) { return response.json(); })
  1551. .then(function (data) {
  1552. if (data.results.length > 0) {
  1553. var elevation = data.results[0].elevation;
  1554. var el = document.getElementById('elevation');
  1555. if (el) el.value = elevation;
  1556. }
  1557. })
  1558. .catch(function (error) { console.error('Error fetching elevation: ' + error); });
  1559. }
  1560. // AU-ish phone mask
  1561. function phoneFormat(input){
  1562. input = input.replace(/\D/g,'');
  1563. input = input.substring(0,20);
  1564. var size = input.length;
  1565. if(size === 0){
  1566. input = input;
  1567. } else if(size < 4){
  1568. input = input + ' ';
  1569. } else if(size < 7){
  1570. input = input.substring(0,4)+' '+input.substring(4,6);
  1571. } else if (input.startsWith("04") ) {
  1572. input = input.substring(0,4)+' '+input.substring(4,7)+' '+input.substring(7,20);
  1573. } else if (input.startsWith("+44") ) {
  1574. input = input;
  1575. } else {
  1576. input = input.substring(0,2)+' '+input.substring(2,6)+' '+input.substring(6,20);
  1577. }
  1578. return input;
  1579. }
  1580. function storeField(name, value) {
  1581. $.ajax({
  1582. url: "database.php",
  1583. type: "POST",
  1584. data: {
  1585. action: 'client-brief',
  1586. drg: drg,
  1587. field_name: name,
  1588. field_value: value,
  1589. csrf: $('#csrf').val()
  1590. },
  1591. success: function(data) {
  1592. try {
  1593. data = $.parseJSON(data);
  1594. if (!data.success) alert('Error: ' + data.message);
  1595. } catch(e) {
  1596. console.warn('Non-JSON response', data);
  1597. }
  1598. },
  1599. error: function() { alert("Please check for Errors."); }
  1600. });
  1601. }
  1602. document.getElementById('authorize_button').addEventListener('click', (e) => {
  1603. e.preventDefault();
  1604. handleAuthClick();
  1605. });
  1606. document.getElementById('signout_button').addEventListener('click', (e) => {
  1607. e.preventDefault();
  1608. handleSignoutClick();
  1609. });
  1610. // Google API creds
  1611. var CLIENT_ID = '615226084553-ujv34r7f62a4p6hvupq7v6rnnt04h59v.apps.googleusercontent.com';
  1612. var API_KEY = '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';
  1613. const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
  1614. var SCOPES = 'https://www.googleapis.com/auth/drive';
  1615. // TODO: Set this to the Google Drive folder ID of the root projects directory
  1616. // (e.g. the "[03] Projects 20XX" folder). Without this, new job folders are
  1617. // created in the signed-in user's Drive root, not the shared projects directory.
  1618. // Find the ID by opening the folder in Drive and copying the ID from the URL:
  1619. // https://drive.google.com/drive/folders/<FOLDER_ID_HERE>
  1620. const PROJECTS_PARENT_FOLDER_ID = ''; // <-- paste folder ID here
  1621. let tokenClient, gapiInited = false, gisInited = false;
  1622. window.gapiLoaded = function () {
  1623. gapi.load('client', async () => {
  1624. try {
  1625. await gapi.client.init({ apiKey: API_KEY, discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'] });
  1626. gapiInited = true;
  1627. maybeEnableButtons();
  1628. } catch (err) {
  1629. console.warn('Discovery failed, falling back to gapi.client.load()', err);
  1630. // small backoff retries
  1631. for (let i = 0; i < 3; i++) {
  1632. try {
  1633. await new Promise(r => setTimeout(r, 400 * (i + 1)));
  1634. await gapi.client.load('drive', 'v3');
  1635. gapiInited = true;
  1636. maybeEnableButtons();
  1637. break;
  1638. } catch (e) {
  1639. if (i === 2) console.error('Drive load failed after retries', e);
  1640. }
  1641. }
  1642. }
  1643. });
  1644. };
  1645. window.gisLoaded = function () {
  1646. tokenClient = google.accounts.oauth2.initTokenClient({
  1647. client_id: CLIENT_ID,
  1648. scope: SCOPES,
  1649. callback: () => {}
  1650. });
  1651. gisInited = true;
  1652. maybeEnableButtons();
  1653. };
  1654. function maybeEnableButtons() {
  1655. if (gapiInited && gisInited) {
  1656. document.getElementById('authorize_button').style.visibility = 'visible';
  1657. document.getElementById('createFolder')?.addEventListener('click', ensureAuthThenCreateFolder);
  1658. }
  1659. }
  1660. function handleAuthClick() {
  1661. tokenClient.callback = (resp) => {
  1662. if (resp.error) { console.error(resp); return; }
  1663. document.getElementById('signout_button').style.visibility = 'visible';
  1664. document.getElementById('authorize_button').innerText = 'Refresh';
  1665. };
  1666. if (!gapi.client.getToken()) tokenClient.requestAccessToken({ prompt: 'consent' });
  1667. else tokenClient.requestAccessToken({ prompt: '' });
  1668. }
  1669. function handleSignoutClick() {
  1670. const tok = gapi.client.getToken();
  1671. if (!tok) return;
  1672. google.accounts.oauth2.revoke(tok.access_token);
  1673. gapi.client.setToken(null);
  1674. document.getElementById('authorize_button').innerText = 'Authorize';
  1675. document.getElementById('signout_button').style.visibility = 'hidden';
  1676. }
  1677. async function ensureAuthThenCreateFolder() {
  1678. if (!gapi.client.getToken()) {
  1679. tokenClient.callback = async (resp) => {
  1680. if (resp && resp.error) { console.error(resp); return; }
  1681. await createFolder();
  1682. };
  1683. tokenClient.requestAccessToken({ prompt: 'consent' });
  1684. } else {
  1685. await createFolder();
  1686. }
  1687. }
  1688. async function createFolder() {
  1689. try {
  1690. const resource = { name: folder_name, mimeType: 'application/vnd.google-apps.folder' };
  1691. if (PROJECTS_PARENT_FOLDER_ID) resource.parents = [PROJECTS_PARENT_FOLDER_ID];
  1692. const res = await gapi.client.drive.files.create({
  1693. resource,
  1694. fields: 'id,name,webViewLink',
  1695. supportsAllDrives: true
  1696. });
  1697. alert('Folder created: ' + res.result.name + '\nID: ' + res.result.id);
  1698. } catch (err) {
  1699. const detail = err?.result?.error || err;
  1700. console.error('Drive create error:', detail);
  1701. alert('Drive error: ' + (detail.message || detail.statusText || JSON.stringify(detail)));
  1702. }
  1703. }
  1704. /* ******************************************************************************************* */
  1705. async function fetchAndExtractData() {
  1706. const lat = $('#site_lat').val();
  1707. const lng = $('#site_lng').val();
  1708. if (!lat || !lng) {
  1709. alert('Please select a Google suggested Site Address first so we can capture coordinates.');
  1710. return;
  1711. }
  1712. // Helper to stringify area object from list_lookup.php
  1713. const formatArea = (area) => {
  1714. if (!area) return '';
  1715. // prefer sqm label, fall back to ha
  1716. return area.sqm_label || area.ha_label || '';
  1717. };
  1718. try {
  1719. const resp = await fetch('classes/list_lookup.php', {
  1720. method: 'POST',
  1721. headers: { 'Content-Type': 'application/json' },
  1722. body: JSON.stringify({ lat: parseFloat(lat), lng: parseFloat(lng) })
  1723. });
  1724. const data = await resp.json();
  1725. // Show any lookup error in the modal
  1726. if (!resp.ok || !data || data.ok !== true) {
  1727. $('#pb-errors').removeClass('d-none').text((data && data.error) ? data.error : 'Lookup failed');
  1728. bootstrap.Modal.getOrCreateInstance(document.getElementById('planbuildPreview')).show();
  1729. return;
  1730. }
  1731. $('#pb-errors').addClass('d-none').text('');
  1732. // Fill the preview modal
  1733. $('#pb_pid').text(data.pid || '–');
  1734. $('#pb_title').text(data.title_id || '–');
  1735. $('#pb_area').text(formatArea(data.total_area) || '–');
  1736. $('#pb_locality').text(data.locality || '–'); // include if you added locality in PHP later
  1737. //$('#pb_council').text(data.council || '–');
  1738. $('#pb_scheme').text(data.planning_scheme || '–');
  1739. $('#pb_zones').text((Array.isArray(data.planning_zones) ? data.planning_zones.join(', ') : (data.planning_zones || '')) || '–');
  1740. $('#pb_codes').text((Array.isArray(data.planning_codes) ? data.planning_codes.join(', ') : (data.planning_codes || '')) || '–');
  1741. $('#area_sqm').text(data.area_sqm || '–');
  1742. $('#area_ha').text(data.area_ha || '–');
  1743. $('#tenure').text(data.tenure || '–');
  1744. $('#lpi').text(data.lpi || '–');
  1745. $('#list_guid').text(data.list_guid || '–');
  1746. bootstrap.Modal.getOrCreateInstance(document.getElementById('planbuildPreview')).show();
  1747. // Apply button writes to the form and DB
  1748. $('#pb-apply').off('click').on('click', () => {
  1749. const apply = (id, v) => {
  1750. const el = document.getElementById(id);
  1751. if (el && typeof v !== 'undefined' && v !== null) {
  1752. el.value = v;
  1753. storeField(id, v);
  1754. }
  1755. };
  1756. apply('property_id', data.pid || '');
  1757. apply('title_id', data.title_id || '');
  1758. apply('total_area', formatArea(data.total_area) || '');
  1759. apply('planning_scheme', data.planning_scheme || '');
  1760. apply('planning_zones', Array.isArray(data.planning_zones) ? data.planning_zones.join(', ') : (data.planning_zones || ''));
  1761. apply('planning_codes', Array.isArray(data.planning_codes) ? data.planning_codes.join(', ') : (data.planning_codes || ''));
  1762. //apply('council', data.council || '');
  1763. if (document.getElementById('locality')) apply('locality', data.locality || '');
  1764. // Optional extras if you add matching inputs:
  1765. //apply('area_sqm', data.total_area?.sqm_label || '');
  1766. //apply('area_ha', data.total_area?.ha_label || '');
  1767. //apply('tenure', data.tenure || '');
  1768. //apply('lpi', data.lpi || '');
  1769. //apply('list_guid',data.list_guid|| '');
  1770. bootstrap.Modal.getOrCreateInstance(document.getElementById('planbuildPreview')).hide();
  1771. });
  1772. } catch (e) {
  1773. $('#pb-errors').removeClass('d-none').text('Error fetching data: ' + e.message);
  1774. bootstrap.Modal.getOrCreateInstance(document.getElementById('planbuildPreview')).show();
  1775. }
  1776. };
  1777. // Build the exact body text from current form values
  1778. const useDynamicGreeting = false;
  1779. function getGreeting() {
  1780. if (!useDynamicGreeting) return 'Good Morning,';
  1781. const hour = new Date().getHours();
  1782. if (hour < 12) return 'Good Morning,';
  1783. if (hour < 18) return 'Good Afternoon,';
  1784. return 'Good Evening,';
  1785. }
  1786. function escapeHtml(s) {
  1787. return String(s || '').replace(/[&<>"']/g, c => ({
  1788. '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'
  1789. }[c]));
  1790. }
  1791. function buildPlanningEmailText() {
  1792. const greet = getGreeting();
  1793. const address = ($('#site_address').val() || '').trim();
  1794. const owners = ($('#registered_owner').val() || '').trim();
  1795. const pid = ($('#property_id').val() || '').trim();
  1796. const title = ($('#title_id').val() || '').trim();
  1797. const fallback = 'N/A';
  1798. const lines = [
  1799. greet,
  1800. '',
  1801. 'I am requesting the planning and plumbing information for the following address:',
  1802. `Property Address: ${address || fallback}`,
  1803. `Property Owners: ${owners || fallback}`,
  1804. `Property ID: ${pid || fallback}`,
  1805. `Title/Vol: ${title || fallback}`,
  1806. '',
  1807. 'Attached is a signed Letter of Authority from the property owners.'
  1808. ];
  1809. return lines.join('\n');
  1810. }
  1811. function buildPlanningEmailHtml() {
  1812. const greet = getGreeting();
  1813. const address = ($('#site_address').val() || '').trim();
  1814. const owners = ($('#registered_owner').val() || '').trim();
  1815. const pid = ($('#property_id').val() || '').trim();
  1816. const title = ($('#title_id').val() || '').trim();
  1817. const fallback = 'N/A';
  1818. return `
  1819. <div style="background:#ffffff;padding:16px;font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.5;color:#000000;">
  1820. <p style="margin:0 0 12px 0;">${escapeHtml(greet)}</p>
  1821. <p style="margin:0 0 12px 0;">I am requesting the planning and plumbing information for the following address:</p>
  1822. <table role="presentation" cellpadding="0" cellspacing="0" width="75%" style="border-collapse:collapse;background:#ffffff;color:#000000;">
  1823. <tr>
  1824. <td style="padding:8px;border:1px solid #d1d5db;font-weight:bold;width:200px;">Property Address</td>
  1825. <td style="padding:8px;border:1px solid #d1d5db;">${escapeHtml(address || fallback)}</td>
  1826. </tr>
  1827. <tr>
  1828. <td style="padding:8px;border:1px solid #d1d5db;font-weight:bold;">Property Owners</td>
  1829. <td style="padding:8px;border:1px solid #d1d5db;">${escapeHtml(owners || fallback)}</td>
  1830. </tr>
  1831. <tr>
  1832. <td style="padding:8px;border:1px solid #d1d5db;font-weight:bold;">Property ID</td>
  1833. <td style="padding:8px;border:1px solid #d1d5db;">${escapeHtml(pid || fallback)}</td>
  1834. </tr>
  1835. <tr>
  1836. <td style="padding:8px;border:1px solid #d1d5db;font-weight:bold;">Title/Vol</td>
  1837. <td style="padding:8px;border:1px solid #d1d5db;">${escapeHtml(title || fallback)}</td>
  1838. </tr>
  1839. </table>
  1840. <p style="margin:12px 0 0 0;">Attached is a signed Letter of Authority from the property owners.</p>
  1841. </div>`;
  1842. }
  1843. function copyFromTextarea(selector, btnEl) {
  1844. const val = $(selector).val();
  1845. const doWrite = async () => {
  1846. if (navigator.clipboard && navigator.clipboard.writeText) {
  1847. await navigator.clipboard.writeText(val);
  1848. } else {
  1849. const ta = document.querySelector(selector);
  1850. ta.focus();
  1851. ta.select();
  1852. document.execCommand('copy');
  1853. }
  1854. };
  1855. doWrite().then(() => {
  1856. const original = btnEl.textContent;
  1857. btnEl.textContent = 'Copied';
  1858. btnEl.disabled = true;
  1859. setTimeout(() => { btnEl.textContent = original; btnEl.disabled = false; }, 1200);
  1860. }).catch(() => {
  1861. alert('Copy failed. You can select and copy the text manually.');
  1862. });
  1863. }
  1864. // Single modal hook
  1865. document.getElementById('emailTemplateModal')
  1866. .addEventListener('show.bs.modal', function () {
  1867. const text = buildPlanningEmailText();
  1868. const html = buildPlanningEmailHtml();
  1869. document.getElementById('emailText').value = text;
  1870. document.getElementById('emailHtmlPreview').innerHTML = html;
  1871. document.getElementById('emailHtmlSource').value = html;
  1872. // Build subject using the current site address
  1873. const addr = (document.getElementById('site_address')?.value || '').trim() || 'N/A';
  1874. const subject = encodeURIComponent(`Request for Property Information - ${addr}`);
  1875. const body = encodeURIComponent(text);
  1876. document.getElementById('openMailto').href = `mailto:?subject=${subject}&body=${body}`;
  1877. });
  1878. // Single copy handlers
  1879. $('#copyEmailText').on('click', function () {
  1880. copyFromTextarea('#emailText', this);
  1881. });
  1882. $('#copyEmailHtml').on('click', function () {
  1883. copyFromTextarea('#emailHtmlSource', this);
  1884. });
  1885. </script>
  1886. <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script>
  1887. <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB-QceOYrDe9otynMmQ9iNF3yEZzbpsanM&libraries=places&loading=async&callback=initAutocomplete" ></script>
  1888. <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
  1889. <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
  1890. </body>
  1891. </html>