<?php
ob_start();
header('Content-Type: text/html; charset=utf-8');

if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) {
    @session_start();
}

require_once __DIR__ . '/db_connect.php';
require_once __DIR__ . '/includes/ProxyHelper.php';

$officeId = $_POST['officeId'] ?? ($_GET['officeId'] ?? ($_POST['office_id'] ?? ($_GET['office_id'] ?? null)));
$officeId = is_string($officeId) ? trim($officeId) : (is_numeric($officeId) ? (string)$officeId : '');
if ($officeId === '' && !empty($_SESSION['office_id'])) {
    $officeId = (string)$_SESSION['office_id'];
}
if ($officeId !== '') {
    $_SESSION['office_id'] = $officeId;
}

$normalizeUbrn = function($value) {
    return preg_replace('/\\D+/', '', (string)$value);
};

$normalizeDateDMY = function($value) {
    $v0 = trim((string)$value);
    if ($v0 === '') return '';
    if (preg_match('/[A-Za-z]/', $v0)) {
        $ts = strtotime($v0);
        if ($ts !== false) {
            return date('d/m/Y', (int)$ts);
        }
    }
    $v = $v0;
    if ($v === '') return '';
    $v = preg_replace('/\\s+/', '', $v);
    $v = str_replace(['.', '\\\\'], ['/', '/'], $v);
    if (preg_match('/^(\\d{4})[-\\/](\\d{1,2})[-\\/](\\d{1,2})$/', $v, $m)) {
        return sprintf('%02d/%02d/%04d', (int)$m[3], (int)$m[2], (int)$m[1]);
    }
    if (preg_match('/^(\\d{1,2})[-\\/](\\d{1,2})[-\\/](\\d{4})$/', $v, $m)) {
        return sprintf('%02d/%02d/%04d', (int)$m[1], (int)$m[2], (int)$m[3]);
    }
    if (preg_match('/^(\\d{2})(\\d{2})(\\d{4})$/', $v, $m)) {
        return $m[1] . '/' . $m[2] . '/' . $m[3];
    }
    if (preg_match('/^(\\d{2})\\/(\\d{2})\\/(\\d{4})$/', $v)) {
        return $v;
    }
    return $v;
};

$formatOfficeAddressEn = function($address) {
    $s = trim((string)$address);
    if ($s === '') return '';
    $s = preg_replace('/\s+/', ' ', $s);
    $parts = preg_split('/,/', $s);
    $clean = [];
    foreach ($parts as $p) {
        $t = trim((string)$p);
        $t = rtrim($t, " \t\n\r\0\x0B");
        if ($t === '') continue;
        if (preg_match('/\bbangladesh\b/i', $t)) continue;
        if (preg_match('/\bdivision\b/i', $t)) continue;
        $clean[] = ucwords(strtolower($t));
    }
    $n = count($clean);
    if ($n > 2) {
        $clean = array_slice($clean, -2);
    }
    $out = implode(', ', $clean);
    if ($out !== '' && !str_ends_with($out, '.')) $out .= '.';
    return $out;
};

$dmyToYmd = function($dmy) {
    $dmy = trim((string)$dmy);
    if ($dmy === '') return '';
    if (preg_match('/^(\\d{2})\\/(\\d{2})\\/(\\d{4})$/', $dmy, $m)) {
        return $m[3] . '-' . $m[2] . '-' . $m[1];
    }
    return '';
};

function filterBirthPlace($address) {
    $address = trim((string)$address);
    if ($address === '') return '';
    $parts = array_values(array_filter(array_map('trim', explode(',', $address)), function($p){ return $p !== ''; }));
    $count = count($parts);
    if ($count >= 2) {
        return $parts[$count - 2] . ', ' . $parts[$count - 1];
    }
    return $address;
}

$formatBirthPlaceEn = function($address) {
    $s = trim((string)$address);
    if ($s === '') return '';
    $parts = array_values(array_filter(array_map('trim', explode(',', $s)), function($p){ return $p !== ''; }));
    $count = count($parts);
    if ($count >= 2) {
        $parts = [$parts[$count - 2], $parts[$count - 1]];
    }
    $clean = [];
    foreach ($parts as $p) {
        $t = preg_replace('/\s+/', ' ', trim((string)$p));
        if ($t === '') continue;
        if (preg_match('/\bbangladesh\b/i', $t)) {
            $clean[] = 'Bangladesh';
            continue;
        }
        $clean[] = ucwords(strtolower($t));
    }
    return implode(', ', $clean);
};

function dateToWords($dmy) {
    $dmy = trim((string)$dmy);
    if ($dmy === '') return '';
    $parts = explode('/', $dmy);
    if (count($parts) !== 3) return $dmy;

    $d = (int)$parts[0]; $m = (int)$parts[1]; $y = (int)$parts[2];
    $months = [1=>'January',2=>'February',3=>'March',4=>'April',5=>'May',6=>'June',7=>'July',8=>'August',9=>'September',10=>'October',11=>'November',12=>'December'];
    $ordinal = ["", "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelfth", "Thirteenth", "Fourteenth", "Fifteenth", "Sixteenth", "Seventeenth", "Eighteenth", "Nineteenth", "Twentieth", "Twenty First", "Twenty Second", "Twenty Third", "Twenty Fourth", "Twenty Fifth", "Twenty Sixth", "Twenty Seventh", "Twenty Eighth", "Twenty Ninth", "Thirtieth", "Thirty First"];
    $ones = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
    $tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];

    $yearWord = "";
    if ($y < 2000) {
        $p1 = (int)substr((string)$y, 0, 2); $p2 = (int)substr((string)$y, 2, 2);
        $yearWord = $ones[$p1] . " Hundred" . ($p2 > 0 ? " " . ($p2 < 20 ? $ones[$p2] : $tens[(int)substr((string)$p2,0,1)]." ".$ones[(int)substr((string)$p2,1,1)]) : "");
    } else {
        $rest = $y - 2000;
        $yearWord = "Two Thousand" . ($rest > 0 ? " " . ($rest < 20 ? $ones[$rest] : $tens[(int)substr((string)$rest,0,1)]." ".$ones[(int)substr((string)$rest,1,1)]) : "");
    }
    return ($ordinal[$d] ?? (string)$d) . " of " . ($months[$m] ?? '') . " " . $yearWord;
}

$pick = function($arr, $key, $default = null) {
    if (!is_array($arr)) return $default;
    if (!array_key_exists($key, $arr) || $arr[$key] === null) return $default;
    return $arr[$key];
};

$firstNonEmpty = function($arr, $keys, $default = null) use ($pick) {
    if (!is_array($keys)) return $default;
    foreach ($keys as $k) {
        $v = $pick($arr, $k, null);
        if ($v !== null && $v !== '') return $v;
    }
    return $default;
};

$findKeyRecursive = function($arr, $keys) use (&$findKeyRecursive, $firstNonEmpty) {
    if (!is_array($arr)) return null;
    $direct = $firstNonEmpty($arr, $keys, null);
    if ($direct !== null && $direct !== '') return $direct;
    foreach ($arr as $v) {
        if (is_array($v)) {
            $found = $findKeyRecursive($v, $keys);
            if ($found !== null && $found !== '') return $found;
        }
    }
    return null;
};

$extractCertificateData = function($raw) use ($firstNonEmpty, $findKeyRecursive) {
    if (!is_array($raw)) return [];
    $root = is_array($raw['data'] ?? null) ? $raw['data'] : $raw;
    $person = is_array($root['personMaster'] ?? null) ? $root['personMaster'] : $root;
    $person = is_array($person['data'] ?? null) ? $person['data'] : $person;

    $get = function($keys, $default = '') use ($firstNonEmpty, $findKeyRecursive, $person, $root, $raw) {
        $v = $firstNonEmpty($person, $keys, null);
        if ($v !== null && $v !== '') return $v;
        $v = $firstNonEmpty($root, $keys, null);
        if ($v !== null && $v !== '') return $v;
        $v = $firstNonEmpty($raw, $keys, null);
        if ($v !== null && $v !== '') return $v;
        $v = $findKeyRecursive($raw, $keys);
        if ($v !== null && $v !== '') return $v;
        return $default;
    };

    return [
        'ubrn' => (string)$get(['ubrn','brn','birthRegistrationNumber','registrationNumber','registrationNo','personBrn'], ''),
        'personBirthDate' => (string)$get(['personBirthDate','dateOfBirth','dob','birthDate','personBirthDateString'], ''),
        'gender' => (string)$get(['gender','personSex','sex','personGender'], ''),
        'dateOfRegistration' => (string)$get(['dateOfRegistration','registrationDate','regDate','reg_date'], ''),
        'issueDate' => (string)$get(['issueDate','dateOfIssue','dateOfIssuance','issuanceDate','issue_date'], ''),
        'personNameBn' => (string)$get(['personNameBn','nameBn','nameBangla','personNameBangla','name'], ''),
        'personNameEn' => (string)$get(['personNameEn','nameEn','nameEnglish','personNameEnglish'], ''),
        'fatherNameBn' => (string)$get(['fatherNameBn','fatherNameBangla','fatherName','fnameBn'], ''),
        'fatherNameEn' => (string)$get(['fatherNameEn','fatherNameEnglish','fnameEn'], ''),
        'fatherNationalityBn' => (string)$get(['fatherNationalityBn','fatherNationality','fatherNationalityBangla','fNationBn'], ''),
        'fatherNationalityEn' => (string)$get(['fatherNationalityEn','fatherNationalityEnglish','fNationEn'], ''),
        'motherNameBn' => (string)$get(['motherNameBn','motherNameBangla','motherName','mNameBn'], ''),
        'motherNameEn' => (string)$get(['motherNameEn','motherNameEnglish','mNameEn'], ''),
        'motherNationalityBn' => (string)$get(['motherNationalityBn','motherNationality','motherNationalityBangla','mNationBn'], ''),
        'motherNationalityEn' => (string)$get(['motherNationalityEn','motherNationalityEnglish','mNationEn'], ''),
        'birthPlaceBn' => (string)$get(['fullBirthPlaceBn','placeOfBirthBn','birthPlaceBn','birthPlace','placeOfBirth','birthPlaceBangla','placeOfBirthAddress'], ''),
        'birthPlaceEn' => (string)$get(['fullBirthPlaceEn','placeOfBirthEn','birthPlaceEn','birthPlaceEnglish','placeOfBirthEnglish','placeOfBirthAddress'], ''),
        'permAddrBn' => (string)$get(['fullPermAddrBn','fullPrsntAddrBn','permanentAddressBn','permAddrBn','permAddr','permanentAddress','permanentAddressBangla','presentAddress'], ''),
        'permAddrEn' => (string)$get(['fullPermAddrEn','fullPrsntAddrEn','permanentAddressEn','permAddrEn','permanentAddressEnglish','permanentAddress','presentAddress'], ''),
        'officeNameBn' => (string)$get(['registrationOfficeNameBn','registrationOfficeName','officeNameBn','officeName','officeNameBangla','registrationOfficeBn','registrationOffice','registerOffice','registerOfficeLocation'], ''),
        'officeNameEn' => (string)$get(['registrationOfficeNameEn','registrationOfficeEn','officeNameEn','officeNameEnglish','registrationOffice','registerOfficeLocationEn'], ''),
        'officeAddressBn' => (string)$get(['officeAddressBn','registrationOfficeAddressBn','fullRegistrationOfficeAddressBn','birthDistrictNameBn','birthDistrictBn','districtNameBn','districtBn','registerOfficeAddress','registerAddress'], ''),
        'officeAddressEn' => (string)$get(['officeAddressEn','registrationOfficeAddressEn','fullRegistrationOfficeAddressEn','birthDistrictNameEn','birthDistrictEn','districtNameEn','districtEn','registerOfficeAddress','registerAddress'], ''),
        'qr_code' => (string)$get(['QR_Code','qr_code','qrCode','qrUrl','qrURL'], ''),
        'qr_text' => (string)$get(['qr_text','qrText','qrCodeText','Bar_Code','bar_code','barcode'], ''),
    ];
};

