client-brief.php 111 KB

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