<?php
declare(strict_types=1);
use setasign\Fpdi\Fpdi;
/**
 * @return string|null Absolute path to the generated Dorset PDF, or null on failure
 */

function generate_dorset_application(string $job, array $vars, array $cfg, string $templatePath, string $outPath): ?string {
    if (!is_file($templatePath)) return null;

	// Property Details
    $addr        = $vars['property']['address'] ?? '';
    $title 		 = 'Title: ' . ($vars['property']['title'] ?? '') . '  PID: '  . ($vars['property']['pid'] ?? '');
    // Owner
	$ownerName   = $vars['client']['name'] ?? '';
    $ownerEmail  = $vars['client']['email'] ?? '';
    $ownerPhone  = $vars['client']['phone'] ?? '';
    $ownerAddr   = $vars['client']['address'] ?? '';
	$sigOwnerPng = __DIR__ . "/loa/{$job}/{$job}_signature.png";

	// Applicant (your business)
    $appName     = ($cfg['dev_name'] ?? '') . ' - ' . ($cfg['dev_company'] ?? '') ?? 'Benjamin Harris - Modulos Design';
	$appEmail    = $cfg['dev_email']   ?? 'drafting@modulosdesign.com.au';
	$appPhone    = $cfg['dev_phone']   ?? '0402 984 082';
	$appAddress  = $cfg['dev_address'] ?? '34 Coplestone St, Scottsdale, Tas 7260';
	$sigAppPng 	 = __DIR__ . "/applicant_signature.png";
	
	
    $today       = date('d/m/Y');

    $pdf = new Fpdi();
    $pdf->AddPage();
    $pdf->setSourceFile($templatePath);
    $tpl = $pdf->importPage(1);
    $pdf->useTemplate($tpl, 0, 0, 210); // A4 width in mm

    $pdf->SetFont('Helvetica','',11);

    // helpers
    $T = function($x,$y,$t) use($pdf){ $pdf->SetXY($x,$y); $pdf->Cell(0,5,(string)$t,0,0); };
	$MB = function($x,$y,$w,$t) use($pdf){ $pdf->SetFont('Helvetica','B',12); $pdf->SetXY($x,$y); $pdf->MultiCell($w,5,(string)$t,0,'L'); $pdf->SetFont('Helvetica','',11); };

    $X = function($x,$y)    use($pdf){ $pdf->Text($x,$y,'X'); };

    // --- Map to fields (adjust if your copy’s baseline differs) ---
    $MB(58, 133, 122, $addr);          // Full Address 45,  95
    $MB(58, 140, 122, $title);         // PID/Title 55, 103

    // Applicant (your business)
    $T(58, 159, $appName);
    $T(58, 167, $appAddress);
    $T(70, 174, $appPhone);
    $T(128,174, $appEmail);
	if (is_file($sigAppPng)) $pdf->Image($sigAppPng, 60, 179, 30); // Signature of Owner
    $T(128, 182, $today);         // Date

    // Owner Authorisation
    $T(58, 203, $ownerName);
    $T(58, 210, $ownerAddr);
    $T(70, 217, $ownerPhone);
    $T(128, 217, $ownerEmail);
    if (is_file($sigOwnerPng)) $pdf->Image($sigOwnerPng, 60, 220, 50); // Signature of Owner
    $T(128, 226, $today);

    // Information Requested – default ticks (tweak to taste / make UI later)
    $X(107,  95);   // Planning Permit & Associated Docs
    $X(185,  95);   // Occupancy & Completion Certificates
    $X(107,  102);   // Building Plans…
    $X(185, 102);   // Building/Plumbing Notices & Orders
    $X(107,  109);  // Plumbing Plans…

    $pdf->Output('F', $outPath);
    return is_file($outPath) ? $outPath : null;
}