$proxy = new ProxyHelper();
$hasSessionCookies = false;
try {
    if (method_exists($proxy, 'getCookies')) {
        $c = trim((string)$proxy->getCookies());
        if ($c !== '') $hasSessionCookies = true;
    }
} catch (Throwable) {
}

$ensureCacheTable = function() use (&$pdo) {
    try {
        if (isset($pdo) && $pdo instanceof PDO) {
            $pdo->exec("CREATE TABLE IF NOT EXISTS certificate_cache (
                ubrn VARCHAR(32) PRIMARY KEY,
                person_birth_date VARCHAR(32) NULL,
                office_id VARCHAR(64) NULL,
                payload_json MEDIUMTEXT NOT NULL,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            )");
        }
    } catch (Throwable) {
    }
};

$saveCache = function($ubrn, $dob, $officeId, $payload) use (&$pdo, $ensureCacheTable) {
    $u = preg_replace('/\\D+/', '', (string)$ubrn);
    if ($u === '' || !is_array($payload)) return;
    $json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if (!is_string($json) || $json === '') return;
    try {
        if (isset($pdo) && $pdo instanceof PDO) {
            $ensureCacheTable();
            $stmt = $pdo->prepare("INSERT INTO certificate_cache (ubrn, person_birth_date, office_id, payload_json)
                VALUES (?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE person_birth_date = VALUES(person_birth_date), office_id = VALUES(office_id), payload_json = VALUES(payload_json)");
            $stmt->execute([$u, $dob !== '' ? $dob : null, $officeId !== '' ? $officeId : null, $json]);
            return;
        }
    } catch (Throwable) {
    }

    $dir = __DIR__ . '/cache/certificates';
    if (!is_dir($dir)) {
        @mkdir($dir, 0777, true);
    }
    $safeOffice = preg_replace('/[^a-zA-Z0-9_\\-]/', '', (string)$officeId);
    if ($safeOffice === '') $safeOffice = 'public';
    $path = $dir . '/' . $safeOffice . '_' . $u . '.json';
    @file_put_contents($path, $json);
};

$loadRecentCache = function($officeId, $limit = 20) use (&$pdo, $ensureCacheTable) {
    $rows = [];
    try {
        if (isset($pdo) && $pdo instanceof PDO) {
            $ensureCacheTable();
            if ($officeId !== '') {
                $stmt = $pdo->prepare("SELECT ubrn, person_birth_date, updated_at FROM certificate_cache WHERE office_id = ? ORDER BY updated_at DESC LIMIT " . (int)$limit);
                $stmt->execute([$officeId]);
            } else {
                $stmt = $pdo->query("SELECT ubrn, person_birth_date, updated_at FROM certificate_cache ORDER BY updated_at DESC LIMIT " . (int)$limit);
            }
            $rows = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
            return is_array($rows) ? $rows : [];
        }
    } catch (Throwable) {
    }

    $dir = __DIR__ . '/cache/certificates';
    if (!is_dir($dir)) return [];
    $safeOffice = preg_replace('/[^a-zA-Z0-9_\\-]/', '', (string)$officeId);
    if ($safeOffice === '') $safeOffice = 'public';

    $files = glob($dir . '/' . $safeOffice . '_*.json') ?: [];
    usort($files, function($a, $b) {
        return (filemtime($b) ?: 0) <=> (filemtime($a) ?: 0);
    });
    $files = array_slice($files, 0, (int)$limit);

    $out = [];
    foreach ($files as $f) {
        $base = basename((string)$f);
        if (!preg_match('/^' . preg_quote($safeOffice, '/') . '_(\\d+)\\.json$/', $base, $m)) continue;
        $u = (string)$m[1];
        $t = filemtime((string)$f);
        $payload = @file_get_contents((string)$f);
        $decoded = is_string($payload) ? json_decode($payload, true) : null;
        $dob = '';
        if (is_array($decoded)) {
            $dob = (string)($decoded['personBirthDate'] ?? ($decoded['person_birth_date'] ?? ''));
        }
        $out[] = [
            'ubrn' => $u,
            'person_birth_date' => $dob,
            'updated_at' => $t ? date('Y-m-d H:i:s', (int)$t) : '',
        ];
    }
    return $out;
};

$fetchPublicRaw = function($ubrn) use ($proxy) {
    $u = preg_replace('/\\D+/', '', (string)$ubrn);
    if ($u === '') return null;

    $try = [
        ['https://everify.bdris.gov.bd/api/br/info/ubrn/' . urlencode($u), 'https://everify.bdris.gov.bd/'],
        ['https://bdris.gov.bd/api/br/info/ubrn/' . urlencode($u), 'https://bdris.gov.bd/'],
        ['https://everify.bdris.gov.bd/api/br/register/search/by-ubrn?ubrn=' . urlencode($u), 'https://everify.bdris.gov.bd/'],
        ['https://bdris.gov.bd/api/br/register/search/by-ubrn?ubrn=' . urlencode($u), 'https://bdris.gov.bd/'],
    ];

    foreach ($try as [$url, $ref]) {
        $resp = $proxy->fetch($url, 'GET', [], false, $ref, [], 18, 1, 200);
        if (($resp['status'] ?? 0) !== 200) continue;
        $parsed = null;
        if (method_exists($proxy, 'parseJson')) {
            $parsed = $proxy->parseJson($resp);
        } else {
            $parsed = json_decode((string)($resp['body'] ?? ''), true);
        }
        if (is_array($parsed) && !isset($parsed['EXCEPTION'])) return $parsed;
    }

    return null;
};

$fetchCaptchaVerifyRaw = function($ubrn, $dobDmy) use ($proxy, $dmyToYmd) {
    $u = preg_replace('/\\D+/', '', (string)$ubrn);
    if ($u === '') return null;
    $dobYmd = $dmyToYmd($dobDmy);
    if ($dobYmd === '') return null;
    $url = 'https://captcha.my-api.top/api/verify';
    $resp = $proxy->fetch($url, 'POST', ['ubrn' => $u, 'dob' => $dobYmd], true, 'https://captcha.my-api.top/', [], 20, 1, 200);
    if (($resp['status'] ?? 0) !== 200) return null;
    $parsed = null;
    if (method_exists($proxy, 'parseJson')) {
        $parsed = $proxy->parseJson($resp);
    } else {
        $parsed = json_decode((string)($resp['body'] ?? ''), true);
    }
    if (is_array($parsed) && (($parsed['success'] ?? false) === true) && isset($parsed['data']) && is_array($parsed['data'])) {
        return $parsed;
    }
    return is_array($parsed) ? $parsed : null;
};

$fetchSessionFullRaw = function($ubrn, $dobDmy) use ($proxy) {
    $u = preg_replace('/\\D+/', '', (string)$ubrn);
    $d = trim((string)$dobDmy);
    if ($u === '' || $d === '') return null;
    $url = 'https://bdris.gov.bd/api/br/user-search-by-ubrn-and-dob';
    $resp = $proxy->fetch($url, 'GET', ['ubrn' => $u, 'personBirthDate' => $d], false, 'https://bdris.gov.bd/admin/br/applications/search', [], 20, 1, 200);
    if (($resp['status'] ?? 0) !== 200) return null;
    $parsed = null;
    if (method_exists($proxy, 'parseJson')) {
        $parsed = $proxy->parseJson($resp);
    } else {
        $parsed = json_decode((string)($resp['body'] ?? ''), true);
    }
    if (is_array($parsed) && isset($parsed['data']) && is_array($parsed['data'])) return $parsed;
    return is_array($parsed) ? $parsed : null;
};

$loadDobFromCacheByUbrn = function($ubrn, $officeId) use (&$pdo, $ensureCacheTable) {
    $u = preg_replace('/\\D+/', '', (string)$ubrn);
    if ($u === '') return '';
    try {
        if (isset($pdo) && $pdo instanceof PDO) {
            $ensureCacheTable();
            $stmt = $pdo->prepare("SELECT person_birth_date FROM certificate_cache WHERE ubrn = ? LIMIT 1");
            $stmt->execute([$u]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if (is_array($row) && !empty($row['person_birth_date'])) return (string)$row['person_birth_date'];
        }
    } catch (Throwable) {
    }
    $dir = __DIR__ . '/cache/certificates';
    if (!is_dir($dir)) return '';
    $safeOffice = preg_replace('/[^a-zA-Z0-9_\\-]/', '', (string)$officeId);
    if ($safeOffice === '') $safeOffice = 'public';
    $paths = glob($dir . '/' . $safeOffice . '_' . $u . '.json') ?: [];
    foreach ($paths as $p) {
        $raw = @file_get_contents((string)$p);
        $decoded = is_string($raw) ? json_decode($raw, true) : null;
        if (is_array($decoded)) {
            $dob = (string)($decoded['personBirthDate'] ?? ($decoded['person_birth_date'] ?? ''));
            if ($dob !== '') return $dob;
        }
    }
    return '';
};

$loadPayloadFromCacheByUbrn = function($ubrn, $officeId) use (&$pdo, $ensureCacheTable) {
    $u = preg_replace('/\\D+/', '', (string)$ubrn);
    if ($u === '') return [];
    try {
        if (isset($pdo) && $pdo instanceof PDO) {
            $ensureCacheTable();
            $stmt = $pdo->prepare("SELECT payload_json FROM certificate_cache WHERE ubrn = ? LIMIT 1");
            $stmt->execute([$u]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if (is_array($row) && !empty($row['payload_json'])) {
                $decoded = json_decode((string)$row['payload_json'], true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) return $decoded;
            }
        }
    } catch (Throwable) {
    }

    $dir = __DIR__ . '/cache/certificates';
    if (!is_dir($dir)) return [];
    $safeOffice = preg_replace('/[^a-zA-Z0-9_\\-]/', '', (string)$officeId);
    if ($safeOffice === '') $safeOffice = 'public';

    $candidates = [];
    foreach (glob($dir . '/' . $safeOffice . '_' . $u . '.json') ?: [] as $p) {
        $candidates[] = (string)$p;
    }
    foreach (glob($dir . '/public_' . $u . '.json') ?: [] as $p) {
        $candidates[] = (string)$p;
    }
    foreach (glob($dir . '/*_' . $u . '.json') ?: [] as $p) {
        $candidates[] = (string)$p;
    }
    $candidates = array_values(array_unique(array_filter($candidates, 'is_file')));
    usort($candidates, function($a, $b) {
        return (filemtime((string)$b) ?: 0) <=> (filemtime((string)$a) ?: 0);
    });

    foreach ($candidates as $p) {
        $raw = @file_get_contents((string)$p);
        $decoded = is_string($raw) ? json_decode($raw, true) : null;
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) return $decoded;
    }
    return [];
};

$action = $_POST['action'] ?? ($_GET['action'] ?? '');
$mode = strtolower(trim((string)($_POST['mode'] ?? ($_GET['mode'] ?? ''))));
$mode = ($mode === 'public' || $mode === 'main') ? $mode : '';
$ubrnInput = $_POST['birth_reg_no'] ?? ($_POST['ubrn'] ?? ($_GET['birth_reg_no'] ?? ($_GET['ubrn'] ?? '')));
$dobInput = $_POST['dob'] ?? ($_GET['dob'] ?? '');

$ubrn = $normalizeUbrn($ubrnInput);
$dob = $normalizeDateDMY($dobInput);

$error = null;
$formData = [];
$step = 'search';
$dobRequired = (!$hasSessionCookies && $officeId === '');

$buildFormDataFromRaw = function($raw, $ubrn, $dob) use ($extractCertificateData, $normalizeDateDMY, $formatBirthPlaceEn) {
    $data = $extractCertificateData($raw);
    $fd = $data;
    $fd['ubrn'] = $ubrn !== '' ? $ubrn : (string)($data['ubrn'] ?? '');

    $dobFromData = $normalizeDateDMY($data['personBirthDate'] ?? '');
    if ($dobFromData === '' && $dob !== '') $dobFromData = $dob;
    $fd['personBirthDate'] = $dobFromData;

    $fd['dateOfRegistration'] = $normalizeDateDMY($data['dateOfRegistration'] ?? '');
    $fd['issueDate'] = $normalizeDateDMY($data['issueDate'] ?? '');
    if ($fd['issueDate'] === '' && $fd['dateOfRegistration'] !== '') {
        $fd['issueDate'] = $fd['dateOfRegistration'];
    }

    $sexRaw = strtoupper(trim((string)($data['gender'] ?? '')));
    $sex = ($sexRaw === 'MALE' || $sexRaw === 'M') ? 'Male' : (($sexRaw === 'FEMALE' || $sexRaw === 'F') ? 'Female' : '');
    $fd['gender'] = $sex !== '' ? $sex : (string)($data['gender'] ?? '');

    $bpBn = filterBirthPlace((string)($fd['birthPlaceBn'] ?? ''));
    if ($bpBn !== '' && !preg_match('/বাংলাদেশ/u', $bpBn)) {
        $bpBn .= ', বাংলাদেশ';
    }
    $bpEn = $formatBirthPlaceEn((string)($fd['birthPlaceEn'] ?? ''));
    if ($bpEn !== '' && !preg_match('/\bbangladesh\b/i', $bpEn)) {
        $bpEn .= ', Bangladesh';
    }
    $fd['birthPlaceBn'] = $bpBn;
    $fd['birthPlaceEn'] = $bpEn;

    $nameBn = trim((string)($fd['personNameBn'] ?? ''));
    $nameEn = trim((string)($fd['personNameEn'] ?? ''));
    if ($nameBn === '' && $nameEn !== '') $fd['personNameBn'] = $nameEn;
    if ($nameEn === '' && $nameBn !== '') $fd['personNameEn'] = $nameBn;

    $officeBn = trim((string)($fd['officeNameBn'] ?? ''));
    $officeEn = trim((string)($fd['officeNameEn'] ?? ''));
    if ($officeBn === '' && $officeEn !== '') $fd['officeNameBn'] = $officeEn;
    if ($officeEn === '' && $officeBn !== '') $fd['officeNameEn'] = $officeBn;

    $addrBn = trim((string)($fd['officeAddressBn'] ?? ''));
    $addrEn = trim((string)($fd['officeAddressEn'] ?? ''));
    if ($addrBn === '' && $addrEn !== '') $fd['officeAddressBn'] = $addrEn;
    if ($addrEn === '' && $addrBn !== '') $fd['officeAddressEn'] = $addrBn;

    $permBn = trim((string)($fd['permAddrBn'] ?? ''));
    $permEn = trim((string)($fd['permAddrEn'] ?? ''));
    if ($permBn === '' && $bpBn !== '') $permBn = $bpBn;
    if ($permEn === '' && $bpEn !== '') $permEn = $bpEn;
    $fd['permAddrBn'] = $permBn;
    $fd['permAddrEn'] = $permEn;

    foreach ([
        ['fatherNameBn','fatherNameEn'],
        ['motherNameBn','motherNameEn'],
        ['fatherNationalityBn','fatherNationalityEn'],
        ['motherNationalityBn','motherNationalityEn'],
    ] as $pair) {
        $a = (string)$pair[0];
        $b = (string)$pair[1];
        $va = trim((string)($fd[$a] ?? ''));
        $vb = trim((string)($fd[$b] ?? ''));
        if ($va === '' && $vb !== '') $fd[$a] = $vb;
        if ($vb === '' && $va !== '') $fd[$b] = $va;
    }

    if (trim((string)($fd['qr_text'] ?? '')) === '') {
        $fd['qr_text'] = 'IAAT';
    }
    if (trim((string)($fd['qr_code'] ?? '')) === '') {
        $u = (string)($fd['ubrn'] ?? '');
        $fd['qr_code'] = 'https://bdris.gov.bd/certificate/verify?key=' . base64_encode($u);
    }
    return $fd;
};

$buildFormDataFromPost = function($post) use ($normalizeUbrn, $normalizeDateDMY, $formatBirthPlaceEn) {
    $get = function($k, $d = '') use ($post) {
        $v = $post[$k] ?? $d;
        return is_string($v) ? trim($v) : (is_numeric($v) ? (string)$v : $d);
    };
    $u = $normalizeUbrn($get('ubrn', $get('birth_reg_no', '')));
    $dob = $normalizeDateDMY($get('personBirthDate', $get('dob', '')));
    $reg = $normalizeDateDMY($get('dateOfRegistration', ''));
    $iss = $normalizeDateDMY($get('issueDate', ''));
    if ($iss === '' && $reg !== '') $iss = $reg;
    $sexRaw = strtoupper(trim($get('gender', '')));
    $sex = ($sexRaw === 'MALE' || $sexRaw === 'M') ? 'Male' : (($sexRaw === 'FEMALE' || $sexRaw === 'F') ? 'Female' : $get('gender', ''));

    $qrText = $get('qr_text', 'IAAT');
    $qrCode = $get('qr_code', '');
    if ($qrCode === '' && $u !== '') {
        $qrCode = 'https://bdris.gov.bd/certificate/verify?key=' . base64_encode($u);
    }

    return [
        'ubrn' => $u,
        'personBirthDate' => $dob,
        'gender' => $sex,
        'dateOfRegistration' => $reg,
        'issueDate' => $iss,
        'personNameBn' => $get('personNameBn', ''),
        'personNameEn' => $get('personNameEn', ''),
        'fatherNameBn' => $get('fatherNameBn', ''),
        'fatherNameEn' => $get('fatherNameEn', ''),
        'fatherNationalityBn' => $get('fatherNationalityBn', ''),
        'fatherNationalityEn' => $get('fatherNationalityEn', ''),
        'motherNameBn' => $get('motherNameBn', ''),
        'motherNameEn' => $get('motherNameEn', ''),
        'motherNationalityBn' => $get('motherNationalityBn', ''),
        'motherNationalityEn' => $get('motherNationalityEn', ''),
        'birthPlaceBn' => (function($v){
            $bp = filterBirthPlace((string)$v);
            if ($bp !== '' && !preg_match('/বাংলাদেশ/u', $bp)) $bp .= ', বাংলাদেশ';
            return $bp;
        })($get('birthPlaceBn', '')),
        'birthPlaceEn' => (function($v) use ($formatBirthPlaceEn){
            $bp = $formatBirthPlaceEn((string)$v);
            if ($bp !== '' && !preg_match('/\bbangladesh\b/i', $bp)) $bp .= ', Bangladesh';
            return $bp;
        })($get('birthPlaceEn', '')),
        'permAddrBn' => $get('permAddrBn', ''),
        'permAddrEn' => $get('permAddrEn', ''),
        'officeNameBn' => $get('officeNameBn', ''),
        'officeNameEn' => $get('officeNameEn', ''),
        'officeAddressBn' => $get('officeAddressBn', ''),
        'officeAddressEn' => $get('officeAddressEn', ''),
        'qr_code' => $qrCode,
        'qr_text' => $qrText,
    ];
};

if ($action === 'fetch') {
    if ($ubrn === '') {
        $error = 'নিবন্ধন নম্বর দিন।';
    } else {
        $cachedPayload = $loadPayloadFromCacheByUbrn($ubrn, $officeId);
        if ($mode === 'public') {
            if ($dob === '') {
                $error = 'জন্ম তারিখ দিন (DD/MM/YYYY)।';
            } else {
                $raw = $fetchCaptchaVerifyRaw($ubrn, $dob);
                if (!is_array($raw)) {
                    $raw = $fetchPublicRaw($ubrn);
                }
                if (!is_array($raw) && !empty($cachedPayload)) {
                    $raw = $cachedPayload;
                }
                if (!is_array($raw)) {
                    $error = 'পাবলিক সার্ভার থেকে তথ্য পাওয়া যায়নি।';
                } else {
                    $wrap = ['raw' => $raw, 'cache' => $cachedPayload];
                    $formData = $buildFormDataFromRaw($wrap, $ubrn, $dob);
                    $saveCache($formData['ubrn'] ?? '', $formData['personBirthDate'] ?? '', $officeId, $formData);
                    $step = 'edit';
                }
            }
        } else {
            if (!$hasSessionCookies && $officeId === '') {
                $error = 'মেইন সেশন পাওয়া যায়নি। পাবলিক সার্চে জন্ম তারিখ দিয়ে চেষ্টা করুন।';
            } else {
                $rawBase = $fetchPublicRaw($ubrn);
                if (!is_array($rawBase) && !empty($cachedPayload)) {
                    $rawBase = $cachedPayload;
                }
                if (!is_array($rawBase)) {
                    $error = 'মেইন সার্ভার থেকে তথ্য পাওয়া যায়নি।';
                } else {
                    $tmp = $buildFormDataFromRaw(['raw' => $rawBase, 'cache' => $cachedPayload], $ubrn, $dob);
                    $dobResolved = trim((string)($tmp['personBirthDate'] ?? ''));
                    if ($dobResolved === '') {
                        $dobResolved = $loadDobFromCacheByUbrn($ubrn, $officeId);
                    }
                    $raw = $rawBase;
                    if ($dobResolved !== '') {
                        $full = $fetchSessionFullRaw($ubrn, $dobResolved);
                        if (is_array($full) && isset($full['data']) && is_array($full['data']) && !empty($full['data'][0]) && is_array($full['data'][0])) {
                            $raw = ['data' => $full['data'][0], 'base' => $rawBase];
                        }
                    }
                    $formData = $buildFormDataFromRaw(['raw' => $raw, 'cache' => $cachedPayload], $ubrn, $dobResolved);
                    $saveCache($formData['ubrn'] ?? '', $formData['personBirthDate'] ?? '', $officeId, $formData);
                    $step = 'edit';
                }
            }
        }
    }
} elseif ($action === 'print') {
    $hasPostedFields = ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['personNameBn']) || isset($_POST['personNameEn']) || isset($_POST['officeNameBn']) || isset($_POST['permAddrBn'])));
    if ($hasPostedFields) {
        $formData = $buildFormDataFromPost($_POST);
        if (($formData['ubrn'] ?? '') === '') {
            $error = 'নিবন্ধন নম্বর দিন।';
            $step = 'search';
        } elseif ($dobRequired && trim((string)($formData['personBirthDate'] ?? '')) === '') {
            $error = 'জন্ম তারিখ দিন (DD/MM/YYYY)।';
            $step = 'edit';
        } else {
            if (trim((string)($formData['qr_text'] ?? '')) === '') $formData['qr_text'] = 'IAAT';
            if (trim((string)($formData['qr_code'] ?? '')) === '' && trim((string)($formData['ubrn'] ?? '')) !== '') {
                $u = (string)$formData['ubrn'];
                $formData['qr_code'] = 'https://bdris.gov.bd/certificate/verify?key=' . base64_encode($u);
            }
            $saveCache($formData['ubrn'] ?? '', $formData['personBirthDate'] ?? '', $officeId, $formData);
            $step = 'print';
        }
    } else {
        if ($ubrn === '') {
            $error = 'নিবন্ধন নম্বর দিন।';
            $step = 'search';
        } else {
            $cachedPayload = $loadPayloadFromCacheByUbrn($ubrn, $officeId);
            if ($mode === 'public') {
                if ($dob === '') {
                    $error = 'জন্ম তারিখ দিন (DD/MM/YYYY)।';
                    $step = 'search';
                } else {
                    $raw = $fetchCaptchaVerifyRaw($ubrn, $dob);
                    if (!is_array($raw)) {
                        $raw = $fetchPublicRaw($ubrn);
                    }
                    if (!is_array($raw) && !empty($cachedPayload)) {
                        $raw = $cachedPayload;
                    }
                    if (!is_array($raw)) {
                        $error = 'পাবলিক সার্ভার থেকে তথ্য পাওয়া যায়নি।';
                        $step = 'search';
                    } else {
                        $wrap = ['raw' => $raw, 'cache' => $cachedPayload];
                        $formData = $buildFormDataFromRaw($wrap, $ubrn, $dob);
                        $saveCache($formData['ubrn'] ?? '', $formData['personBirthDate'] ?? '', $officeId, $formData);
                        $step = 'print';
                    }
                }
            } else {
                if (!$hasSessionCookies && $officeId === '') {
                    $error = 'মেইন সেশন পাওয়া যায়নি। পাবলিক সার্চে জন্ম তারিখ দিয়ে চেষ্টা করুন।';
                    $step = 'search';
                } else {
                    $rawBase = $fetchPublicRaw($ubrn);
                    if (!is_array($rawBase) && !empty($cachedPayload)) {
                        $rawBase = $cachedPayload;
                    }
                    if (!is_array($rawBase)) {
                        $error = 'মেইন সার্ভার থেকে তথ্য পাওয়া যায়নি।';
                        $step = 'search';
                    } else {
                        $tmp = $buildFormDataFromRaw(['raw' => $rawBase, 'cache' => $cachedPayload], $ubrn, $dob);
                        $dobResolved = trim((string)($tmp['personBirthDate'] ?? ''));
                        if ($dobResolved === '') {
                            $dobResolved = $loadDobFromCacheByUbrn($ubrn, $officeId);
                        }
                        $raw = $rawBase;
                        if ($dobResolved !== '') {
                            $full = $fetchSessionFullRaw($ubrn, $dobResolved);
                            if (is_array($full) && isset($full['data']) && is_array($full['data']) && !empty($full['data'][0]) && is_array($full['data'][0])) {
                                $raw = ['data' => $full['data'][0], 'base' => $rawBase];
                            }
                        }
                        $formData = $buildFormDataFromRaw(['raw' => $raw, 'cache' => $cachedPayload], $ubrn, $dobResolved);
                        $saveCache($formData['ubrn'] ?? '', $formData['personBirthDate'] ?? '', $officeId, $formData);
                        $step = 'print';
                    }
                }
            }
        }
    }
}

