client-brief.php 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139
  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()
  380. {
  381. try {
  382. $client = new Google\Client();
  383. $client->useApplicationDefaultCredentials();
  384. $client->addScope(Drive::DRIVE);
  385. $driveService = new Drive($client);
  386. $fileMetadata = new Drive\DriveFile(array(
  387. 'name' => '[03]Projects 2023',
  388. 'mimeType' => 'application/vnd.google-apps.folder'));
  389. $file = $driveService->files->create($fileMetadata, array(
  390. 'fields' => 'id'));
  391. printf("Folder ID: %s\n", $file->id);
  392. return $file->id;
  393. }catch(Exception $e) {
  394. echo "Error Message: ".$e;
  395. }
  396. }
  397. function createDealHubSpot($newDealData)
  398. {
  399. global $accessToken;
  400. $endpoint = 'https://api.hubapi.com/crm/v3/objects/deals';
  401. $curl = curl_init();
  402. curl_setopt_array($curl, [
  403. CURLOPT_URL => $endpoint,
  404. CURLOPT_RETURNTRANSFER => true,
  405. CURLOPT_POST => true,
  406. CURLOPT_POSTFIELDS => json_encode($newDealData),
  407. CURLOPT_HTTPHEADER => [
  408. 'Authorization: Bearer ' . $accessToken, // Use OAuth 2.0 token OR 'Authorization: Bearer ' . $apiKey for API key
  409. 'Content-Type: application/json'
  410. ]
  411. ]);
  412. $response = curl_exec($curl);
  413. curl_close($curl);
  414. return $response;
  415. }
  416. function updateDealHubSpot($dealId, $data)
  417. {
  418. global $accessToken;
  419. $endpoint = 'https://api.hubapi.com/crm/v3/objects/deals/' . $dealId;
  420. $curl = curl_init();
  421. curl_setopt_array($curl, [
  422. CURLOPT_URL => $endpoint,
  423. CURLOPT_RETURNTRANSFER => true,
  424. CURLOPT_CUSTOMREQUEST => 'PATCH',
  425. CURLOPT_POSTFIELDS => json_encode($data),
  426. CURLOPT_HTTPHEADER => [
  427. 'Authorization: Bearer ' . $accessToken, // Use OAuth 2.0 token OR 'Authorization: Bearer ' . $apiKey for API key
  428. 'Content-Type: application/json'
  429. ]
  430. ]);
  431. $response = curl_exec($curl);
  432. curl_close($curl);
  433. return $response;
  434. }
  435. function addContactToHubSpot($newContactData) {
  436. global $accessToken;
  437. $endpoint = 'https://api.hubapi.com/crm/v3/objects/contacts';
  438. $curl = curl_init();
  439. curl_setopt_array($curl, [
  440. CURLOPT_URL => $endpoint,
  441. CURLOPT_RETURNTRANSFER => true,
  442. CURLOPT_POST => true,
  443. CURLOPT_POSTFIELDS => json_encode($newContactData),
  444. CURLOPT_HTTPHEADER => [
  445. 'Authorization: Bearer ' . $accessToken,
  446. 'Content-Type: application/json'
  447. ]
  448. ]);
  449. $response = curl_exec($curl);
  450. curl_close($curl);
  451. return $response;
  452. }
  453. function searchContact($query) {
  454. global $accessToken;
  455. $endpoint = 'https://api.hubapi.com/crm/v3/objects/contacts/search';
  456. $queryJson = json_encode($query);
  457. $ch = curl_init($endpoint);
  458. curl_setopt($ch, CURLOPT_POST, 1);
  459. curl_setopt($ch, CURLOPT_POSTFIELDS, $queryJson);
  460. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $accessToken, 'Content-Type: application/json'));
  461. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  462. $response = curl_exec($ch);
  463. if (curl_errno($ch)) {
  464. echo 'Error making cURL request: ' . curl_error($ch);
  465. }
  466. curl_close($ch);
  467. return $response;
  468. }
  469. function updateContact($contactId, $data) {
  470. global $accessToken;
  471. $endpoint = 'https://api.hubapi.com/crm/v3/objects/contacts/' . $contactId;
  472. $curl = curl_init();
  473. curl_setopt_array($curl, [
  474. CURLOPT_URL => $endpoint,
  475. CURLOPT_RETURNTRANSFER => true,
  476. CURLOPT_CUSTOMREQUEST => 'PUT',
  477. CURLOPT_POSTFIELDS => json_encode($data),
  478. CURLOPT_HTTPHEADER => [
  479. 'Authorization: Bearer ' . $accessToken,
  480. 'Content-Type: application/json'
  481. ]
  482. ]);
  483. $response = curl_exec($curl);
  484. curl_close($curl);
  485. return $response;
  486. }
  487. function format_E164($num)
  488. {
  489. $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
  490. try {
  491. $phoneProto = $phoneUtil->parse($num, "AU");
  492. return [
  493. "phone_number" => $phoneUtil->format($phoneProto, \libphonenumber\PhoneNumberFormat::INTERNATIONAL),
  494. "phone_type" => $phoneUtil->getNumberType($phoneProto)
  495. ];
  496. } catch (\libphonenumber\NumberParseException $e) {
  497. return null;
  498. }
  499. }
  500. if (!empty($drg) and !empty($_POST['add_client_to_crm']) and empty($contactId)) {
  501. try {
  502. $query = [
  503. "filterGroups" => [
  504. [
  505. "filters" => [
  506. [
  507. "value" => $_POST['firstname'] . "*",
  508. "propertyName" => 'firstname',
  509. "operator" => "EQ"
  510. ],
  511. [
  512. "value" => $_POST['lastname'] . "*",
  513. "propertyName" => "lastname",
  514. "operator" => "EQ"
  515. ],
  516. [
  517. "value" => $_POST['client_mobile'] . "*",
  518. "propertyName" => "phone",
  519. "operator" => "EQ"
  520. ]
  521. ]
  522. ]
  523. ],
  524. ];
  525. $response = json_decode(searchContact($query), true);
  526. if ($response['total'] > 0) {
  527. 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>";
  528. } else {
  529. $newContactData = [
  530. 'properties' => [
  531. 'firstname' => $_POST['firstname'],
  532. 'lastname' => $_POST['lastname'],
  533. 'description' => 'Added via Online Client Brief Form # ' . $drg,
  534. 'company' => $_POST['joint_name'],
  535. 'email' => $_POST['client_email'],
  536. 'address' => $_POST['postal_address'],
  537. 'city' => $_POST['postal_address_town'],
  538. 'zip' => $_POST['postal_address_postcode'],
  539. 'country' => 'AU',
  540. 'state' => $_POST['postal_address_state'],
  541. 'hubspot_owner_id' => '585959844',
  542. ]
  543. ];
  544. if($phone) {
  545. if($phone["phone_type"] == \libphonenumber\PhoneNumberType::MOBILE)
  546. $newContactData["properties"]["mobilephone"] = $phone["phone_number"];
  547. else
  548. $newContactData["properties"]["phone"] = $phone["phone_number"];
  549. }
  550. $response = addContactToHubSpot($newContactData);
  551. file_put_contents("crmadd.log", $response);
  552. $createdContact = json_decode($response, true);
  553. if ($createdContact['id'] > 0) {
  554. $crm_id = intval($createdContact['id']);
  555. $result = mysqli_query($con, "UPDATE details SET crm_id = '{$crm_id}' WHERE drg = '{$drg}'");
  556. if (!$result) {
  557. printf("Error: %s\n", mysqli_error($con));
  558. exit();
  559. } else {
  560. 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>";
  561. $isHideDismissableAlert = 1;
  562. }
  563. }
  564. }
  565. } catch (\Exception $err) {
  566. echo '<pre>' . $err->getMessage() . '</pre>';
  567. die();
  568. }
  569. } elseif (!empty($drg) and !empty($_POST['edit_client_in_crm']) and !empty($contactId)) {
  570. try {
  571. $data = [
  572. 'properties' => [
  573. 'firstname' => $_POST['firstname'],
  574. 'lastname' => $_POST['lastname'],
  575. 'company' => $_POST['joint_name'],
  576. 'email' => $_POST['client_email'],
  577. 'address' => $_POST['postal_address'],
  578. 'city' => $_POST['postal_address_town'],
  579. 'zip' => $_POST['postal_address_postcode'],
  580. 'country' => 'AU',
  581. 'state' => $_POST['postal_address_state'],
  582. 'hubspot_owner_id' => '585959844',
  583. ]
  584. ];
  585. if($phone) {
  586. if($phone["phone_type"] == \libphonenumber\PhoneNumberType::MOBILE)
  587. $data["properties"]["mobilephone"] = $phone["phone_number"];
  588. else
  589. $data["properties"]["phone"] = $phone["phone_number"];
  590. }
  591. $query = [
  592. "filterGroups" => [
  593. [
  594. "filters" => [
  595. [
  596. "value" => $_POST['firstname'] . "*",
  597. "propertyName" => 'firstname',
  598. "operator" => "EQ"
  599. ],
  600. [
  601. "value" => $_POST['lastname'] . "*",
  602. "propertyName" => "lastname",
  603. "operator" => "EQ"
  604. ],
  605. [
  606. "value" => $_POST['client_mobile'] . "*",
  607. "propertyName" => "phone",
  608. "operator" => "EQ"
  609. ]
  610. ]
  611. ]
  612. ],
  613. ];
  614. $response = json_decode(searchContact($query), true);
  615. if ($response['total'] > 0) {
  616. $response = updateContact($contactId, $data);
  617. $result = mysqli_query($con, "UPDATE details SET crm_id = '{$response['id']}' WHERE drg = '{$drg}'");
  618. file_put_contents("crmupdate.log", $response);
  619. $response = json_decode($response, true);
  620. if ($response['id'] > 0) {
  621. 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>";
  622. $isHideDismissableAlert = 1;
  623. }
  624. } else {
  625. $response = addContactToHubSpot($newContactData);
  626. file_put_contents("crmadd.log", $response);
  627. $createdContact = json_decode($response, true);
  628. if ($createdContact['id'] > 0) {
  629. $crm_id = intval($createdContact['id']);
  630. 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>";
  631. $isHideDismissableAlert = 1;
  632. }
  633. }
  634. } catch (\Exception $err) {
  635. echo '<pre>Crm Id: ' . $contactId . ', response: ' . $err->getMessage() . '</pre>';
  636. die();
  637. }
  638. }
  639. // Create Deal from Enquiry Form
  640. if (!empty($quid) and !empty($_POST['add_deal_to_hubspot']) and empty($dealId)) {
  641. try {
  642. $newDealData = [
  643. 'associations' => [
  644. [
  645. 'types' => [
  646. [
  647. 'associationCategory' => 'HUBSPOT_DEFINED',
  648. 'associationTypeId' => 3,
  649. ]
  650. ],
  651. 'to' => [
  652. 'id' => $_POST['crm_id']
  653. ],
  654. ]
  655. ],
  656. 'properties' => [
  657. 'dealname' => $_POST['quid'] . ' - ' . $_POST['client'],
  658. 'dealtype' => 'newbusiness', // New or Existing Business - do we do a sql lookup and see if there is some won jobs for this customer ??
  659. 'hubspot_owner_id' => $_POST['hubspot_owner_id'],
  660. 'createdate' => $_POST['enquiry_date'],
  661. //assign deal to contact with hubspot contact id
  662. //'associatedCompanyIds' => $_POST['company_id'],
  663. 'pipeline' => '64401721',
  664. 'dealstage' => '126963334',
  665. 'width' => str_replace('m', '', $_POST['width']),
  666. 'length' => str_replace('m', '', $_POST['length']),
  667. 'height' => str_replace('m', '', $_POST['height']),
  668. 'quote_type' => $_POST['quote_type'],
  669. 'type' => $_POST['product'],
  670. 'roof_type' => $_POST['roof_style'],
  671. 'sides' => $_POST['side_walls'],
  672. 'ends' => $_POST['end_walls'],
  673. 'internal' => $_POST['internal_walls'],
  674. 'qty_bays' => $_POST['bay_qty'],
  675. //'bay_width' => $_POST['bay_width'],
  676. //'uneven_bays' => $_POST['bay_uneven'],
  677. 'quote' => $_POST['quid'],
  678. ]
  679. ];
  680. $response = createDealHubSpot($newDealData);
  681. file_put_contents("crmdeal.log", $response);
  682. $createdDeal = json_decode($response, true);
  683. if ($createdDeal['id'] > 0) {
  684. $dealId = intval($createdDeal['id']);
  685. $result = mysqli_query($con, "UPDATE details SET dealId = '{$dealId}' WHERE drg = '{$drg}'");
  686. 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>";
  687. $isHideDismissableAlert = 1;
  688. }
  689. } catch (\Exception $err) {
  690. echo '<pre>' . $err->getMessage() . '</pre>';
  691. die();
  692. }
  693. } elseif (!empty($drg) and !empty($_POST['update_deal_in_hubspot']) and !empty($dealId)) {
  694. try {
  695. $updateDealData = [
  696. 'properties' => [
  697. 'dealname' => $_POST['drg'] . ' - ' . $_POST['client'],
  698. 'hubspot_owner_id' => $_POST['hubspot_owner_id'],
  699. 'createdate' => $_POST['enquiry_date'],
  700. //assign deal to contact with hubspot contact id
  701. //'associatedCompanyIds' => $_POST['company_id'],
  702. 'quote_type' => $_POST['quote_type'],
  703. 'type' => $_POST['product'],
  704. ],
  705. 'associations' => [
  706. 'types' => [
  707. 'association_category' => 'HUBSPOT_DEFINED',
  708. 'association_type_id' => 3
  709. ],
  710. 'to' => [
  711. 'id' => $_POST['crm_id']
  712. ]
  713. ]
  714. ];
  715. $response = updateDealHubSpot($dealId, $updateDealData);
  716. file_put_contents("crmdeal.log", $response);
  717. $updatedDeal = json_decode($response, true);
  718. if ($updatedDeal['id'] > 0) {
  719. $dealId = intval($updatedDeal['id']);
  720. 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>";
  721. $isHideDismissableAlert = 1;
  722. }
  723. } catch (\Exception $err) {
  724. echo '<pre>' . $err->getMessage() . '</pre>';
  725. die();
  726. }
  727. }
  728. if (!empty($_GET['drg'])) {
  729. $contact_button = '';
  730. if ($crm_id > 5) {
  731. $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>';
  732. } else {
  733. $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>';
  734. }
  735. }
  736. ?>
  737. <!doctype html>
  738. <html lang="en">
  739. <head>
  740. <meta charset="utf-8">
  741. <meta name="viewport" content="width=device-width, initial-scale=1">
  742. <title><?php echo $drg; ?> - Client Brief</title>
  743. <link rel="shortcut icon" href="images/blueprint.ico" type="image/x-icon">
  744. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
  745. <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  746. <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  747. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
  748. <link href="css/blueprint.css" rel="stylesheet">
  749. <link href="css/print.css" rel="stylesheet" media="print">
  750. <script type="text/javascript" src="https://use.fontawesome.com/1e2844bb90.js"></script>
  751. <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
  752. <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>
  753. </head>
  754. <body>
  755. <nav class="navbar bg-brown-dark brown-light border-bottom border-body d-print-none" data-bs-theme="dark">
  756. <div class="container-fluid">
  757. <a class="navbar-brand brown-light" href="#">
  758. <img src="images/blueprint-logo-light.png" alt="Logo" width="30" height="24" class="d-inline-block align-text-top">
  759. Modulos Design
  760. </a>
  761. </div>
  762. </nav>
  763. <div class="container">
  764. <div class="row pt-2">
  765. <div class="col-sm-4 col-md-4 pt-3">
  766. <img class="img-fluid logo pt-2" src="images/blueprint-full-logo-medium.png" alt="Modulos Design">
  767. </div>
  768. <div class="col-sm-4 col-md-4 m-auto text-center">
  769. <h3 class="architect text-center">Job: <?php echo $drg; ?></h3>
  770. </div>
  771. <div class="col-sm-4 col-md-4 text-end pt-3">
  772. <h2 class="fw-bold text-end mb-1">Client Brief Form</h2>
  773. <h4 class="text-end mb-1">
  774. <span class="fw-bold brown-two"><?php echo $enquiry_date; ?></span>
  775. </h4>
  776. </div>
  777. </div>
  778. <hr>
  779. <form id="client-brief" data-remote="true" method="post" accept-charset="UTF-8">
  780. <input type="hidden" name="csrf" id="csrf" value="<?php echo $csrf; ?>">
  781. <div class="row">
  782. <div class="col-12 col-md-6">
  783. <div class="row ">
  784. <div class="col ">
  785. <h4 class="fw-bold">Client Details</h4>
  786. </div>
  787. </div>
  788. <div class="mb-1">
  789. <div class="row ">
  790. <div class="col-12 col-md-6">
  791. <label for="firstname" class="form-label form-label-sm p-0 m-0">Clients Name</label>
  792. <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">
  793. </div>
  794. <div class="col-12 col-md-6">
  795. <label for="lastname" class="form-label form-label-sm p-0 m-0"></label>
  796. <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">
  797. </div>
  798. </div>
  799. </div>
  800. <div class="mb-1">
  801. <label for="joint_name" class="form-label form-label-sm p-0 m-0">T/As - Joint Names</label>
  802. <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">
  803. </div>
  804. <div class="mb-1">
  805. <label for="postal_address" class="form-label form-label-sm p-0 m-0">Clients Postal Address</label>
  806. <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">
  807. </div>
  808. <div class="mb-1">
  809. <div class="row ">
  810. <div class="col-md-6">
  811. <label for="phoneNumber" class="form-label form-label-sm p-0 m-0">Clients Mobile</label>
  812. <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">
  813. </div>
  814. <div class="col-12 col-md-3 d-print-none">
  815. <label for="crm_id" class="form-label form-label-sm p-0 m-0">CID</label>
  816. <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; ?>" >
  817. </div>
  818. <div class="col-12 col-md-3 d-print-none">
  819. <label for="dealId" class="form-label form-label-sm p-0 m-0">DID</label>
  820. <input type="text" class="form-control form-control-sm savable-text-field brown-three" id="dealId" name="dealId" value="<?php echo $dealId; ?>" >
  821. </div>
  822. </div>
  823. </div>
  824. <div class="mb-1">
  825. <label for="client_email" class="form-label form-label-sm p-0 m-0">Email address</label>
  826. <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">
  827. </div>
  828. <hr>
  829. <div class="row ">
  830. <div class="col ">
  831. <h4 class="fw-bold">Proposed Site Details</h4>
  832. </div>
  833. </div>
  834. <div class="mb-1">
  835. <label for="site_address" class="form-label form-label-sm p-0 m-0">Site Address</label>
  836. <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">
  837. <input type="hidden" class="savable-text-field" id="site_lat" name="site_lat" value="<?php echo htmlspecialchars($site_lat ?? '', ENT_QUOTES, 'UTF-8'); ?>">
  838. <input type="hidden" class="savable-text-field" id="site_lng" name="site_lng" value="<?php echo htmlspecialchars($site_lng ?? '', ENT_QUOTES, 'UTF-8'); ?>">
  839. </div>
  840. <div class="row g-3">
  841. <div class="col-12 col-md-6">
  842. <label for="property_id" class="form-label form-label-sm p-0 m-0">Property ID:</label>
  843. <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">
  844. </div>
  845. <div class="col-12 col-md-6">
  846. <label for="title_id" class="form-label form-label-sm p-0 m-0">Title Reference:</label>
  847. <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">
  848. </div>
  849. </div>
  850. <div class="mb-1">
  851. <label for="registered_owner" class="form-label form-label-sm p-0 m-0">Registered Title Owners:</label>
  852. <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="">
  853. </div>
  854. <div class="row g-3">
  855. <div class="col-12 col-md-5">
  856. <label for="council" class="form-label form-label-sm p-0 m-0">Council:</label>
  857. <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">
  858. </div>
  859. <div class="col-12 col-md-3">
  860. <label for="elevation" class="form-label form-label-sm p-0 m-0">Elev (AHD):</label>
  861. <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)">
  862. </div>
  863. <div class="col-12 col-md-4">
  864. <label for="elevation" class="form-label form-label-sm p-0 m-0">Land Area (m2):</label>
  865. <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="">
  866. </div>
  867. </div>
  868. <div class="row g-3">
  869. <div class="col-12 col-md-4">
  870. <label for="planning_zones" class="form-label form-label-sm p-0 m-0">Planning Zones:</label>
  871. <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">
  872. </div>
  873. <div class="col-12 col-md-8">
  874. <label for="planning_scheme" class="form-label form-label-sm p-0 m-0">Planning Scheme:</label>
  875. <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">
  876. </div>
  877. </div>
  878. <div class="row g-3">
  879. <div class="col-12">
  880. <label for="planning_codes" class="form-label form-label-sm p-0 m-0">Planning Codes:</label>
  881. <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">
  882. </div>
  883. </div>
  884. <hr>
  885. <div class="row ">
  886. <div class="col ">
  887. <h4 class="fw-bold">Design Brief</h4>
  888. </div>
  889. </div>
  890. <div class="mb-1">
  891. <label for="design_style" class="form-label form-label-sm p-0 m-0">Type of Design</label>
  892. <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'); ?>" >
  893. </div>
  894. <div class="row g-3">
  895. <div class="col-12 col-md-6">
  896. <label for="build_type" class="form-label form-label-sm p-0 m-0">Build Type:</label>
  897. <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">
  898. <option><?php echo $build_type; ?></option>
  899. <option >New Residential</option>
  900. <option >Residential Extension</option>
  901. <option >New Commercial</option>
  902. <option >Commercial Extension</option>
  903. <option >Shed or Ancillary Dwelling</option>
  904. <option >Pool</option>
  905. <option >Interior Design</option>
  906. <option >Other</option>
  907. </select>
  908. </div>
  909. <div class="col-12 col-md-6">
  910. <label for="scope" class="form-label form-label-sm p-0 m-0">Our Scope</label>
  911. <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'); ?>" >
  912. </div>
  913. </div>
  914. </div>
  915. <div class="col-12 col-md-6">
  916. <div class="row d-print-none">
  917. <div class="col-12 col-md my-1 d-grid">
  918. <?php echo $contact_button; ?>
  919. </div>
  920. <div class="col-12 col-md my-1 d-grid">
  921. <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>
  922. </div>
  923. <div class="col-12 col-md my-1 d-grid">
  924. <button type="button" class="btn btn-sm bg-brown-three brown-five" id="createFolder"><i class="bi bi-folder-fill"></i> Create Job</button>
  925. </div>
  926. <div class="col-12 col-md my-1 d-grid">
  927. <button type="button" class="btn btn-sm bg-brown-three brown-five" onclick="fetchAndExtractData()"><i class="bi bi-folder-fill"></i> Planbuild</button>
  928. <!-- <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> -->
  929. </div>
  930. </div>
  931. <div class="row d-print-none">
  932. <div class="col">
  933. <hr class="mvt-3">
  934. </div>
  935. </div>
  936. <div class="row ">
  937. <div class="col-12">
  938. <h5 class="fw-bold">Brief Checklist</h5>
  939. <p class="extra-light small">Have the following documents being provided?</p>
  940. </div>
  941. </div>
  942. <div class="row ">
  943. <div class="col-6 col-md-4">
  944. <div class="form-check form-check-inline savable-checkbox">
  945. <input class="form-check-input savable-checkbox-field"
  946. type="checkbox"
  947. name="copy_title" id="copy_title"
  948. value="1"
  949. <?php if ('1' == $copy_title) { echo 'checked'; } ?>
  950. >
  951. <label class="form-check-label" for="copy_title">Copy of Title</label>
  952. </div>
  953. </div>
  954. <div class="col-6 col-md-4">
  955. <div class="form-check form-check-inline savable-checkbox">
  956. <input class="form-check-input savable-checkbox-field"
  957. type="checkbox"
  958. name="original_plans" id="original_plans"
  959. value="1"
  960. <?php if ('1' == $original_plans) { echo 'checked'; } ?>
  961. >
  962. <label class="form-check-label" for="original_plans">Original Plans</label>
  963. </div>
  964. </div>
  965. <div class="col-6 col-md-4">
  966. <div class="form-check form-check-inline savable-checkbox">
  967. <input class="form-check-input savable-checkbox-field"
  968. type="checkbox"
  969. name="concepts_styles" id="concepts_styles"
  970. value="1"
  971. <?php if ('1' == $concepts_styles) { echo 'checked'; } ?>
  972. >
  973. <label class="form-check-label" for="concepts_styles">Concepts & Styles</label>
  974. </div>
  975. </div>
  976. </div>
  977. <div class="row ">
  978. <div class="col-6 col-md-4">
  979. <div class="form-check form-check-inline savable-checkbox">
  980. <input class="form-check-input savable-checkbox-field"
  981. type="checkbox"
  982. name="loa_signed" id="loa_signed"
  983. value="1"
  984. <?php if ('1' == $loa_signed) { echo 'checked'; } ?>
  985. >
  986. <label class="form-check-label" for="loa_signed">LOA signed</label>
  987. </div>
  988. </div>
  989. <div class="col-6 col-md-4">
  990. <div class="form-check form-check-inline savable-checkbox">
  991. <input class="form-check-input savable-checkbox-field"
  992. type="checkbox"
  993. name="da_application" id="da_application"
  994. value="1"
  995. <?php if ('1' == $da_application) { echo 'checked'; } ?>
  996. >
  997. <label class="form-check-label" for="da_application">DA Application</label>
  998. </div>
  999. </div>
  1000. <div class="col-6 col-md-4">
  1001. <div class="form-check form-check-inline savable-checkbox">
  1002. <input class="form-check-input savable-checkbox-field"
  1003. type="checkbox"
  1004. name="ba_application" id="ba_application"
  1005. value="1"
  1006. <?php if ('1' == $ba_application) { echo 'checked'; } ?>
  1007. >
  1008. <label class="form-check-label" for="ba_application">BA Application</label>
  1009. </div>
  1010. </div>
  1011. </div>
  1012. <hr>
  1013. <div class="row ">
  1014. <div class="col ">
  1015. <h5 class="fw-bold">Design Outputs</h5>
  1016. <p class="extra-light small"></p>
  1017. </div>
  1018. </div>
  1019. <div class="row ">
  1020. <div class="col-6 col-md-4">
  1021. <div class="form-check form-check-inline savable-checkbox">
  1022. <input class="form-check-input savable-checkbox-field"
  1023. type="checkbox"
  1024. name="concepts_3d" id="concepts_3d"
  1025. value="1"
  1026. <?php if ('1' == $concepts_3d) { echo 'checked'; } ?>
  1027. >
  1028. <label class="form-check-label" for="concepts_3d">3D Concepts</label>
  1029. </div>
  1030. </div>
  1031. <div class="col-6 col-md-4">
  1032. <div class="form-check form-check-inline savable-checkbox">
  1033. <input class="form-check-input savable-checkbox-field"
  1034. type="checkbox"
  1035. name="draft_floorPlan" id="draft_floorPlan"
  1036. value="1"
  1037. <?php if ('1' == $draft_floorPlan) { echo 'checked'; } ?>
  1038. >
  1039. <label class="form-check-label" for="draft_floorPlan">Draft Floor Plan</label>
  1040. </div>
  1041. </div>
  1042. <div class="col-6 col-md-4">
  1043. <div class="form-check form-check-inline savable-checkbox">
  1044. <input class="form-check-input savable-checkbox-field"
  1045. type="checkbox"
  1046. name="fire_report" id="fire_report"
  1047. value="1"
  1048. <?php if ('1' == $fire_report) { echo 'checked'; } ?>
  1049. >
  1050. <label class="form-check-label" for="fire_report">Fire Report</label>
  1051. </div>
  1052. </div>
  1053. </div>
  1054. <div class="row ">
  1055. <div class="col-6 col-md-4">
  1056. <div class="form-check form-check-inline savable-checkbox">
  1057. <input class="form-check-input savable-checkbox-field"
  1058. type="checkbox"
  1059. name="energy_report" id="energy_report"
  1060. value="1"
  1061. <?php if ('1' == $energy_report) { echo 'checked'; } ?>
  1062. >
  1063. <label class="form-check-label" for="energy_report">Energy Report</label>
  1064. </div>
  1065. </div>
  1066. <div class="col-6 col-md-4">
  1067. <div class="form-check form-check-inline savable-checkbox">
  1068. <input class="form-check-input savable-checkbox-field"
  1069. type="checkbox"
  1070. name="tender_set" id="tender_set"
  1071. value="1"
  1072. <?php if ('1' == $tender_set) { echo 'checked'; } ?>
  1073. >
  1074. <label class="form-check-label" for="tender_set">Tender Doc Set</label>
  1075. </div>
  1076. </div>
  1077. <div class="col-6 col-md-4">
  1078. <div class="form-check form-check-inline savable-checkbox">
  1079. <input class="form-check-input savable-checkbox-field"
  1080. type="checkbox"
  1081. name="quantity_survey" id="quantity_survey"
  1082. value="1"
  1083. <?php if ('1' == $quantity_survey) { echo 'checked'; } ?>
  1084. >
  1085. <label class="form-check-label" for="quantity_survey">Quantity Survey</label>
  1086. </div>
  1087. </div>
  1088. </div>
  1089. <hr>
  1090. <div class="row ">
  1091. <div class="col ">
  1092. <h5 class="fw-bold">Presentations</h5>
  1093. <p class="extra-light small"></p>
  1094. </div>
  1095. </div>
  1096. <div class="row ">
  1097. <div class="col-6 col-md-4">
  1098. <div class="form-check form-check-inline savable-checkbox">
  1099. <input class="form-check-input savable-checkbox-field"
  1100. type="checkbox"
  1101. name="vr_concepts" id="vr_concepts"
  1102. value="1"
  1103. <?php if ('1' == $vr_concepts) { echo 'checked'; } ?>
  1104. >
  1105. <label class="form-check-label" for="vr_concepts">VR Concepts</label>
  1106. </div>
  1107. </div>
  1108. <div class="col-6 col-md-4">
  1109. <div class="form-check form-check-inline savable-checkbox">
  1110. <input class="form-check-input savable-checkbox-field"
  1111. type="checkbox"
  1112. name="render_set" id="render_set"
  1113. value="1"
  1114. <?php if ('1' == $render_set) { echo 'checked'; } ?>
  1115. >
  1116. <label class="form-check-label" for="render_set">Full Rended Set</label>
  1117. </div>
  1118. </div>
  1119. <div class="col-6 col-md-4">
  1120. <div class="form-check form-check-inline savable-checkbox">
  1121. <input class="form-check-input savable-checkbox-field"
  1122. type="checkbox"
  1123. name="model_3d" id="model_3d"
  1124. value="1"
  1125. <?php if ('1' == $model_3d) { echo 'checked'; } ?>
  1126. >
  1127. <label class="form-check-label" for="model_3d">3D Model</label>
  1128. </div>
  1129. </div>
  1130. </div>
  1131. <hr>
  1132. <div class="row ">
  1133. <div class="col ">
  1134. <h5 class="fw-bold">Create Documents</h5>
  1135. <p class="extra-light small"></p>
  1136. </div>
  1137. </div>
  1138. <div class="row d-print-none mb-2">
  1139. <div class="col d-inline-flex gap-1">
  1140. <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>
  1141. </div>
  1142. </div>
  1143. <div class="row d-print-none">
  1144. <div class="col d-inline-flex gap-1">
  1145. <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>
  1146. <div class="form-check d-inline-flex align-items-center ms-2">
  1147. <input class="form-check-input" type="checkbox" id="updateFrontMatter">
  1148. <label class="form-check-label ms-1" for="updateFrontMatter">
  1149. Update contact details if file exists
  1150. </label>
  1151. </div>
  1152. </div>
  1153. </div>
  1154. <hr>
  1155. <div class="row ">
  1156. <div class="col ">
  1157. <h4 class="fw-bold">Investment Details</h4>
  1158. </div>
  1159. </div>
  1160. <div class="row g-3">
  1161. <div class="col-12 col-md-6">
  1162. <label for="budget_low" class="form-label form-label-sm p-0 m-0">Budget Range (Lower)</label>
  1163. <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">
  1164. </div>
  1165. <div class="col-12 col-md-6">
  1166. <label for="budget_high" class="form-label form-label-sm p-0 m-0">Budget Range (Upper)</label>
  1167. <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">
  1168. </div>
  1169. </div>
  1170. <div class="mb-1">
  1171. <label for="finance_status" class="form-label form-label-sm p-0 m-0">Finance</label>
  1172. <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 ?">
  1173. </div>
  1174. <hr>
  1175. <div class="row ">
  1176. <div class="col ">
  1177. <h4 class="fw-bold">Services Used</h4>
  1178. </div>
  1179. </div>
  1180. <div class="row g-3">
  1181. <div class="col-12">
  1182. <select class="form-control form-control-sm" id="building_surveyors_select" name="building_surveyors">
  1183. <label for="building_surveyors">Building Surveyor:</label>
  1184. <option selected="" disabled="">Select Building Surveyor</option>
  1185. <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>
  1186. <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>
  1187. <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>
  1188. <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>
  1189. </select>
  1190. <input type="hidden" id="building_surveyors_meta" name="building_surveyors_meta" value="<?php echo $building_surveyors_meta ?? ''; ?>">
  1191. </div>
  1192. <div class="col-12 col-md-6">
  1193. </div>
  1194. </div>
  1195. <div class="row mb-1">
  1196. <div class="col-12 col-md-6">
  1197. <div class="row mb-1">
  1198. <div class="col-12 col-md-6">
  1199. </div>
  1200. </div>
  1201. </div>
  1202. </div>
  1203. </div>
  1204. </div>
  1205. <hr>
  1206. <div class="row">
  1207. <div class="col">
  1208. <div class="mb-1">
  1209. <label for="details" class="form-label form-label-sm p-0 m-0">Details</label>
  1210. <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>
  1211. </div>
  1212. </div>
  1213. </div>
  1214. <hr>
  1215. <div class="row d-print-none">
  1216. <div class="col-6">
  1217. <!--Add buttons to initiate auth sequence and sign out-->
  1218. <button id="authorize_button" type="button" class="btn btn-sm bg-brown-three brown-five">Authorize</button>
  1219. <button id="signout_button" type="button" class="btn btn-sm bg-brown-three brown-five">Sign Out</button>
  1220. </div>
  1221. </div>
  1222. <hr>
  1223. <footer class="footer">
  1224. <p class="text-center">&copy; 2023 - Modulos Design</p>
  1225. </footer>
  1226. </form>
  1227. </div>
  1228. <!-- Planbuild/LIST preview modal -->
  1229. <div class="modal fade" id="planbuildPreview" tabindex="-1" role="dialog" aria-labelledby="planbuildPreviewLabel" aria-hidden="true">
  1230. <div class="modal-dialog modal-lg" role="document">
  1231. <div class="modal-content">
  1232. <div class="modal-header">
  1233. <h5 class="modal-title" id="planbuildPreviewLabel">Property info from LIST</h5>
  1234. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  1235. </div>
  1236. <div class="modal-body">
  1237. <div id="pb-errors" class="alert alert-danger d-none"></div>
  1238. <div class="row">
  1239. <div class="col-md-6">
  1240. <dl class="row small mb-0">
  1241. <dt class="col-5">PID</dt><dd class="col-7" id="pb_pid">–</dd>
  1242. <dt class="col-5">Title</dt><dd class="col-7" id="pb_title">–</dd>
  1243. <dt class="col-5">Total Area</dt><dd class="col-7" id="pb_area">–</dd>
  1244. <dt class="col-5">Total Area sqm</dt><dd class="col-7" id="area_sqm">–</dd>
  1245. <dt class="col-5">Total Area ha</dt><dd class="col-7" id="area_ha">–</dd>
  1246. <dt class="col-5">Locality</dt><dd class="col-7" id="pb_locality">–</dd>
  1247. </dl>
  1248. </div>
  1249. <div class="col-md-6">
  1250. <dl class="row small mb-0">
  1251. <dt class="col-5">Planning Scheme</dt><dd class="col-7" id="pb_scheme">–</dd>
  1252. <dt class="col-5">Zones</dt><dd class="col-7" id="pb_zones">–</dd>
  1253. <dt class="col-5">Code Overlays</dt><dd class="col-7" id="pb_codes">–</dd>
  1254. </dl>
  1255. </div>
  1256. </div>
  1257. <hr>
  1258. <div class="row">
  1259. <div class="col-md-6">
  1260. <dl class="row small mb-0">
  1261. <dt class="col-5">tenure</dt><dd class="col-7" id="tenure">–</dd>
  1262. <dt class="col-5">lpi</dt><dd class="col-7" id="lpi">–</dd>
  1263. <dt class="col-5">list_guid</dt><dd class="col-7" id="list_guid">–</dd>
  1264. </dl>
  1265. </div>
  1266. <div class="col-md-6">
  1267. </div>
  1268. </div>
  1269. </div>
  1270. <div class="modal-footer">
  1271. <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
  1272. <button type="button" class="btn btn-primary" id="pb-apply">Apply to form</button>
  1273. </div>
  1274. </div>
  1275. </div>
  1276. </div>
  1277. <!-- Prefilled email text modal -->
  1278. <div class="modal fade" id="emailTemplateModal" tabindex="-1" role="dialog" aria-labelledby="emailTemplateLabel" aria-hidden="true">
  1279. <div class="modal-dialog modal-lg" role="document">
  1280. <div class="modal-content">
  1281. <div class="modal-header">
  1282. <h5 class="modal-title" id="emailTemplateLabel">Email text to council</h5>
  1283. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  1284. </div>
  1285. <div class="modal-body">
  1286. <ul class="nav nav-tabs" role="tablist">
  1287. <li class="nav-item">
  1288. <a class="nav-link" data-bs-toggle="tab" href="#tabText" role="tab">Plain text</a>
  1289. </li>
  1290. <li class="nav-item">
  1291. <a class="nav-link active" data-bs-toggle="tab" href="#tabHtml" role="tab">HTML email</a>
  1292. </li>
  1293. </ul>
  1294. <div class="tab-content">
  1295. <div class="tab-pane fade p-3" id="tabText" role="tabpanel">
  1296. <textarea id="emailText" class="form-control small" rows="10" readonly style="font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;"></textarea>
  1297. <p class="text-muted small mt-2 mb-0">
  1298. Uses fields: Site Address, Registered Title Owners, Property ID, Title Reference
  1299. </p>
  1300. </div>
  1301. <div class="tab-pane fade active show p-3" id="tabHtml" role="tabpanel">
  1302. <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>
  1303. <!--<textarea id="emailHtmlSource" class="form-control small mt-2" rows="8" readonly></textarea>
  1304. <p class="text-muted small mt-2 mb-0">
  1305. Preview above. Copy the HTML if you paste into an HTML-capable composer such as Gmail or Outlook.
  1306. </p>-->
  1307. </div>
  1308. </div>
  1309. </div>
  1310. <div class="modal-footer">
  1311. <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
  1312. <button type="button" class="btn btn-outline-secondary" id="copyEmailText">Copy text</button>
  1313. <button type="button" class="btn btn-outline-secondary" id="copyEmailHtml">Copy HTML</button>
  1314. <a href="#" class="btn btn-primary" id="openMailto">Open email draft</a>
  1315. </div>
  1316. </div>
  1317. </div>
  1318. </div>
  1319. <script type="text/javascript">
  1320. const drg = <?php echo (int)($drg ?? 0); ?>;
  1321. const folder_name = <?php echo json_encode(($drg ?? '') . ' - ' . ($site_address_street ?? '')); ?>;
  1322. $(function () {
  1323. document.querySelectorAll('[data-bs-toggle="popover"]')
  1324. .forEach(el => new bootstrap.Popover(el));
  1325. });
  1326. $(function () {
  1327. $(".datetime").each(function(){
  1328. $(this).datepicker({ format: 'yyyy-mm-dd', autoclose: true, todayBtn: true, todayHighlight: true });
  1329. });
  1330. });
  1331. $(function () {
  1332. $(".datemonth").each(function(){
  1333. $(this).datepicker({ format: 'MM yy', autoclose: true, todayBtn: true, todayHighlight: true });
  1334. });
  1335. });
  1336. // Create LOA from current form fields
  1337. $('#createLOA').on('click', async function () {
  1338. const job = String(drg || '').trim();
  1339. if (!job) { alert('Missing Job #'); return; }
  1340. const clientName = ($('#joint_name').val().trim()) ||
  1341. [$('#firstname').val().trim(), $('#lastname').val().trim()].filter(Boolean).join(' ');
  1342. const clientEmail = $('#client_email').val().trim();
  1343. const propertyAddr = $('#site_address').val().trim();
  1344. // NEW fields
  1345. const clientPhone = $('#phoneNumber').val().trim();
  1346. const clientAddress = $('#postal_address').val().trim();
  1347. const propertyPid = $('#property_id').val().trim();
  1348. const propertyTitle = $('#title_id').val().trim(); // server will split vol/folio if possible
  1349. //const startDate = $('#start_date').val?.().trim?.() || ''; // include if you add inputs
  1350. //const endDate = $('#end_date').val?.().trim?.() || '';
  1351. async function doCreate(overwrite) {
  1352. const fd = new FormData();
  1353. fd.append('action', 'loa_create');
  1354. fd.append('job', job);
  1355. fd.append('client_name', clientName);
  1356. fd.append('client_email', clientEmail);
  1357. fd.append('property_address', propertyAddr);
  1358. // NEW fields
  1359. fd.append('client_phone', clientPhone);
  1360. fd.append('client_address', clientAddress);
  1361. fd.append('property_pid', propertyPid);
  1362. fd.append('property_title', propertyTitle);
  1363. //fd.append('start_date', startDate);
  1364. //fd.append('end_date', endDate);
  1365. fd.append('overwrite', overwrite ? 1 : 0);
  1366. fd.append('csrf', $('#csrf').val());
  1367. const res = await fetch(location.pathname + '?action=loa_create', { method: 'POST', body: fd });
  1368. return res.json();
  1369. }
  1370. try {
  1371. let js = await doCreate(false);
  1372. // If file exists, the server will just update front matter (no prompt).
  1373. // If you still want an overwrite option:
  1374. if (!js.ok && js.error && js.error.toLowerCase().includes('exists')) {
  1375. if (confirm('An LOA already exists. Overwrite the whole file from template?')) {
  1376. js = await doCreate(true);
  1377. } else return;
  1378. }
  1379. if (js.ok) {
  1380. const msg = 'LOA saved for Job #' + job + (js.public_url ? '\n\nOpen signing page now?' : '');
  1381. if (confirm(msg) && js.public_url) window.open(js.public_url, '_blank', 'noopener');
  1382. } else {
  1383. alert(js.error || 'Failed to create/update LOA');
  1384. }
  1385. } catch (e) {
  1386. alert('Error creating LOA: ' + e.message);
  1387. }
  1388. });
  1389. // simple phone length “checker” (kept as-is)
  1390. function check() {
  1391. var mobile = document.getElementById('phoneNumber');
  1392. if(!mobile) return;
  1393. if(mobile.value.length !== 12){ /* no-op */ }
  1394. }
  1395. const isHideDismissableAlert = <?php echo json_encode($isHideDismissableAlert ?? 0); ?>;
  1396. window.autocompletes = {};
  1397. var placeSearch, clickedGeolocationField = null;
  1398. var componentForm = {
  1399. street_number: 'short_name',
  1400. route: 'long_name',
  1401. locality: 'long_name',
  1402. administrative_area_level_1: 'short_name',
  1403. postal_code: 'short_name'
  1404. };
  1405. $(document).ready(function() {
  1406. if (isHideDismissableAlert > 0) {
  1407. $(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function () {
  1408. document.querySelectorAll('.alert-dismissible').forEach(el => {
  1409. bootstrap.Alert.getOrCreateInstance(el).close();
  1410. });
  1411. });
  1412. }
  1413. if (drg > 0) {
  1414. const debouncedStore = $.debounce(500, function(name, value) { storeField(name, value); });
  1415. $('.savable-text-field').on('keyup', function(e) {
  1416. const key = e.keyCode || e.which;
  1417. const systemKeys = [9,13,16,17,18,37,38,39,40,91];
  1418. if (systemKeys.includes(key)) return;
  1419. debouncedStore($(this).prop('name'), $(this).val());
  1420. });
  1421. }
  1422. $('.savable-date-field').on('change', function () {
  1423. storeField($(this).prop('name'), $(this).val());
  1424. });
  1425. $('.savable-dropdown-field').on('change', function () {
  1426. const name = $(this).prop('name');
  1427. const value = $(this).val();
  1428. storeField(name, value);
  1429. $(this).removeClass('form-control-danger');
  1430. if (this.id === 'building_surveyors_select') {
  1431. const meta = this.options[this.selectedIndex]?.dataset?.id || '';
  1432. $('#building_surveyors_meta').val(meta);
  1433. storeField('building_surveyors_meta', meta);
  1434. }
  1435. });
  1436. $('.savable-checkbox-field').on('change', function () {
  1437. storeField($(this).prop('name'), $(this).is(":checked") ? 1 : 0);
  1438. });
  1439. $('.savable-radio-field').on('change', function () {
  1440. storeField($(this).prop('name'), $(this).val());
  1441. });
  1442. // phone mask
  1443. const phoneInput = document.getElementById('phoneNumber');
  1444. if (phoneInput) {
  1445. phoneInput.addEventListener('keyup', function(evt){
  1446. phoneInput.value = phoneFormat(phoneInput.value);
  1447. });
  1448. }
  1449. }); // <--- correctly closes $(document).ready
  1450. String.prototype.toProperCase = function () {
  1451. return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
  1452. };
  1453. var rectangle, map, infoWindow, rectPoly, journey = '', rotate = '';
  1454. function stateDisplay(shortCode) {
  1455. if (!shortCode) return '';
  1456. const s = shortCode.toUpperCase();
  1457. const map = { TAS: 'Tas', VIC: 'Vic', QLD: 'Qld', NSW: 'NSW', WA: 'WA', SA: 'SA', ACT: 'ACT', NT: 'NT' };
  1458. return map[s] || shortCode;
  1459. }
  1460. // Google Places — global so callback can find it
  1461. window.initAutocomplete = function initAutocomplete() {
  1462. const inputs = document.getElementsByClassName('map-autocomplete');
  1463. for (let i = 0; i < inputs.length; i++) {
  1464. const el = inputs[i];
  1465. const ac = new google.maps.places.Autocomplete(
  1466. el,
  1467. { types: ['address'], componentRestrictions: { country: 'au' } }
  1468. );
  1469. ac.setFields(['address_component', 'geometry']);
  1470. window.autocompletes[el.id] = ac; // store for geolocate()
  1471. ac.addListener('place_changed', () => fillInAddress(el, ac));
  1472. }
  1473. };
  1474. function fillInAddress(targetInput, ac) {
  1475. const place = ac.getPlace();
  1476. if (!place || !place.address_components) return;
  1477. const parts = { street_number: '', route: '', locality: '', state: '', postal_code: '' };
  1478. for (const comp of place.address_components) {
  1479. const type = comp.types[0];
  1480. if (type === 'street_number') parts.street_number = comp.short_name || '';
  1481. if (type === 'route') parts.route = comp.long_name || '';
  1482. if (type === 'locality') parts.locality = comp.long_name || '';
  1483. if (type === 'administrative_area_level_1') parts.state = comp.short_name || '';
  1484. if (type === 'postal_code') parts.postal_code = comp.short_name || '';
  1485. }
  1486. if (parts.street_number && parts.route && parts.locality && parts.state && parts.postal_code) {
  1487. const formatted = `${parts.street_number} ${parts.route}, ${parts.locality}, ${stateDisplay(parts.state)}, ${parts.postal_code}`;
  1488. targetInput.value = formatted;
  1489. if (typeof storeField === 'function') {
  1490. try { storeField(targetInput.name || targetInput.id, formatted); } catch (e) {}
  1491. }
  1492. if (targetInput.id === 'site_address' && typeof writeIfReady === 'function') {
  1493. try { writeIfReady(); } catch (e) {}
  1494. }
  1495. // NEW: council lookup for TAS
  1496. if (parts.state && parts.state.toUpperCase() === 'TAS') {
  1497. const url = `classes/council_lookup.php?town=${encodeURIComponent(parts.locality)}&postcode=${encodeURIComponent(parts.postal_code)}&state=TAS`;
  1498. fetch(url)
  1499. .then(r => r.json())
  1500. .then(data => {
  1501. if (data && data.ok && data.council) {
  1502. const councilEl = document.getElementById('council');
  1503. if (councilEl) {
  1504. councilEl.value = data.council;
  1505. }
  1506. if (typeof storeField === 'function') {
  1507. storeField('council', data.council);
  1508. }
  1509. // If you also want to store the shapeFile, uncomment:
  1510. // if (data.shapeFile) storeField('shapeFile', data.shapeFile);
  1511. }
  1512. })
  1513. .catch(() => { /* silent fail is fine */ });
  1514. }
  1515. // store lat/lng if available
  1516. if (place.geometry && place.geometry.location) {
  1517. const lat = place.geometry.location.lat();
  1518. const lng = place.geometry.location.lng();
  1519. $('#site_lat').val(lat);
  1520. $('#site_lng').val(lng);
  1521. storeField('site_lat', lat);
  1522. storeField('site_lng', lng);
  1523. }
  1524. if (typeof storeField === 'function') {
  1525. try { storeField(targetInput.name || targetInput.id, formatted); } catch (e) {}
  1526. }
  1527. }
  1528. }
  1529. function geolocate(el) {
  1530. if (!el || !el.id) return;
  1531. clickedGeolocationField = el.name;
  1532. const ac = window.autocompletes[el.id];
  1533. if (!ac) return;
  1534. if (navigator.geolocation) {
  1535. navigator.geolocation.getCurrentPosition(function(position) {
  1536. const circle = new google.maps.Circle({
  1537. center: { lat: position.coords.latitude, lng: position.coords.longitude },
  1538. radius: position.coords.accuracy
  1539. });
  1540. ac.setBounds(circle.getBounds());
  1541. });
  1542. }
  1543. }
  1544. function getElevation(lat, lng) {
  1545. var elevationApiKey = 'AIzaSyB-QceOYrDe9otynMmQ9iNF3yEZzbpsanM';
  1546. var elevationApiUrl = `https://maps.googleapis.com/maps/api/elevation/json?locations=${lat},${lng}&key=${elevationApiKey}`;
  1547. fetch(elevationApiUrl)
  1548. .then(function (response) { return response.json(); })
  1549. .then(function (data) {
  1550. if (data.results.length > 0) {
  1551. var elevation = data.results[0].elevation;
  1552. var el = document.getElementById('elevation');
  1553. if (el) el.value = elevation;
  1554. }
  1555. })
  1556. .catch(function (error) { console.error('Error fetching elevation: ' + error); });
  1557. }
  1558. // AU-ish phone mask
  1559. function phoneFormat(input){
  1560. input = input.replace(/\D/g,'');
  1561. input = input.substring(0,20);
  1562. var size = input.length;
  1563. if(size === 0){
  1564. input = input;
  1565. } else if(size < 4){
  1566. input = input + ' ';
  1567. } else if(size < 7){
  1568. input = input.substring(0,4)+' '+input.substring(4,6);
  1569. } else if (input.startsWith("04") ) {
  1570. input = input.substring(0,4)+' '+input.substring(4,7)+' '+input.substring(7,20);
  1571. } else if (input.startsWith("+44") ) {
  1572. input = input;
  1573. } else {
  1574. input = input.substring(0,2)+' '+input.substring(2,6)+' '+input.substring(6,20);
  1575. }
  1576. return input;
  1577. }
  1578. function storeField(name, value) {
  1579. $.ajax({
  1580. url: "database.php",
  1581. type: "POST",
  1582. data: {
  1583. action: 'client-brief',
  1584. drg: drg,
  1585. field_name: name,
  1586. field_value: value,
  1587. csrf: $('#csrf').val()
  1588. },
  1589. success: function(data) {
  1590. try {
  1591. data = $.parseJSON(data);
  1592. if (!data.success) alert('Error: ' + data.message);
  1593. } catch(e) {
  1594. console.warn('Non-JSON response', data);
  1595. }
  1596. },
  1597. error: function() { alert("Please check for Errors."); }
  1598. });
  1599. }
  1600. document.getElementById('authorize_button').addEventListener('click', (e) => {
  1601. e.preventDefault();
  1602. handleAuthClick();
  1603. });
  1604. document.getElementById('signout_button').addEventListener('click', (e) => {
  1605. e.preventDefault();
  1606. handleSignoutClick();
  1607. });
  1608. // Google API creds
  1609. var CLIENT_ID = '615226084553-ujv34r7f62a4p6hvupq7v6rnnt04h59v.apps.googleusercontent.com';
  1610. var API_KEY = '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';
  1611. const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
  1612. var SCOPES = 'https://www.googleapis.com/auth/drive';
  1613. // parent folder: supply a folder ID if you want a parent; leave '' for My Drive
  1614. const PROJECTS_PARENT_FOLDER_ID = ''; // e.g. '1AbCxyz...'
  1615. let tokenClient, gapiInited = false, gisInited = false;
  1616. window.gapiLoaded = function () {
  1617. gapi.load('client', async () => {
  1618. try {
  1619. await gapi.client.init({ apiKey: API_KEY, discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'] });
  1620. gapiInited = true;
  1621. maybeEnableButtons();
  1622. } catch (err) {
  1623. console.warn('Discovery failed, falling back to gapi.client.load()', err);
  1624. // small backoff retries
  1625. for (let i = 0; i < 3; i++) {
  1626. try {
  1627. await new Promise(r => setTimeout(r, 400 * (i + 1)));
  1628. await gapi.client.load('drive', 'v3');
  1629. gapiInited = true;
  1630. maybeEnableButtons();
  1631. break;
  1632. } catch (e) {
  1633. if (i === 2) console.error('Drive load failed after retries', e);
  1634. }
  1635. }
  1636. }
  1637. });
  1638. };
  1639. window.gisLoaded = function () {
  1640. tokenClient = google.accounts.oauth2.initTokenClient({
  1641. client_id: CLIENT_ID,
  1642. scope: SCOPES,
  1643. callback: () => {}
  1644. });
  1645. gisInited = true;
  1646. maybeEnableButtons();
  1647. };
  1648. function maybeEnableButtons() {
  1649. if (gapiInited && gisInited) {
  1650. document.getElementById('authorize_button').style.visibility = 'visible';
  1651. document.getElementById('createFolder')?.addEventListener('click', ensureAuthThenCreateFolder);
  1652. }
  1653. }
  1654. function handleAuthClick() {
  1655. tokenClient.callback = (resp) => {
  1656. if (resp.error) { console.error(resp); return; }
  1657. document.getElementById('signout_button').style.visibility = 'visible';
  1658. document.getElementById('authorize_button').innerText = 'Refresh';
  1659. };
  1660. if (!gapi.client.getToken()) tokenClient.requestAccessToken({ prompt: 'consent' });
  1661. else tokenClient.requestAccessToken({ prompt: '' });
  1662. }
  1663. function handleSignoutClick() {
  1664. const tok = gapi.client.getToken();
  1665. if (!tok) return;
  1666. google.accounts.oauth2.revoke(tok.access_token);
  1667. gapi.client.setToken(null);
  1668. document.getElementById('authorize_button').innerText = 'Authorize';
  1669. document.getElementById('signout_button').style.visibility = 'hidden';
  1670. }
  1671. async function ensureAuthThenCreateFolder() {
  1672. if (!gapi.client.getToken()) {
  1673. tokenClient.callback = async (resp) => {
  1674. if (resp && resp.error) { console.error(resp); return; }
  1675. await createFolder();
  1676. };
  1677. tokenClient.requestAccessToken({ prompt: 'consent' });
  1678. } else {
  1679. await createFolder();
  1680. }
  1681. }
  1682. async function createFolder() {
  1683. try {
  1684. const resource = { name: folder_name, mimeType: 'application/vnd.google-apps.folder' };
  1685. if (PROJECTS_PARENT_FOLDER_ID) resource.parents = [PROJECTS_PARENT_FOLDER_ID];
  1686. const res = await gapi.client.drive.files.create({
  1687. resource,
  1688. fields: 'id,name,webViewLink',
  1689. supportsAllDrives: true
  1690. });
  1691. alert('Folder created: ' + res.result.name + '\nID: ' + res.result.id);
  1692. } catch (err) {
  1693. const detail = err?.result?.error || err;
  1694. console.error('Drive create error:', detail);
  1695. alert('Drive error: ' + (detail.message || detail.statusText || JSON.stringify(detail)));
  1696. }
  1697. }
  1698. /* ******************************************************************************************* */
  1699. async function fetchAndExtractData() {
  1700. const lat = $('#site_lat').val();
  1701. const lng = $('#site_lng').val();
  1702. if (!lat || !lng) {
  1703. alert('Please select a Google suggested Site Address first so we can capture coordinates.');
  1704. return;
  1705. }
  1706. // Helper to stringify area object from list_lookup.php
  1707. const formatArea = (area) => {
  1708. if (!area) return '';
  1709. // prefer sqm label, fall back to ha
  1710. return area.sqm_label || area.ha_label || '';
  1711. };
  1712. try {
  1713. const resp = await fetch('classes/list_lookup.php', {
  1714. method: 'POST',
  1715. headers: { 'Content-Type': 'application/json' },
  1716. body: JSON.stringify({ lat: parseFloat(lat), lng: parseFloat(lng) })
  1717. });
  1718. const data = await resp.json();
  1719. // Show any lookup error in the modal
  1720. if (!resp.ok || !data || data.ok !== true) {
  1721. $('#pb-errors').removeClass('d-none').text((data && data.error) ? data.error : 'Lookup failed');
  1722. bootstrap.Modal.getOrCreateInstance(document.getElementById('planbuildPreview')).show();
  1723. return;
  1724. }
  1725. $('#pb-errors').addClass('d-none').text('');
  1726. // Fill the preview modal
  1727. $('#pb_pid').text(data.pid || '–');
  1728. $('#pb_title').text(data.title_id || '–');
  1729. $('#pb_area').text(formatArea(data.total_area) || '–');
  1730. $('#pb_locality').text(data.locality || '–'); // include if you added locality in PHP later
  1731. //$('#pb_council').text(data.council || '–');
  1732. $('#pb_scheme').text(data.planning_scheme || '–');
  1733. $('#pb_zones').text((Array.isArray(data.planning_zones) ? data.planning_zones.join(', ') : (data.planning_zones || '')) || '–');
  1734. $('#pb_codes').text((Array.isArray(data.planning_codes) ? data.planning_codes.join(', ') : (data.planning_codes || '')) || '–');
  1735. $('#area_sqm').text(data.area_sqm || '–');
  1736. $('#area_ha').text(data.area_ha || '–');
  1737. $('#tenure').text(data.tenure || '–');
  1738. $('#lpi').text(data.lpi || '–');
  1739. $('#list_guid').text(data.list_guid || '–');
  1740. bootstrap.Modal.getOrCreateInstance(document.getElementById('planbuildPreview')).show();
  1741. // Apply button writes to the form and DB
  1742. $('#pb-apply').off('click').on('click', () => {
  1743. const apply = (id, v) => {
  1744. const el = document.getElementById(id);
  1745. if (el && typeof v !== 'undefined' && v !== null) {
  1746. el.value = v;
  1747. storeField(id, v);
  1748. }
  1749. };
  1750. apply('property_id', data.pid || '');
  1751. apply('title_id', data.title_id || '');
  1752. apply('total_area', formatArea(data.total_area) || '');
  1753. apply('planning_scheme', data.planning_scheme || '');
  1754. apply('planning_zones', Array.isArray(data.planning_zones) ? data.planning_zones.join(', ') : (data.planning_zones || ''));
  1755. apply('planning_codes', Array.isArray(data.planning_codes) ? data.planning_codes.join(', ') : (data.planning_codes || ''));
  1756. //apply('council', data.council || '');
  1757. if (document.getElementById('locality')) apply('locality', data.locality || '');
  1758. // Optional extras if you add matching inputs:
  1759. //apply('area_sqm', data.total_area?.sqm_label || '');
  1760. //apply('area_ha', data.total_area?.ha_label || '');
  1761. //apply('tenure', data.tenure || '');
  1762. //apply('lpi', data.lpi || '');
  1763. //apply('list_guid',data.list_guid|| '');
  1764. bootstrap.Modal.getOrCreateInstance(document.getElementById('planbuildPreview')).hide();
  1765. });
  1766. } catch (e) {
  1767. $('#pb-errors').removeClass('d-none').text('Error fetching data: ' + e.message);
  1768. bootstrap.Modal.getOrCreateInstance(document.getElementById('planbuildPreview')).show();
  1769. }
  1770. };
  1771. // Build the exact body text from current form values
  1772. const useDynamicGreeting = false;
  1773. function getGreeting() {
  1774. if (!useDynamicGreeting) return 'Good Morning,';
  1775. const hour = new Date().getHours();
  1776. if (hour < 12) return 'Good Morning,';
  1777. if (hour < 18) return 'Good Afternoon,';
  1778. return 'Good Evening,';
  1779. }
  1780. function escapeHtml(s) {
  1781. return String(s || '').replace(/[&<>"']/g, c => ({
  1782. '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'
  1783. }[c]));
  1784. }
  1785. function buildPlanningEmailText() {
  1786. const greet = getGreeting();
  1787. const address = ($('#site_address').val() || '').trim();
  1788. const owners = ($('#registered_owner').val() || '').trim();
  1789. const pid = ($('#property_id').val() || '').trim();
  1790. const title = ($('#title_id').val() || '').trim();
  1791. const fallback = 'N/A';
  1792. const lines = [
  1793. greet,
  1794. '',
  1795. 'I am requesting the planning and plumbing information for the following address:',
  1796. `Property Address: ${address || fallback}`,
  1797. `Property Owners: ${owners || fallback}`,
  1798. `Property ID: ${pid || fallback}`,
  1799. `Title/Vol: ${title || fallback}`,
  1800. '',
  1801. 'Attached is a signed Letter of Authority from the property owners.'
  1802. ];
  1803. return lines.join('\n');
  1804. }
  1805. function buildPlanningEmailHtml() {
  1806. const greet = getGreeting();
  1807. const address = ($('#site_address').val() || '').trim();
  1808. const owners = ($('#registered_owner').val() || '').trim();
  1809. const pid = ($('#property_id').val() || '').trim();
  1810. const title = ($('#title_id').val() || '').trim();
  1811. const fallback = 'N/A';
  1812. return `
  1813. <div style="background:#ffffff;padding:16px;font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.5;color:#000000;">
  1814. <p style="margin:0 0 12px 0;">${escapeHtml(greet)}</p>
  1815. <p style="margin:0 0 12px 0;">I am requesting the planning and plumbing information for the following address:</p>
  1816. <table role="presentation" cellpadding="0" cellspacing="0" width="75%" style="border-collapse:collapse;background:#ffffff;color:#000000;">
  1817. <tr>
  1818. <td style="padding:8px;border:1px solid #d1d5db;font-weight:bold;width:200px;">Property Address</td>
  1819. <td style="padding:8px;border:1px solid #d1d5db;">${escapeHtml(address || fallback)}</td>
  1820. </tr>
  1821. <tr>
  1822. <td style="padding:8px;border:1px solid #d1d5db;font-weight:bold;">Property Owners</td>
  1823. <td style="padding:8px;border:1px solid #d1d5db;">${escapeHtml(owners || fallback)}</td>
  1824. </tr>
  1825. <tr>
  1826. <td style="padding:8px;border:1px solid #d1d5db;font-weight:bold;">Property ID</td>
  1827. <td style="padding:8px;border:1px solid #d1d5db;">${escapeHtml(pid || fallback)}</td>
  1828. </tr>
  1829. <tr>
  1830. <td style="padding:8px;border:1px solid #d1d5db;font-weight:bold;">Title/Vol</td>
  1831. <td style="padding:8px;border:1px solid #d1d5db;">${escapeHtml(title || fallback)}</td>
  1832. </tr>
  1833. </table>
  1834. <p style="margin:12px 0 0 0;">Attached is a signed Letter of Authority from the property owners.</p>
  1835. </div>`;
  1836. }
  1837. function copyFromTextarea(selector, btnEl) {
  1838. const val = $(selector).val();
  1839. const doWrite = async () => {
  1840. if (navigator.clipboard && navigator.clipboard.writeText) {
  1841. await navigator.clipboard.writeText(val);
  1842. } else {
  1843. const ta = document.querySelector(selector);
  1844. ta.focus();
  1845. ta.select();
  1846. document.execCommand('copy');
  1847. }
  1848. };
  1849. doWrite().then(() => {
  1850. const original = btnEl.textContent;
  1851. btnEl.textContent = 'Copied';
  1852. btnEl.disabled = true;
  1853. setTimeout(() => { btnEl.textContent = original; btnEl.disabled = false; }, 1200);
  1854. }).catch(() => {
  1855. alert('Copy failed. You can select and copy the text manually.');
  1856. });
  1857. }
  1858. // Single modal hook
  1859. document.getElementById('emailTemplateModal')
  1860. .addEventListener('show.bs.modal', function () {
  1861. const text = buildPlanningEmailText();
  1862. const html = buildPlanningEmailHtml();
  1863. document.getElementById('emailText').value = text;
  1864. document.getElementById('emailHtmlPreview').innerHTML = html;
  1865. document.getElementById('emailHtmlSource').value = html;
  1866. // Build subject using the current site address
  1867. const addr = (document.getElementById('site_address')?.value || '').trim() || 'N/A';
  1868. const subject = encodeURIComponent(`Request for Property Information - ${addr}`);
  1869. const body = encodeURIComponent(text);
  1870. document.getElementById('openMailto').href = `mailto:?subject=${subject}&body=${body}`;
  1871. });
  1872. // Single copy handlers
  1873. $('#copyEmailText').on('click', function () {
  1874. copyFromTextarea('#emailText', this);
  1875. });
  1876. $('#copyEmailHtml').on('click', function () {
  1877. copyFromTextarea('#emailHtmlSource', this);
  1878. });
  1879. </script>
  1880. <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>
  1881. <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB-QceOYrDe9otynMmQ9iNF3yEZzbpsanM&libraries=places&loading=async&callback=initAutocomplete" ></script>
  1882. <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
  1883. <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
  1884. </body>
  1885. </html>