if ($step !== 'print') {
    include __DIR__ . '/includes/header.php';
    $recent = $loadRecentCache($officeId, 20);
    ?>
    <div class="container py-4">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <div class="fw-bold">সার্টিফিকেট প্রিন্ট</div>
            </div>
            <div class="card-body">
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo htmlspecialchars((string)$error); ?></div>
                <?php endif; ?>
                <?php if ($step === 'edit'): ?>
                    <form method="post" action="print-certificate.php" class="row g-3">
                        <input type="hidden" name="action" value="print">
                        <?php if ($mode !== ''): ?>
                            <input type="hidden" name="mode" value="<?php echo htmlspecialchars((string)$mode); ?>">
                        <?php endif; ?>
                        <?php if ($officeId !== ''): ?>
                            <input type="hidden" name="officeId" value="<?php echo htmlspecialchars((string)$officeId); ?>">
                        <?php endif; ?>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">নিবন্ধন নম্বর</label>
                            <input type="text" class="form-control" name="ubrn" value="<?php echo htmlspecialchars((string)($formData['ubrn'] ?? '')); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">জন্ম তারিখ (DD/MM/YYYY)</label>
                            <input type="text" class="form-control" name="personBirthDate" value="<?php echo htmlspecialchars((string)($formData['personBirthDate'] ?? '')); ?>" <?php echo $dobRequired ? 'required' : ''; ?>>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">Date of Registration</label>
                            <input type="text" class="form-control" name="dateOfRegistration" value="<?php echo htmlspecialchars((string)($formData['dateOfRegistration'] ?? '')); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Date of Issuance</label>
                            <input type="text" class="form-control" name="issueDate" value="<?php echo htmlspecialchars((string)($formData['issueDate'] ?? '')); ?>">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">লিঙ্গ (Sex)</label>
                            <select class="form-select" name="gender">
                                <?php $g = (string)($formData['gender'] ?? ''); ?>
                                <option value="" <?php echo $g === '' ? 'selected' : ''; ?>>--</option>
                                <option value="Male" <?php echo $g === 'Male' ? 'selected' : ''; ?>>Male</option>
                                <option value="Female" <?php echo $g === 'Female' ? 'selected' : ''; ?>>Female</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">QR টেক্সট (QR এর নিচে)</label>
                            <input type="text" class="form-control" name="qr_text" value="<?php echo htmlspecialchars((string)($formData['qr_text'] ?? 'IAAT')); ?>">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">নাম (বাংলা)</label>
                            <input type="text" class="form-control" name="personNameBn" value="<?php echo htmlspecialchars((string)($formData['personNameBn'] ?? '')); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Name (English)</label>
                            <input type="text" class="form-control" name="personNameEn" value="<?php echo htmlspecialchars((string)($formData['personNameEn'] ?? '')); ?>">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">পিতা (বাংলা)</label>
                            <input type="text" class="form-control" name="fatherNameBn" value="<?php echo htmlspecialchars((string)($formData['fatherNameBn'] ?? '')); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Father (English)</label>
                            <input type="text" class="form-control" name="fatherNameEn" value="<?php echo htmlspecialchars((string)($formData['fatherNameEn'] ?? '')); ?>">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">মাতা (বাংলা)</label>
                            <input type="text" class="form-control" name="motherNameBn" value="<?php echo htmlspecialchars((string)($formData['motherNameBn'] ?? '')); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Mother (English)</label>
                            <input type="text" class="form-control" name="motherNameEn" value="<?php echo htmlspecialchars((string)($formData['motherNameEn'] ?? '')); ?>">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">পিতার জাতীয়তা (বাংলা)</label>
                            <input type="text" class="form-control" name="fatherNationalityBn" value="<?php echo htmlspecialchars((string)($formData['fatherNationalityBn'] ?? 'বাংলাদেশী')); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Father Nationality (English)</label>
                            <input type="text" class="form-control" name="fatherNationalityEn" value="<?php echo htmlspecialchars((string)($formData['fatherNationalityEn'] ?? 'Bangladeshi')); ?>">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">মাতার জাতীয়তা (বাংলা)</label>
                            <input type="text" class="form-control" name="motherNationalityBn" value="<?php echo htmlspecialchars((string)($formData['motherNationalityBn'] ?? 'বাংলাদেশী')); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Mother Nationality (English)</label>
                            <input type="text" class="form-control" name="motherNationalityEn" value="<?php echo htmlspecialchars((string)($formData['motherNationalityEn'] ?? 'Bangladeshi')); ?>">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">জন্মস্থান (বাংলা)</label>
                            <textarea class="form-control" name="birthPlaceBn" rows="2"><?php echo htmlspecialchars((string)($formData['birthPlaceBn'] ?? '')); ?></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Place of Birth (English)</label>
                            <textarea class="form-control" name="birthPlaceEn" rows="2"><?php echo htmlspecialchars((string)($formData['birthPlaceEn'] ?? '')); ?></textarea>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">স্থায়ী ঠিকানা (বাংলা)</label>
                            <textarea class="form-control" name="permAddrBn" rows="3"><?php echo htmlspecialchars((string)($formData['permAddrBn'] ?? '')); ?></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Permanent Address (English)</label>
                            <textarea class="form-control" name="permAddrEn" rows="3"><?php echo htmlspecialchars((string)($formData['permAddrEn'] ?? '')); ?></textarea>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-bold">অফিসের নাম (বাংলা)</label>
                            <input type="text" class="form-control" name="officeNameBn" value="<?php echo htmlspecialchars((string)($formData['officeNameBn'] ?? '')); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Office Name (English)</label>
                            <input type="text" class="form-control" name="officeNameEn" value="<?php echo htmlspecialchars((string)($formData['officeNameEn'] ?? '')); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">অফিসের ঠিকানা (বাংলা)</label>
                            <textarea class="form-control" name="officeAddressBn" rows="2"><?php echo htmlspecialchars((string)($formData['officeAddressBn'] ?? '')); ?></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Office Address (English)</label>
                            <textarea class="form-control" name="officeAddressEn" rows="2"><?php echo htmlspecialchars((string)($formData['officeAddressEn'] ?? '')); ?></textarea>
                        </div>

                        <input type="hidden" name="qr_code" value="<?php echo htmlspecialchars((string)($formData['qr_code'] ?? '')); ?>">

                        <div class="col-12 d-flex gap-2">
                            <a class="btn btn-outline-secondary w-50" href="print-certificate.php">Back</a>
                            <button type="submit" class="btn btn-success w-50 fw-bold">সার্টিফিকেট মেক</button>
                        </div>
                    </form>
                <?php else: ?>
                    <?php if ($hasSessionCookies || $officeId !== ''): ?>
                        <div class="card mb-3 border-0 shadow-sm">
                            <div class="card-body">
                                <div class="fw-bold mb-2">মেইন সেশন সার্চ (জন্ম তারিখ লাগবে না)</div>
                                <form method="post" action="print-certificate.php" class="row g-3">
                                    <input type="hidden" name="action" value="fetch">
                                    <input type="hidden" name="mode" value="main">
                                    <?php if ($officeId !== ''): ?>
                                        <input type="hidden" name="officeId" value="<?php echo htmlspecialchars((string)$officeId); ?>">
                                    <?php endif; ?>
                                    <div class="col-12">
                                        <label class="form-label fw-bold">নিবন্ধন নম্বর</label>
                                        <input type="text" class="form-control" name="birth_reg_no" value="<?php echo htmlspecialchars((string)$ubrnInput); ?>" placeholder="১৭ ডিজিট" required>
                                    </div>
                                    <div class="col-12">
                                        <button type="submit" class="btn btn-primary w-100 fw-bold">অটো তথ্য পূরণ করুন</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="card border-0 shadow-sm">
                        <div class="card-body">
                            <div class="fw-bold mb-2">পাবলিক সার্চ (জন্ম তারিখ লাগবে)</div>
                            <form method="post" action="print-certificate.php" class="row g-3" data-dob-required="1">
                                <input type="hidden" name="action" value="fetch">
                                <input type="hidden" name="mode" value="public">
                                <div class="col-md-6">
                                    <label class="form-label fw-bold"><i class="fa-solid fa-id-card me-1"></i> Birth Registration Number</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" name="birth_reg_no" value="<?php echo htmlspecialchars((string)$ubrnInput); ?>" placeholder="Enter 17-digit birth registration number" required>
                                        <button type="button" class="btn btn-success fw-bold" id="dobLookupBtn"><i class="fa-solid fa-calendar-check me-1"></i> জন্ম তারিখ আনুন</button>
                                    </div>
                                    <div class="form-text">Must be exactly 17 digits</div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-bold"><i class="fa-solid fa-cake-candles me-1"></i> Date of Birth</label>
                                    <?php
                                    $dobValueIso = '';
                                    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)$dobInput)) {
                                        $dobValueIso = (string)$dobInput;
                                    } elseif (preg_match('/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/', (string)$dobInput, $mm)) {
                                        $dobValueIso = sprintf('%04d-%02d-%02d', (int)$mm[3], (int)$mm[2], (int)$mm[1]);
                                    }
                                    ?>
                                    <input type="date" class="form-control" name="dob" value="<?php echo htmlspecialchars((string)$dobValueIso); ?>" placeholder="YYYY-MM-DD" required>
                                    <div class="form-text">Format: YYYY-MM-DD</div>
                                </div>
                                <div class="col-12">
                                    <div class="d-flex gap-2">
                                        <button type="submit" class="btn btn-outline-primary w-100 fw-bold">অটো তথ্য আনুন</button>
                                        <button type="button" class="btn btn-outline-dark w-100 fw-bold" id="searchCopyBtn"><i class="fa-regular fa-copy me-1"></i> সার্চ কপি</button>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="alert d-none mb-0" id="dobLookupMsg" role="alert"></div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="modal fade" id="searchCopyModal" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-lg modal-dialog-scrollable">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">সার্চ কপি</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <textarea class="form-control" id="searchCopyText" rows="14" readonly></textarea>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-primary fw-bold" id="copyToClipboardBtn">Copy</button>
                                    <button type="button" class="btn btn-outline-secondary fw-bold" data-bs-dismiss="modal">Close</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <script>
                        (function () {
                            function onlyDigits(s) { return (s || '').toString().replace(/\D+/g, ''); }
                            function wireDigitsOnly(input) {
                                if (!input) return;
                                input.addEventListener('input', function () {
                                    var cur = input.value || '';
                                    var digits = onlyDigits(cur);
                                    if (digits.length > 17) digits = digits.slice(0, 17);
                                    if (cur !== digits) input.value = digits;
                                });
                            }
                            function normalizeDob(v) {
                                v = (v || '').toString().trim();
                                if (!v) return '';
                                var m1 = v.match(/^(\d{4})[-\/.](\d{1,2})[-\/.](\d{1,2})$/);
                                if (m1) {
                                    var y = m1[1], mo = ('0' + m1[2]).slice(-2), d = ('0' + m1[3]).slice(-2);
                                    return d + '/' + mo + '/' + y;
                                }
                                var m2 = v.match(/^(\d{1,2})[-\/.](\d{1,2})[-\/.](\d{4})$/);
                                if (m2) {
                                    var d2 = ('0' + m2[1]).slice(-2), mo2 = ('0' + m2[2]).slice(-2), y2 = m2[3];
                                    return d2 + '/' + mo2 + '/' + y2;
                                }
                                var digits = onlyDigits(v);
                                if (digits.length === 8) {
                                    if (digits.slice(0, 2) === '19' || digits.slice(0, 2) === '20') {
                                        return digits.slice(6, 8) + '/' + digits.slice(4, 6) + '/' + digits.slice(0, 4);
                                    }
                                    return digits.slice(0, 2) + '/' + digits.slice(2, 4) + '/' + digits.slice(4);
                                }
                                return v;
                            }
                            function toIsoDate(v) {
                                var n = normalizeDob(v);
                                var m = n.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
                                if (!m) return '';
                                return m[3] + '-' + m[2] + '-' + m[1];
                            }

                            var form = document.querySelector('form[data-dob-required]');
                            if (!form) return;
                            var dob = form.querySelector('input[name="dob"]');
                            if (!dob) return;
                            var ubrn = form.querySelector('input[name="birth_reg_no"]');
                            var btn = document.getElementById('dobLookupBtn');
                            var copyBtn = document.getElementById('searchCopyBtn');
                            var msgEl = document.getElementById('dobLookupMsg');
                            var modalEl = document.getElementById('searchCopyModal');
                            var modal = null;
                            function getModal() {
                                if (!modalEl) return null;
                                if (modal) return modal;
                                if (window.bootstrap && window.bootstrap.Modal) {
                                    modal = new window.bootstrap.Modal(modalEl);
                                    return modal;
                                }
                                return null;
                            }
                            var textArea = document.getElementById('searchCopyText');
                            var copyToClipboardBtn = document.getElementById('copyToClipboardBtn');

                            function hideMsg() {
                                if (!msgEl) return;
                                msgEl.className = 'alert d-none mb-0';
                                msgEl.textContent = '';
                                msgEl.innerHTML = '';
                            }

                            function showMsgText(text, kind) {
                                if (!msgEl) return;
                                msgEl.className = 'alert mb-0 ' + (kind || 'alert-info');
                                msgEl.textContent = (text || '').toString();
                            }

                            function showMsgHtml(html, kind) {
                                if (!msgEl) return;
                                msgEl.className = 'alert mb-0 ' + (kind || 'alert-info');
                                msgEl.innerHTML = html || '';
                            }

                            function helpLinksHtml() {
                                return '<div class="d-flex flex-wrap gap-2 mt-2">'
                                    + '<a class="btn btn-sm btn-outline-primary fw-bold" href="session-manager.php" target="_blank" rel="noopener">Session Manager</a>'
                                    + '<a class="btn btn-sm btn-outline-secondary fw-bold" href="settings.php" target="_blank" rel="noopener">Settings (Cookie Sync)</a>'
                                    + '<a class="btn btn-sm btn-outline-dark fw-bold" href="dob-finder.php" target="_blank" rel="noopener">DOB Finder</a>'
                                    + '</div>';
                            }

                            function isOutOfArea(msg) {
                                msg = (msg || '').toString();
                                return msg.indexOf('আওতাধীন') !== -1;
                            }

                            function isSessionExpired(msg) {
                                msg = (msg || '').toString().toLowerCase();
                                return msg.indexOf('session expired') !== -1 || msg.indexOf('reconnect') !== -1;
                            }

                            window.addEventListener('message', function (e) {
                                if (!e.data || typeof e.data !== 'object') return;
                                if (e.data.type === 'bdris_result') {
                                    if (e.data.dob && dob) {
                                        dob.value = toIsoDate(e.data.dob);
                                        showMsgText('DOB: ' + e.data.dob + ' (সফলভাবে পাওয়া গেছে)', 'alert-success');
                                    }
                                }
                            });


                            function fetchJson(url) {
                                return fetch(url, { cache: 'no-store' }).then(function (r) {
                                    return r.text().then(function (t) {
                                        try {
                                            return JSON.parse(t);
                                        } catch (e) {
                                            var sn = (t || '').toString().slice(0, 200);
                                            throw new Error('Invalid response (' + (r.status || 0) + '): ' + sn);
                                        }
                                    });
                                });
                            }

                            wireDigitsOnly(ubrn);

                            if (copyToClipboardBtn && textArea) {
                                copyToClipboardBtn.addEventListener('click', function () {
                                    var t = textArea.value || '';
                                    if (!t) return;
                                    if (navigator.clipboard && navigator.clipboard.writeText) {
                                        navigator.clipboard.writeText(t).catch(function () { });
                                    } else {
                                        textArea.focus();
                                        textArea.select();
                                        try { document.execCommand('copy'); } catch (e) { }
                                    }
                                });
                            }
                            if (btn && ubrn) {
                                ubrn.addEventListener('keydown', function (e) {
                                    if (!e) return;
                                    if (e.key === 'Enter') {
                                        e.preventDefault();
                                        btn.click();
                                    }
                                });
                                btn.addEventListener('click', function () {
                                    hideMsg();
                                    var u = onlyDigits(ubrn.value);
                                    if (!u || u.length !== 17) {
                                        showMsgText('১৭ ডিজিট নিবন্ধন নম্বর দিন', 'alert-danger');
                                        return;
                                    }
                                    var old = btn.textContent;
                                    btn.disabled = true;
                                    btn.textContent = 'খুঁজছি...';
                                    fetchJson('get_dob_v2.php?ubrn=' + encodeURIComponent(u) + '&_=' + Date.now())
                                        .then(function (j) {
                                            if (j && j.ok && j.dob) {
                                                dob.value = toIsoDate(j.dob);
                                                showMsgText('DOB: ' + j.dob + (j.source ? (' | Source: ' + j.source) : ''), 'alert-success');
                                                return;
                                            }
                                            var msg = (j && (j.error || j.message)) ? (j.error || j.message) : 'DOB পাওয়া যায়নি';
                                            if (j && j.relay_needed) {
                                                showMsgHtml('<div class="fw-bold mb-2">' + msg + '</div>'
                                                    + '<button type="button" class="btn btn-sm btn-primary" onclick="window.open(\'' + j.relay_url + '\', \'_blank\', \'width=600,height=500\')">সরাসরি ডেটা আনুন (ক্লিক করুন)</button>', 'alert-warning');
                                            } else if (isOutOfArea(msg) || isSessionExpired(msg)) {
                                                showMsgHtml('<div class="fw-bold">' + msg + '</div>'
                                                    + '<div class="small text-muted mt-1">এই UBRN অন্য ইউনিয়ন/অফিসের হলে National/উচ্চ-অধিকার সেশন দরকার, অথবা প্রিন্ট লিংকের encryptedId (data=...) দিয়ে চেষ্টা করুন।</div>'
                                                    + helpLinksHtml(), 'alert-warning');
                                            } else {
                                                showMsgText(msg, 'alert-danger');
                                            }
                                        })
                                        .catch(function (e) {
                                            var em = (e && e.message) ? e.message : 'DOB অনুসন্ধান ব্যর্থ';
                                            showMsgText(em, 'alert-danger');
                                        })
                                        .finally(function () {
                                            btn.disabled = false;
                                            btn.textContent = old;
                                        });
                                });
                            }
                            if (copyBtn && ubrn && dob) {
                                copyBtn.addEventListener('click', function () {
                                    hideMsg();
                                    var u = onlyDigits(ubrn.value);
                                    if (!u || u.length !== 17) {
                                        showMsgText('১৭ ডিজিট নিবন্ধন নম্বর দিন', 'alert-danger');
                                        return;
                                    }
                                    var old = copyBtn.textContent;
                                    copyBtn.disabled = true;
                                    copyBtn.textContent = 'খুঁজছি...';
                                    var d0 = dob.value;
                                    var p = Promise.resolve(d0);
                                    if (!d0) {
                                        p = fetchJson('get_dob_v2.php?ubrn=' + encodeURIComponent(u) + '&_=' + Date.now())
                                            .then(function (j) {
                                                if (j && j.ok && j.dob) {
                                                    dob.value = toIsoDate(j.dob);
                                                    return dob.value;
                                                }
                                                var msg = (j && (j.error || j.message)) ? (j.error || j.message) : 'DOB পাওয়া যায়নি';
                                                if (j && j.relay_needed) {
                                                    showMsgHtml('<div class="fw-bold mb-2">' + msg + '</div>'
                                                        + '<button type="button" class="btn btn-sm btn-primary" onclick="window.open(\'' + j.relay_url + '\', \'_blank\', \'width=600,height=500\')">সরাসরি ডেটা আনুন (ক্লিক করুন)</button>', 'alert-warning');
                                                } else if (isOutOfArea(msg) || isSessionExpired(msg)) {
                                                    showMsgHtml('<div class="fw-bold">' + msg + '</div>'
                                                        + '<div class="small text-muted mt-1">এই UBRN অন্য ইউনিয়ন/অফিসের হলে National/উচ্চ-অধিকার সেশন দরকার, অথবা প্রিন্ট লিংকের encryptedId (data=...) দিয়ে চেষ্টা করুন।</div>'
                                                        + helpLinksHtml(), 'alert-warning');
                                                } else {
                                                    showMsgText(msg, 'alert-danger');
                                                }
                                                return '';
                                            });
                                    }
                                    p.then(function (di) {
                                        var d = normalizeDob(di);
                                        return fetch('get_br_copy.php?ubrn=' + encodeURIComponent(u) + '&dob=' + encodeURIComponent(d) + '&_=' + Date.now(), { cache: 'no-store' })
                                            .then(function (r) { return r.json(); });
                                    }).then(function (j) {
                                        if (j && j.ok && j.copy) {
                                            if (textArea) textArea.value = j.copy;
                                            var m = getModal();
                                            if (m) m.show();
                                            return;
                                        }
                                        var msg = (j && (j.error || j.message)) ? (j.error || j.message) : 'ডাটা পাওয়া যায়নি';
                                        showMsgText(msg, 'alert-danger');
                                    }).catch(function (e) {
                                        var msg = (e && e.message) ? e.message : 'সার্চ কপি ব্যর্থ';
                                        showMsgText(msg, 'alert-danger');
                                    })
                                      .finally(function () {
                                          copyBtn.disabled = false;
                                          copyBtn.textContent = old;
                                      });
                                });
                            }
                        })();
                    </script>
                <?php endif; ?>

                <?php if (!empty($recent) && $officeId !== '' && $step !== 'edit'): ?>
                    <hr>
                    <div class="fw-bold mb-2">সার্টিফিকেট তালিকা</div>
                    <div class="table-responsive">
                        <table class="table table-sm table-striped align-middle">
                            <thead>
                                <tr>
                                    <th>UBRN</th>
                                    <th>জন্ম তারিখ</th>
                                    <th>তারিখ</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recent as $r): ?>
                                    <?php
                                    $rU = (string)($r['ubrn'] ?? '');
                                    $rD = (string)($r['person_birth_date'] ?? '');
                                    $rT = (string)($r['updated_at'] ?? '');
                                    ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($rU); ?></td>
                                        <td><?php echo htmlspecialchars($rD); ?></td>
                                        <td><?php echo htmlspecialchars($rT); ?></td>
                                        <td class="text-end">
                                            <a class="btn btn-sm btn-outline-primary" href="print-certificate.php?action=print&officeId=<?php echo urlencode((string)$officeId); ?>&ubrn=<?php echo urlencode($rU); ?>&dob=<?php echo urlencode($rD); ?>">প্রিন্ট</a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php
    include __DIR__ . '/includes/footer.php';
    exit;
}

?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&family=Noto+Sans+Bengali:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="https://fonts.maateen.me/solaiman-lipi/font.css" rel="stylesheet">
    <style>
        :root {
            --bs-blue: #0d6efd;
            --bs-indigo: #6610f2;
            --bs-purple: #6f42c1;
            --bs-pink: #d63384;
            --bs-red: #dc3545;
            --bs-orange: #fd7e14;
            --bs-yellow: #ffc107;
            --bs-green: #198754;
            --bs-teal: #20c997;
            --bs-cyan: #0dcaf0;
            --bs-white: #fff;
            --bs-gray: #6c757d;
            --bs-gray-dark: #343a40;
            --bs-primary: #0d6efd;
            --bs-secondary: #6c757d;
            --bs-success: #198754;
            --bs-info: #0dcaf0;
            --bs-warning: #ffc107;
            --bs-danger: #dc3545;
            --bs-light: #f8f9fa;
            --bs-dark: #212529;
            --bs-font-sans-serif: system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans","Liberation Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";
            --bs-font-monospace: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;
            --bs-gradient: linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));
        }
        html {
            box-sizing: border-box;
        }
        @media (prefers-reduced-motion: no-preference) {
            html {
                scroll-behavior: smooth;
            }
        }
        body {
            box-sizing: border-box;
            margin: 0px;
            font-family: var(--bs-font-sans-serif);
            font-size: 1rem;
            font-weight: 400;
            line-height: 1.5;
            color: rgb(33, 37, 41);
            background-color: rgb(255, 255, 255);
            text-size-adjust: 100%;
            -webkit-tap-highlight-color: transparent;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgb(221, 221, 221);
            flex-direction: column;
            font-family: Helvetica;
            min-height: 100vh;
        }
        .bn { font-family: 'SolaimanLipi','Noto Sans Bengali','Hind Siliguri', sans-serif; }
        .en { font-family: Arial, Helvetica, sans-serif; }
        .c0156 {
            width: 100%;
            display: flex;
            padding: 0 8px;
            position: relative;
            box-sizing: border-box;
            align-items: center;
            justify-content: space-between;
            height: 41px;
            border-bottom: 1px solid #BEBEBE;
            box-shadow: 0px 4.8px 10.8px rgba(0,0,0,0.13), 0px 0px 4.7px rgba(0,0,0,0.11);
        }
        @media (max-width: 1470px) {
            .c0156 { justify-content: unset; }
        }
        @media (forced-colors:active) {
            .c0156 {
                border: 1px solid WindowText;
                background: Background;
            }
        }
        .c0157 { top: 0; position: fixed; box-shadow: none; background: #fff; z-index: 9999; }
        .c0158 { display: flex; align-items: center; gap: 10px; }
        .c0159 { width: 100%; display: grid; align-items: center; grid-template-columns: auto 420px; }
        @media (max-width: 1470px) { .c0159 { grid-template-columns: auto; } }
        @media (max-width: 790px) { .c0159 { display: none; } }
        .c0160 { width: 100%; display: flex; align-items: center; justify-content: center; }
        @media (max-width: 1470px) { .c0160 { margin: 0 auto; } }
        .c0161 { width: 100%; display: flex; align-items: center; justify-content: flex-end; }
        @media (max-width: 790px) { .c0161 { display: none; } }
        .cert-container {
            width: 8.3in;
            height: 11.7in;
            background: center center / 100% 100% white;
            box-sizing: border-box;
            overflow: auto;
            box-shadow: 0 0 15px rgba(0,0,0,0.2);
            margin-right: 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-direction: column;
            position: relative;
            padding: 20px 20px 20px 40px;
            z-index: 10;
        }
        .bg-watermark {
            position: absolute;
            top: 56%;
            left: 50%;
            transform: translate(-50%, -50%);
            opacity: 0.18;
            width: 80%;
            z-index: 0;
            pointer-events: none;
            filter: contrast(1.02) saturate(1.02);
        }
        .header { width: 100%; text-align: center; position: relative; z-index: 1; }
        .govt-logo { width: 74px; height: auto; }
        .barcode {
            height: 30px;
            width: 220px;
            object-fit: contain;
            box-sizing: border-box;
        }
        .qr-code {
            height: 110px;
            width: 110px;
            box-sizing: border-box;
            vertical-align: middle;
        }
        .title-en {
            box-sizing: border-box;
            margin-top: 0px;
            margin-bottom: 0.5rem;
            font-weight: 500;
            line-height: 1.2;
            font-size: calc(1.325rem + 0.9vw);
            margin: 0px;
            padding: 0px;
            font-size: 20px;
            font-family: Helvetica, Arial, sans-serif;
            color: rgb(53, 53, 53);
            margin-bottom: 5px;
            white-space: normal;
            display: block;
        }
        @media (min-width: 1200px) {
            .title-en {
                font-size: 2rem;
            }
        }
        .office-title {
            font-size: 16px !important;
            font-weight: 500;
            color: rgb(26, 26, 26);
            margin: 0;
            margin-bottom: -3px;
            padding: 0;
            box-sizing: border-box;
            white-space: normal;
            display: block;
        }
        .office-location {
            font-family: Roboto, sans-serif;
            font-size: 16px !important;
            font-weight: 500;
            color: rgb(26, 26, 26);
            margin: 0;
            margin-top: 4px !important;
            margin-bottom: -3px;
            padding: 0;
            box-sizing: border-box;
            white-space: normal;
            display: block;
        }
        .office-address {
            font-family: Roboto, sans-serif;
            font-size: 16px !important;
            font-weight: 500;
            color: rgb(26, 26, 26);
            margin: 0;
            margin-top: 6px !important;
            margin-bottom: -3px;
            padding: 0;
            box-sizing: border-box;
            white-space: normal;
            display: block;
        }
        .brn-block {
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            margin-left: -37px;
            padding: 0px 0px 0px 52px;
        }
        .rule {
            font-size: 12px !important;
            font-weight: 500;
            color: rgb(26, 26, 26);
            margin: 0;
            margin-top: 2px !important;
            margin-bottom: -3px;
            padding: 0;
            box-sizing: border-box;
            display: block;
        }
        .cert-title {
            box-sizing: border-box;
            font-size: 20px;
            font-weight: bold;
            margin: 0;
            margin-top: 61px;
            margin-bottom: 15px;
            display: inline-block;
            text-decoration: none;
            padding-bottom: 3px;
        }
        .qr-text { font-size: 10px; text-align: center; color: #b5b5b5; letter-spacing: 0.8px; font-weight: 600; margin-top: 2px; }
        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 10px;
            margin-bottom: 10px;
            font-size: 14px;
        }
        .main-table {
            width: 100%;
            border-collapse: collapse;
            position: relative;
            z-index: 1;
            margin-top: 8px;
        }
        .main-table td {
            padding: 8px 4px;
            vertical-align: top;
            font-size: 14px;
            line-height: 1.3;
            font-weight: 400;
        }
        .label-col { width: 18%; font-weight: normal; }
        .val-col { width: 32%; white-space: normal; word-break: break-word; overflow-wrap: anywhere; }
        .field-long { font-size: 13px; }
        .footer {
            width: 100%;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: relative;
            margin-top: 61px;
            padding: 0 18px;
        }
        .signature-box { text-align: center; }
        .signature-box div:nth-child(2) { font-weight: 700; }

        @media print {
            .d-print-none { display: none !important; }
            @page { size: A4; margin: 0; }
            body { display: block; margin: 0; padding: 0; background: #fff; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .cert-container { width: 210mm; max-width: 210mm; min-height: 297mm; padding: 25mm 15mm 15mm; margin: 0 auto; box-shadow: none; }
            .govt-logo { width: 74px; height: auto; }
            .barcode { height: 30px; width: 220px; }
            .title-en { font-size: 20px; margin-bottom: 5px; }
            .office-title { font-size: 16px !important; margin-bottom: -3px; }
            .office-location { font-size: 16px !important; margin-top: 4px !important; margin-bottom: -3px; }
            .office-address { font-size: 16px !important; margin-top: 6px !important; margin-bottom: -3px; }
            .rule { font-size: 11px; }
            .cert-title { font-size: 18px; margin: 10px 0; }
            .info-grid { gap: 8px; font-size: 13px; }
            .main-table td { font-size: 12.5px; padding: 5px 3px; }
            .field-long { font-size: 12px; }
        }

        @media (max-width: 790px) {
            .cert-container { padding: 8mm 8mm 7mm; }
            .barcode { width: 130px; }
            .title-en { font-size: 14px; }
            .office-title { font-size: 12px; }
            .rule { font-size: 11px; }
            .cert-title { font-size: 18px; }
            .info-grid { grid-template-columns: 1fr; gap: 6px; }
            .main-table td { font-size: 12px; }
        }
    </style>
</head>
<body>
    <div class="d-print-none c0156 c0157" style="justify-content: center; gap: 4px; padding: 10px; background: #e9ecef;">
        <button class="btn" style="background-color: #198754; color: white; border: none; padding: 6px 20px; font-weight: bold; border-radius: 0;" onclick="setCertType('')">New</button>
        <button class="btn" style="background-color: #14a44d; color: white; border: none; padding: 6px 20px; font-weight: bold; border-radius: 0;" onclick="setCertType('সংশোধিত/Corrected')">Corrected</button>
        <button class="btn" style="background-color: #5b7cfa; color: white; border: none; padding: 6px 20px; font-weight: bold; border-radius: 0;" onclick="setCertType('প্রতিলিপি/Duplicate')">Duplicate</button>
        <button class="btn" style="background-color: #008000; color: white; border: none; padding: 6px 20px; font-weight: bold; border-radius: 0;" onclick="window.print()">Print</button>
        
        <a href="print-certificate.php<?php echo $officeId !== '' ? ('?officeId=' . urlencode((string)$officeId)) : ''; ?>" class="btn btn-secondary" style="position: absolute; left: 10px; border-radius: 0; padding: 6px 15px;">Back</a>
    </div>

    <script>
        function setCertType(type) {
            var box = document.getElementById('certStatusBox');
            if (type === '') {
                box.style.display = 'none';
            } else {
                box.style.display = 'block';
                box.innerHTML = type;
            }
        }
    </script>

    <div class="cert-container">
        <div style="display:none;box-sizing:border-box;position:absolute;border:2px solid rgb(17, 17, 17);padding:3px 8px;right:50px;top:63px;font-size:14.4px;font-family:SolaimanLipi;" id="certStatusBox">
            <p style="margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"></p>
        </div> 
        <img src="img/watermark.png" alt="" style="position:absolute;top:634.594px;left:383.125px;transform:matrix(1, 0, 0, 1, -280.5, -280.5);vertical-align:middle;box-sizing:border-box;opacity: 0.28;filter: contrast(1.02) saturate(1.02);z-index: 0;pointer-events: none;" /> 
        
        <span style="z-index: 10;box-sizing:border-box;position:relative;width:100%;display:block;">
            <div style="position:relative; margin-top:61px; box-sizing:border-box; width:100%; text-align:center;">
                <!-- QR Code Left -->
                <div style="position:absolute; top:10px; left:0px; display:flex; align-items:center; justify-content:center; flex-direction:column; box-sizing:border-box; z-index:2;">
                    <img style="height:110px; width:110px; vertical-align:middle; box-sizing:border-box;" src="https://bwipjs-api.metafloor.com/?bcid=qrcode&text=<?php echo urlencode((string)($formData['qr_code'] ?? '')); ?>&scale=2&includetext=false" alt="QR Code" onerror="this.style.display='none';var fb=this.parentNode.querySelector('.qr-fallback');if(fb)fb.style.display='block';" />
                    <div class="qr-fallback" style="display:none;font-size:10px;line-height:1.2;word-break:break-all;text-align:center;width:110px;"><?php echo htmlspecialchars((string)($formData['qr_code'] ?? '')); ?></div>
                    <h2 style="font-size:17px;color:rgb(153, 153, 153);margin-top:11px;margin:11px 0px 0px;padding:0px;margin-bottom:0px;font-weight:500;line-height:20.4px;box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['qr_text'] ?? 'IAAT')); ?></h2>
                </div>
                
                <!-- Barcode Right -->
                <div style="position:absolute; top:35px; right:0px; box-sizing:border-box; z-index:2;">
                    <img class="barcode" src="https://bwipjs-api.metafloor.com/?bcid=code128&text=<?php echo urlencode((string)($formData['ubrn'] ?? '')); ?>&scale=2&height=10&includetext=false" style="height: 30px; width:220px; box-sizing:border-box;" onerror="this.style.display='none';">
                </div>

                <!-- Center Text -->
                <div style="display:inline-block; text-align:center; box-sizing:border-box; position:relative; z-index:1; margin-top: 30px;">
                    <img src="img/govt_logo.png" alt="Govt Logo" class="govt-logo" style="vertical-align:middle; box-sizing:border-box; margin-bottom:25px;" />
                    <h2 class="title-en">Government of the People's Republic of Bangladesh</h2>
                    <p class="office-title">Office of the Registrar, Birth and Death Registration</p>
                    
                    <?php if (trim((string)($formData['officeNameEn'] ?? '')) !== ''): ?>
                        <p class="office-location"><?php echo htmlspecialchars(ucwords(strtolower((string)$formData['officeNameEn']))); ?></p>
                    <?php else: ?>
                        <p class="office-location"><?php echo htmlspecialchars((string)($formData['officeNameBn'] ?? '')); ?></p>
                    <?php endif; ?>

                    <?php if (trim((string)($formData['officeAddressEn'] ?? '')) !== ''): ?>
                        <p class="office-address"><?php echo htmlspecialchars($formatOfficeAddressEn((string)$formData['officeAddressEn'])); ?></p>
                    <?php else: ?>
                        <p class="office-address"><?php echo htmlspecialchars((string)($formData['officeAddressBn'] ?? '')); ?></p>
                    <?php endif; ?>

                    <p class="rule">(Rule 9, 10)</p>
                    
                    <h1 style="font-size:24px; font-family:Roboto, sans-serif; color:rgb(0, 0, 0); font-weight:600; margin:15px 0px 0px; letter-spacing:1px; padding:0px; line-height:30px; box-sizing:border-box; text-align:center;">
                        <span style="font-family:'SolaimanLipi', sans-serif; font-size:20px; box-sizing:border-box;">জন্ম নিবন্ধন সনদ /</span> <span style="font-family:'Roboto Slab', serif; font-size:20px; box-sizing:border-box;">Birth Registration Certificate</span>
                    </h1>
                </div>
            </div>
            
            <div style="margin-top:18px;box-sizing:border-box;">
                <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;padding:0px 51px;margin-top:15px;box-sizing:border-box;">
                    <div style="box-sizing:border-box;margin-left:-17px;">
                        <p style="font-weight: normal;margin-bottom:0px;font-size:13px;color:rgb(35, 35, 35);font-family:Roboto, sans-serif;margin:0px;padding:0px;margin-top:0px;box-sizing:border-box;">Date of Registration</p>
                        <p style="font-weight: normal;margin-bottom:0px;font-size:13px;color:rgb(35, 35, 35);font-family:Roboto, sans-serif;margin:0px;padding:0px;margin-top:0px;box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['dateOfRegistration'] ?? '')); ?></p>
                    </div>
                    <div class="brn-block">
                        <h2 style="font-size:20px;color:rgb(26, 26, 26);font-weight:500;margin-bottom:3px;margin:0px 0px 3px;padding:0px;margin-top:0px;line-height:24px;box-sizing:border-box;">Birth Registration Number</h2>
                        <h1 style="font-weight:500 !important;font-size:18px;font-family:Roboto, sans-serif;color:rgb(0, 0, 0);margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;line-height:21.6px;box-sizing:border-box;"> <?php echo htmlspecialchars((string)($formData['ubrn'] ?? '')); ?></h1>
                    </div>
                    <div style="box-sizing:border-box;margin-left:-4px;">
                        <p style="font-weight: normal;margin-bottom:0px;font-size:13px;color:rgb(35, 35, 35);font-family:Roboto, sans-serif;margin:0px;padding:0px;margin-top:0px;box-sizing:border-box;">Date of Issuance</p>
                        <p style="font-weight: normal;margin-bottom:0px;font-size:13px;color:rgb(35, 35, 35);font-family:Roboto, sans-serif;margin:0px;padding:0px;margin-top:0px;box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['issueDate'] ?? '')); ?></p>
                    </div>
                </div>
                
                <div style="padding:0px 0px 0px 52px;box-sizing:border-box;">
                    <div style="margin-top: 13px;margin-bottom: 5px;width: 100%;float:left;box-sizing:border-box;">
                        <div style="width: 50%;float:left;display:flex;box-sizing:border-box;margin-left:-17px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(0, 0, 0);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">Date of Birth<span style="margin-left: 39px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(0, 0, 0);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['personBirthDate'] ?? '')); ?></span></p>
                            </div>
                        </div>
                        <div style="width: 39%;float:left;display:flex;margin-left:35px;box-sizing:border-box;">
                            <div style="box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(0, 0, 0);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="margin-left: 95px;margin-right:13px;box-sizing:border-box;">Sex :</span></p>
                            </div>
                            <div style="box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(0, 0, 0);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['gender'] ?? '')); ?></span></p>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 5px;margin-bottom: 24px !important;width: 100%;display:grid;grid-template-columns:516px 108.781px;box-sizing:border-box;">
                        <div style="display:grid;grid-template-columns:133px 400px;box-sizing:border-box;margin-left:-17px;">
                            <div style="width: 126px;margin-right:7px;box-sizing:border-box;">
                                <p style="display:flex;align-items:center;justify-content:space-between;font-size:15px;font-weight:500;color:rgb(0, 0, 0);margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">In Word<span style="box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 400px;box-sizing:border-box;">
                                <p style="font-size:15px;font-weight:500;color:rgb(0, 0, 0);margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-style: oblique; margin-left:5px;box-sizing:border-box;"><?php echo htmlspecialchars(dateToWords((string)($formData['personBirthDate'] ?? ''))); ?></span></p>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 7px;width: 100%;float:left;box-sizing:border-box;">
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-17px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">নাম<span style="margin-left: 100px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['personNameBn'] ?? '')); ?></span></p>
                            </div>
                        </div>
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-4px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-weight:500;font-size:15px;color:rgb(26, 26, 26);margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">Name<span style="margin-left: 95px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-weight:500;box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['personNameEn'] ?? '')); ?></span></p>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 17px;width: 100%;float:left;box-sizing:border-box;">
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-17px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">মাতা<span style="margin-left: 94px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['motherNameBn'] ?? '')); ?></span></p>
                            </div>
                        </div>
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-4px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-weight:500;font-size:15px;color:rgb(26, 26, 26);margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">Mother<span style="margin-left: 87px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-weight:500;box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['motherNameEn'] ?? '')); ?></span></p>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 17px;width: 100%;float:left;box-sizing:border-box;">
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-17px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">মাতার জাতীয়তা<span style="margin-left: 26px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;box-sizing:border-box;"><?php echo htmlspecialchars((string)(trim((string)($formData['motherNationalityBn'] ?? '')) !== '' ? (string)($formData['motherNationalityBn'] ?? '') : 'বাংলাদেশী')); ?></span></p>
                            </div>
                        </div>
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-4px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-weight:500;font-size:15px;color:rgb(26, 26, 26);margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">Nationality<span style="margin-left: 64px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-weight:500;box-sizing:border-box;"><?php echo htmlspecialchars((string)(trim((string)($formData['motherNationalityEn'] ?? '')) !== '' ? (string)($formData['motherNationalityEn'] ?? '') : 'Bangladeshi')); ?></span></p>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 16px;width: 100%;float:left;box-sizing:border-box;">
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-17px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">পিতা<span style="margin-left: 94px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['fatherNameBn'] ?? '')); ?></span></p>
                            </div>
                        </div>
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-4px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-weight:500;font-size:15px;color:rgb(26, 26, 26);margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">Father<span style="margin-left: 91px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-weight:500;box-sizing:border-box;"><?php echo htmlspecialchars((string)($formData['fatherNameEn'] ?? '')); ?></span></p>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 17px;width: 100%;float:left;box-sizing:border-box;">
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-17px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">পিতার জাতীয়তা<span style="margin-left: 26px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;box-sizing:border-box;"><?php echo htmlspecialchars((string)(trim((string)($formData['fatherNationalityBn'] ?? '')) !== '' ? (string)($formData['fatherNationalityBn'] ?? '') : 'বাংলাদেশী')); ?></span></p>
                            </div>
                        </div>
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-4px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-weight:500;font-size:15px;color:rgb(26, 26, 26);margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">Nationality<span style="margin-left: 65px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-weight:500;box-sizing:border-box;"><?php echo htmlspecialchars((string)(trim((string)($formData['fatherNationalityEn'] ?? '')) !== '' ? (string)($formData['fatherNationalityEn'] ?? '') : 'Bangladeshi')); ?></span></p>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 17px;width: 100%;float:left;box-sizing:border-box;">
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-17px;">
                            <div style="box-sizing:border-box;">
                                <p style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">জন্মস্থান<span style="margin-left: 78px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;box-sizing:border-box;word-break: break-word;"><?php echo htmlspecialchars(filterBirthPlace((string)($formData['birthPlaceBn'] ?? ''))); ?></span></p>
                            </div>
                        </div>
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-4px;">
                            <div style="box-sizing:border-box;">
                                <p style="width: 153px; font-weight:500;font-size:15px;color:rgb(26, 26, 26);margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">Place of Birth<span style="margin-left: 46px;margin-right: 0;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-weight:500;box-sizing:border-box;word-break: break-word;"><?php echo htmlspecialchars(filterBirthPlace((string)($formData['birthPlaceEn'] ?? ''))); ?></span></p>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 30px;width: 100%;float:left;box-sizing:border-box;">
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-17px;">
                            <div style="box-sizing:border-box;">
                                <p style="width: 146px;font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);font-size:17px;font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">স্থায়ী ঠিকানা<span style="margin-left:53px;margin-right: 0;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-size: 15px !important;font-family:'SolaimanLipi', bangla_font, sans-serif;color:rgb(47, 47, 47);box-sizing:border-box;word-break: break-word;"><?php echo htmlspecialchars((string)($formData['permAddrBn'] ?? '')); ?></span></p>
                            </div>
                        </div>
                        <div style="float:left;width: 50%;display:flex;align-items:start;justify-content:start;box-sizing:border-box;margin-left:-4px;">
                            <div style="box-sizing:border-box;">
                                <p style="display:flex; width:154px; font-weight:500;font-size:15px;color:rgb(26, 26, 26);margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">Permanent<br style="box-sizing:border-box;" />Address<span style="margin-left: 64px;margin-right:13px;box-sizing:border-box;">:</span></p>
                            </div>
                            <div style="width: 188px;box-sizing:border-box;">
                                <p style="font-size:15px;color:rgb(26, 26, 26);font-weight:500;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;"><span style="font-weight:500;text-transform: capitalize; font-size:14px;box-sizing:border-box;word-break: break-word;"><?php echo htmlspecialchars((string)($formData['permAddrEn'] ?? '')); ?></span></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </span>
        
        <div style="padding:0px 3px 22px;margin-bottom:0px;box-sizing:border-box;width:100%;">
            <div style="display:block;margin-bottom:20px;width: 655px;float:left;box-sizing:border-box;">
                <div style="display:flex;align-items:center;justify-content:center;flex-direction:column;width: 31% !important;float:left;box-sizing:border-box;margin-left:-17px;">
                    <h2 style="width:10rem; margin-top: 0px;font-size:17px;color:rgb(0, 0, 0);font-weight:400;text-align:center;margin-bottom:5px;font-family:Roboto, sans-serif;margin:0px 0px 5px;padding:0px;line-height:20.4px;box-sizing:border-box;">Seal &amp; Signature</h2>
                    <p style="margin-top: 0px;margin-bottom:0px;font-size:13px;color:rgb(35, 35, 35);font-weight:500;font-family:Roboto, sans-serif;text-align:center;padding:0px;box-sizing:border-box;">Assistant to Registrar</p>
                    <p style="margin-top: 0px;margin-bottom:0px;font-size:13px;color:rgb(35, 35, 35);font-weight:500;font-family:Roboto, sans-serif;text-align:center;padding:0px;box-sizing:border-box;">(Preparation, Verification)</p>
                </div>
                <div style="display:flex;align-items:center;justify-content:center;flex-direction:column;width: 20% !important;float:right;box-sizing:border-box;margin-left:-4px;">
                    <h2 style="width:10rem;font-size:17px;color:rgb(0, 0, 0);font-weight:400;text-align:center;margin-bottom:5px;font-family:Roboto, sans-serif;margin:0px 0px 5px;padding:0px;margin-top:0px;line-height:20.4px;box-sizing:border-box;">Seal &amp; Signature</h2>
                    <p style="margin-bottom:0px;font-size:13px;color:rgb(35, 35, 35);font-weight:500;font-family:Roboto, sans-serif;text-align:center;padding:0px;margin-top:0px;box-sizing:border-box;">Registrar</p>
                </div>
            </div>
            <div style="margin-top:8rem;box-sizing:border-box;clear:both;">
                <p style="font-size:10px;color:rgb(35, 35, 35);font-weight:500;font-family:Roboto, sans-serif;text-align:center;margin:0px;padding:0px;margin-top:0px;margin-bottom:0px;box-sizing:border-box;">This certificate is generated from bdris.gov.bd, and to verify this certificate, please scan the above QR Code &amp; Bar Code.</p>
            </div>
        </div>
    </div>

</body>
</html>
