<?php
ob_start();
require_once __DIR__ . '/includes/ProxyHelper.php';

$proxy      = new ProxyHelper();
$birth_reg_no = '';
$searchResult = null;
$error        = null;
$debugLog     = [];
$apiUsed      = '';

/* ── helpers ─────────────────────────────────────────────── */
function normalizeDob($v) {
    $v = trim((string)$v);
    if ($v === '') return '';
    if (preg_match('/^(\d{2})\/(\d{2})\/(\d{4})$/', $v, $m))
        return "$m[1]/$m[2]/$m[3]";              // dd/mm/yyyy
    if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $v, $m))
        return "$m[3]/$m[2]/$m[1]";              // yyyy-mm-dd → dd/mm/yyyy
    return $v;
}
function toBn($s) {
    return str_replace(
        ['0','1','2','3','4','5','6','7','8','9'],
        ['০','১','২','৩','৪','৫','৬','৭','৮','৯'],
        (string)$s
    );
}
function tryJson($body) {
    if (!$body) return null;
    $d = json_decode($body, true);
    if (json_last_error() !== JSON_ERROR_NONE) return null;
    if (isset($d['EXCEPTION'])) return null;
    return $d;
}

/* ── AJAX mode: return JSON directly ────────────────────── */
if (isset($_GET['ajax']) && $_GET['ajax'] === '1') {
    header('Content-Type: application/json; charset=utf-8');

    $ubrn = preg_replace('/\D/', '', (string)($_GET['ubrn'] ?? $_POST['ubrn'] ?? ''));
    if (strlen($ubrn) < 9) {
        echo json_encode(['ok' => false, 'error' => 'অনুগ্রহ করে সঠিক নিবন্ধন নম্বর দিন।']);
        exit;
    }

    $log    = [];
    $result = null;
    $used   = '';

    // ── Check relay cache first (result stored by bdris-relay.php) ──
    $cacheDir  = dirname(__FILE__) . '/cache';
    $cacheFile = $cacheDir . '/relay_' . $ubrn . '.json';
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 300) {
        $cached = json_decode((string)file_get_contents($cacheFile), true);
        if (!empty($cached['data'])) {
            $result = $cached['data'];
            $used   = 'relay_cache:' . ($cached['source'] ?? '');
        }
    }

    // ── Try server-side APIs ──
    if (!$result) {
        $apis = [
            [
                'label' => 'everify /info/ubrn',
                'url'   => 'https://everify.bdris.gov.bd/api/br/info/ubrn/' . urlencode($ubrn),
                'ref'   => 'https://everify.bdris.gov.bd/',
            ],
            [
                'label' => 'bdris /info/ubrn',
                'url'   => 'https://bdris.gov.bd/api/br/info/ubrn/' . urlencode($ubrn),
                'ref'   => 'https://bdris.gov.bd/',
            ],
            [
                'label' => 'everify /search/by-ubrn',
                'url'   => 'https://everify.bdris.gov.bd/api/br/register/search/by-ubrn?ubrn=' . urlencode($ubrn),
                'ref'   => 'https://everify.bdris.gov.bd/',
            ],
            [
                'label' => 'bdris /search/by-ubrn',
                'url'   => 'https://bdris.gov.bd/api/br/register/search/by-ubrn?ubrn=' . urlencode($ubrn),
                'ref'   => 'https://bdris.gov.bd/',
            ],
        ];

        foreach ($apis as $api) {
            $resp = $proxy->fetch($api['url'], 'GET', [], false, $api['ref']);
            $status = (int)($resp['status'] ?? 0);
            $log[] = ['api' => $api['label'], 'http' => $status];

            if ($status === 200) {
                $parsed = tryJson($resp['body'] ?? '');
                if ($parsed) {
                    $result = $parsed;
                    $used   = $api['label'];
                    break;
                }
            }
        }
    }

    if (!$result) {
        echo json_encode([
            'ok'           => false,
            'relay_needed' => true,
            'relay_url'    => 'bdris-relay.php?ubrn=' . $ubrn,
            'error'        => 'সার্ভার থেকে তথ্য পাওয়া যায়নি। নিচের বাটন চাপুন — BDRIS ট্যাব খুলবে এবং স্বয়ংক্রিয়ভাবে তথ্য নেবে।',
            'debug'        => $log,
        ]);
        exit;
    }

    /* ── Extract fields ── */
    $person = $result['personMaster']['data'] ?? ($result['personMaster'] ?? $result);

    $getFirst = function(array $keys) use ($person) {
        foreach ($keys as $k) {
            $v = $person[$k] ?? null;
            if ($v !== null && trim((string)$v) !== '') return trim((string)$v);
        }
        return '';
    };

    $ubrn_out   = $result['ubrn']
                ?? $person['ubrn']
                ?? $person['birthRegistrationNumber']
                ?? $ubrn;
    $dobRaw     = $getFirst(['personBirthDate','dateOfBirth']);
    $dob        = normalizeDob($dobRaw);
    $nameBn     = $getFirst(['personNameBn','nameBn']);
    $nameEn     = $getFirst(['personNameEn','nameEn']);
    $gender     = $getFirst(['gender','personSex']);
    $office     = $getFirst(['registrationOfficeName','registrationOfficeNameBn']);
    $fatherBn   = $getFirst(['fatherNameBn']);
    $motherBn   = $getFirst(['motherNameBn']);
    $permAddr   = $getFirst(['fullPermAddrBn','permanentAddressBn','permAddrBn']);

    echo json_encode([
        'ok'       => true,
        'ubrn'     => $ubrn_out,
        'dob'      => $dob,
        'dobBn'    => toBn($dob),
        'nameBn'   => $nameBn,
        'nameEn'   => $nameEn,
        'gender'   => $gender,
        'office'   => $office,
        'fatherBn' => $fatherBn,
        'motherBn' => $motherBn,
        'permAddr' => $permAddr,
        'apiUsed'  => $used,
        'debug'    => $log,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

/* ── Normal page render ────────────────────────────────── */
?>
<?php include __DIR__ . '/includes/header.php'; ?>
<link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
/* ======================================================
   DOB FINDER — Full UI
   ====================================================== */
body {
    background: linear-gradient(135deg, #060d1a 0%, #0c1f3d 50%, #060d1a 100%);
    min-height: 100vh;
    font-family: 'Hind Siliguri', sans-serif;
    color: #e2e8f0;
}
.navbar { background: rgba(6,13,26,.97) !important; backdrop-filter: blur(12px); border-bottom: 1px solid rgba(59,130,246,.2); }

/* ── Wrapper ── */
.finder-wrap {
    max-width: 720px;
    margin: 28px auto 80px;
    padding: 0 16px;
}

/* ── Page Hero ── */
.hero {
    text-align: center;
    margin-bottom: 28px;
}
.hero-icon {
    width: 86px; height: 86px;
    background: linear-gradient(135deg, #1d4ed8, #0891b2);
    border-radius: 26px;
    display: flex; align-items: center; justify-content: center;
    margin: 0 auto 18px;
    font-size: 38px; color: #fff;
    box-shadow: 0 0 36px rgba(59,130,246,.45);
    animation: pulse-glow 3s ease-in-out infinite;
}
@keyframes pulse-glow {
    0%,100% { box-shadow: 0 0 28px rgba(59,130,246,.4); }
    50%      { box-shadow: 0 0 52px rgba(59,130,246,.75); }
}
.hero h1 { font-size: 28px; font-weight: 700; color: #f0f9ff; margin: 0 0 6px; }
.hero p  { font-size: 15px; color: #64748b; margin: 0; }

/* ── Search Card ── */
.search-card {
    background: rgba(255,255,255,.055);
    border: 1px solid rgba(255,255,255,.11);
    border-radius: 22px;
    padding: 36px 40px 32px;
    backdrop-filter: blur(24px);
    box-shadow: 0 24px 72px rgba(0,0,0,.45);
}

.field-label {
    display: block;
    font-size: 13px; font-weight: 600;
    color: #93c5fd; letter-spacing: .6px;
    margin-bottom: 10px;
}

/* ── Input ── */
.inp-wrap {
    display: flex;
    border-radius: 14px;
    overflow: hidden;
    border: 2px solid rgba(59,130,246,.3);
    transition: border-color .25s, box-shadow .25s;
}
.inp-wrap:focus-within {
    border-color: rgba(59,130,246,.75);
    box-shadow: 0 0 0 4px rgba(59,130,246,.15), 0 0 22px rgba(59,130,246,.2);
}
.inp-icon {
    background: rgba(59,130,246,.18);
    display: flex; align-items: center; padding: 0 18px;
    color: #60a5fa; font-size: 20px; flex-shrink: 0;
}
#ubrn {
    flex: 1;
    background: rgba(6,13,26,.85);
    border: none; outline: none;
    color: #f0f9ff; font-size: 19px;
    padding: 16px 18px;
    font-family: 'Courier New', monospace;
    letter-spacing: 1.5px;
}
#ubrn::placeholder { color: #334155; font-size: 13px; letter-spacing: 0; font-family: 'Hind Siliguri', sans-serif; }

/* ── Search Button ── */
#searchBtn {
    width: 100%; margin-top: 20px;
    padding: 17px; font-size: 18px; font-weight: 700;
    color: #fff;
    background: linear-gradient(135deg, #1d4ed8, #0891b2);
    border: none; border-radius: 14px; cursor: pointer;
    display: flex; align-items: center; justify-content: center; gap: 10px;
    box-shadow: 0 10px 28px rgba(29,78,216,.4);
    transition: all .28s; position: relative; overflow: hidden;
}
#searchBtn::before {
    content: '';
    position: absolute; top: 0; left: -100%;
    width: 100%; height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,.18), transparent);
    transition: left .5s;
}
#searchBtn:hover::before { left: 100%; }
#searchBtn:hover { transform: translateY(-2px); box-shadow: 0 16px 40px rgba(29,78,216,.55); }
#searchBtn:active { transform: translateY(0); }
#searchBtn:disabled { opacity: .75; pointer-events: none; }

/* Spinner */
.spin {
    width: 22px; height: 22px;
    border: 3px solid rgba(255,255,255,.3);
    border-top-color: #fff;
    border-radius: 50%;
    animation: spin .75s linear infinite;
    display: none;
}
@keyframes spin { to { transform: rotate(360deg); } }
.loading .spin { display: block; }
.loading .btn-txt { display: none; }

/* ── Progress Bar ── */
.progress-wrap {
    margin-top: 20px;
    display: none;
}
.progress-bar-bg {
    height: 4px;
    background: rgba(255,255,255,.08);
    border-radius: 2px;
    overflow: hidden;
}
.progress-bar-fill {
    height: 100%;
    background: linear-gradient(90deg, #1d4ed8, #06b6d4);
    border-radius: 2px;
    width: 0%;
    transition: width .4s ease;
}
.progress-txt {
    font-size: 12px; color: #64748b;
    text-align: center; margin-top: 8px;
}

/* ── Result Card ── */
.result-card {
    margin-top: 22px;
    border-radius: 22px;
    overflow: hidden;
    box-shadow: 0 24px 72px rgba(0,0,0,.55);
    animation: slideUp .38s ease;
    display: none;
}
@keyframes slideUp {
    from { opacity: 0; transform: translateY(22px); }
    to   { opacity: 1; transform: translateY(0); }
}

/* DOB Hero Block */
.dob-block {
    background: linear-gradient(135deg, #0f2744, #0c3460);
    padding: 40px 32px;
    text-align: center;
    border-bottom: 1px solid rgba(255,255,255,.08);
    position: relative;
}
.dob-badge {
    display: inline-block;
    background: rgba(16,185,129,.2);
    border: 1px solid rgba(16,185,129,.45);
    color: #34d399;
    font-size: 12px; font-weight: 700;
    padding: 3px 14px; border-radius: 20px;
    margin-bottom: 14px; letter-spacing: 1px;
}
.dob-label-txt {
    font-size: 12px; font-weight: 600;
    color: #64748b; letter-spacing: 2.5px;
    text-transform: uppercase; margin-bottom: 10px;
}
.dob-en {
    font-size: 48px; font-weight: 700;
    color: #60a5fa;
    font-family: 'Courier New', monospace;
    text-shadow: 0 0 40px rgba(96,165,250,.45);
    line-height: 1;
}
.dob-bn {
    font-size: 24px; color: #93c5fd;
    margin-top: 8px;
}
.copy-dob {
    margin-top: 14px;
    background: rgba(59,130,246,.18);
    border: 1px solid rgba(59,130,246,.35);
    color: #93c5fd; font-size: 13px;
    padding: 6px 18px; border-radius: 8px;
    cursor: pointer; transition: all .2s;
}
.copy-dob:hover { background: rgba(59,130,246,.35); color: #fff; }

/* Info Rows */
.info-section {
    background: rgba(6,13,26,.8);
    padding: 24px 32px;
}
.info-row {
    display: flex; align-items: flex-start;
    padding: 11px 0;
    border-bottom: 1px solid rgba(255,255,255,.055);
    gap: 16px;
}
.info-row:last-child { border-bottom: none; }
.info-row .lbl {
    font-size: 12.5px; color: #475569; font-weight: 600;
    min-width: 150px; flex-shrink: 0;
    padding-top: 2px;
}
.info-row .val {
    font-size: 15px; color: #e2e8f0; font-weight: 600;
    word-break: break-word;
}
.val-mono {
    font-family: 'Courier New', monospace;
    color: #93c5fd !important; font-size: 15px;
    background: rgba(59,130,246,.1);
    padding: 2px 10px; border-radius: 6px;
}

/* Actions */
.result-actions {
    background: rgba(6,13,26,.95);
    padding: 20px 32px;
    display: flex; gap: 10px; flex-wrap: wrap;
}
.act-btn {
    flex: 1; min-width: 130px;
    padding: 13px 20px;
    border-radius: 11px;
    font-size: 14px; font-weight: 600;
    text-decoration: none; text-align: center;
    border: none; cursor: pointer;
    display: inline-flex; align-items: center; justify-content: center; gap: 7px;
    transition: all .2s;
}
.act-primary { background: linear-gradient(135deg,#1d4ed8,#0891b2); color:#fff; box-shadow:0 4px 14px rgba(29,78,216,.3); }
.act-primary:hover { transform:translateY(-1px); color:#fff; box-shadow:0 8px 22px rgba(29,78,216,.5); }
.act-ghost { background:rgba(255,255,255,.07); color:#cbd5e1; border:1px solid rgba(255,255,255,.12); }
.act-ghost:hover { background:rgba(255,255,255,.13); color:#fff; }
.act-red { background:rgba(220,38,38,.15); color:#fca5a5; border:1px solid rgba(220,38,38,.3); }
.act-red:hover { background:rgba(220,38,38,.3); color:#fff; }

/* ── Error Box ── */
.err-box {
    display: none;
    margin-top: 20px;
    background: rgba(127,29,29,.28);
    border: 1px solid rgba(239,68,68,.38);
    border-radius: 14px;
    padding: 18px 24px;
    display: none;
    align-items: flex-start;
    gap: 14px;
    color: #fca5a5;
    animation: slideUp .3s ease;
}
.err-box i { font-size: 22px; color: #ef4444; flex-shrink: 0; margin-top: 2px; }
.err-box strong { display: block; margin-bottom: 3px; }
.err-box .err-detail { font-size: 13px; opacity: .8; }

/* ── Debug badge ── */
.api-badge {
    display: inline-block; margin-top: 8px;
    background: rgba(255,255,255,.06);
    border: 1px solid rgba(255,255,255,.1);
    font-size: 11px; color: #475569;
    padding: 2px 10px; border-radius: 6px;
    font-family: monospace;
}

/* Print */
@media print {
    body { background: #fff !important; }
    .navbar,.search-card,.result-actions,.no-print { display: none !important; }
    .result-card { display: block !important; box-shadow: none; border: 1px solid #ccc; }
    .dob-en { color: #1a5e1d !important; text-shadow: none; }
}
</style>

<div class="finder-wrap">

    <!-- Hero -->
    <div class="hero">
        <div class="hero-icon"><i class="fas fa-calendar-alt"></i></div>
        <h1>জন্ম তারিখ অনুসন্ধান</h1>
        <p>যেকোনো ইউনিয়নের নিবন্ধন নম্বর দিয়ে তাৎক্ষণিক জন্ম তারিখ বের করুন</p>
    </div>

    <!-- Search Box -->
    <div class="search-card no-print">
        <label class="field-label" for="ubrn">
            <i class="fas fa-id-card me-1"></i> জন্ম নিবন্ধন নম্বর
        </label>
        <div class="inp-wrap">
            <div class="inp-icon"><i class="fas fa-fingerprint"></i></div>
            <input
                type="text"
                id="ubrn"
                name="ubrn"
                placeholder="নিবন্ধন নম্বর লিখুন (যেমন: 20149XXXXXXXXXXXX)"
                inputmode="numeric"
                autocomplete="off"
                maxlength="20"
                autofocus
            >
        </div>

        <button type="button" id="searchBtn" onclick="doSearch()">
            <div class="spin"></div>
            <span class="btn-txt"><i class="fas fa-search"></i> &nbsp;জন্ম তারিখ বের করুন</span>
        </button>

        <!-- Progress -->
        <div class="progress-wrap" id="progressWrap">
            <div class="progress-bar-bg">
                <div class="progress-bar-fill" id="progressFill"></div>
            </div>
            <div class="progress-txt" id="progressTxt">সার্ভারে তথ্য খোঁজা হচ্ছে…</div>
        </div>
    </div>

    <!-- Error Box -->
    <div class="err-box" id="errBox">
        <i class="fas fa-exclamation-circle"></i>
        <div>
            <strong id="errTitle">তথ্য পাওয়া যায়নি</strong>
            <div class="err-detail" id="errDetail"></div>
        </div>
    </div>

    <!-- Result Card -->
    <div class="result-card" id="resultCard">
        <!-- DOB Block -->
        <div class="dob-block">
            <div class="dob-badge">✓ তথ্য পাওয়া গেছে</div>
            <div class="dob-label-txt">জন্ম তারিখ</div>
            <div class="dob-en" id="rDob">—</div>
            <div class="dob-bn" id="rDobBn"></div>
            <button class="copy-dob" onclick="copyDob()">
                <i class="fas fa-copy me-1"></i> কপি করুন
            </button>
            <div class="api-badge" id="rApi"></div>
        </div>

        <!-- Info Section -->
        <div class="info-section" id="infoSection"></div>

        <!-- Actions -->
        <div class="result-actions no-print" id="resultActions"></div>
    </div>
</div>

<script>
(function () {
    var currentUbrn = '';

    /* Enter key support */
    document.getElementById('ubrn').addEventListener('keydown', function (e) {
        if (e.key === 'Enter') doSearch();
    });

    /* Strip non-digits */
    document.getElementById('ubrn').addEventListener('input', function () {
        this.value = this.value.replace(/\D/g, '');
    });

    window.doSearch = function () {
        var ubrn = document.getElementById('ubrn').value.trim();
        if (ubrn.length < 9) {
            showError('অনুগ্রহ করে সঠিক নিবন্ধন নম্বর দিন।', 'কমপক্ষে ৯ সংখ্যার নম্বর প্রয়োজন।');
            return;
        }

        currentUbrn = ubrn;
        hideAll();
        setLoading(true);
        startProgress();

        fetch('dob-finder.php?ajax=1&ubrn=' + encodeURIComponent(ubrn))
            .then(function (r) { return r.json(); })
            .then(function (data) {
                setLoading(false);
                stopProgress();

                if (!data.ok) {
                    if (data.relay_needed && data.relay_url) {
                        // Open relay in a popup window
                        var left = (screen.width/2) - (600/2);
                        var top = (screen.height/2) - (500/2);
                        var popup = window.open(data.relay_url, 'bdris_relay', 'width=600,height=500,top='+top+',left='+left);
                        if (!popup) {
                            showError('পপআপ ব্লক করা আছে', 'দয়া করে ব্রাউজারে পপআপ (Popup) অ্যালাও করুন।');
                            return;
                        }
                        
                        showError('সার্ভার সরাসরি তথ্য আনতে পারেনি', 'একটি নতুন উইন্ডো খোলা হয়েছে। ব্রাউজার নিজে থেকেই তথ্য আনছে, দয়া করে অপেক্ষা করুন...');
                        
                        // Listen for result from popup
                        var listener = function(event) {
                            if (event.data && event.data.type === 'bdris_result' && event.data.ubrn === currentUbrn) {
                                window.removeEventListener('message', listener);
                                popup.close();
                                hideAll();
                                // Try fetching again - it should now be in the cache!
                                doSearch();
                            } else if (event.data && event.data.type === 'bdris_error' && event.data.ubrn === currentUbrn) {
                                window.removeEventListener('message', listener);
                                popup.close();
                                showError('তথ্য পাওয়া যায়নি', 'BDRIS সার্ভারে এই নিবন্ধন নম্বরটি নেই অথবা আপনার BDRIS সেশনের মেয়াদ শেষ।');
                            }
                        };
                        window.addEventListener('message', listener);
                        return;
                    }
                    showError('তথ্য পাওয়া যায়নি', data.error || 'অজানা ত্রুটি।');
                    return;
                }
                renderResult(data);
            })
            .catch(function (ex) {
                setLoading(false);
                stopProgress();
                showError('নেটওয়ার্ক ত্রুটি', ex.message || 'সার্ভারের সাথে যোগাযোগ করা যাচ্ছে না।');
            });
    };

    /* ── Progress animation ── */
    var pTimer = null, pVal = 0;
    function startProgress() {
        var wrap = document.getElementById('progressWrap');
        var fill = document.getElementById('progressFill');
        var txt  = document.getElementById('progressTxt');
        wrap.style.display = 'block';
        pVal = 0;
        fill.style.width = '0%';

        var messages = [
            'সার্ভারে তথ্য খোঁজা হচ্ছে…',
            'BDRIS API-তে অনুরোধ পাঠানো হচ্ছে…',
            'নিবন্ধন রেকর্ড যাচাই করা হচ্ছে…',
            'তথ্য প্রক্রিয়া করা হচ্ছে…'
        ];
        var mi = 0;

        pTimer = setInterval(function () {
            pVal = Math.min(pVal + (pVal < 60 ? 3 : pVal < 85 ? 1.5 : 0.3), 92);
            fill.style.width = pVal + '%';
            if (pVal > (mi + 1) * 22 && mi < messages.length - 1) {
                mi++;
                txt.textContent = messages[mi];
            }
        }, 120);
    }
    function stopProgress() {
        clearInterval(pTimer);
        var fill = document.getElementById('progressFill');
        fill.style.width = '100%';
        setTimeout(function () {
            document.getElementById('progressWrap').style.display = 'none';
        }, 400);
    }

    /* ── UI helpers ── */
    function setLoading(on) {
        var btn = document.getElementById('searchBtn');
        btn.disabled = on;
        if (on) btn.classList.add('loading');
        else btn.classList.remove('loading');
    }
    function hideAll() {
        document.getElementById('resultCard').style.display = 'none';
        document.getElementById('errBox').style.display = 'none';
    }
    function showError(title, detail) {
        document.getElementById('errTitle').textContent = title;
        document.getElementById('errDetail').textContent = detail;
        var b = document.getElementById('errBox');
        b.style.display = 'flex';
    }

    /* ── Render result ── */
    function renderResult(d) {
        /* DOB */
        document.getElementById('rDob').textContent   = d.dob   || '—';
        document.getElementById('rDobBn').textContent = d.dobBn || '';
        document.getElementById('rApi').textContent   = 'via: ' + (d.apiUsed || '');

        /* Info rows */
        var rows = [
            { lbl: '🔢 নিবন্ধন নম্বর', val: d.ubrn,     mono: true  },
            { lbl: '👤 নাম (বাংলা)',   val: d.nameBn,           },
            { lbl: '👤 Name (EN)',      val: d.nameEn,           },
            { lbl: '⚤ লিঙ্গ',          val: d.gender,           },
            { lbl: '👨 পিতার নাম',     val: d.fatherBn,         },
            { lbl: '👩 মাতার নাম',     val: d.motherBn,         },
            { lbl: '🏢 নিবন্ধন কার্যালয়', val: d.office,      },
            { lbl: '📍 স্থায়ী ঠিকানা', val: d.permAddr,        },
        ];

        var html = '';
        rows.forEach(function (r) {
            if (!r.val) return;
            var cls = r.mono ? 'val val-mono' : 'val';
            html += '<div class="info-row">'
                  + '<span class="lbl">' + esc(r.lbl) + '</span>'
                  + '<span class="' + cls + '">' + esc(r.val) + '</span>'
                  + '</div>';
        });
        document.getElementById('infoSection').innerHTML = html;

        /* Actions */
        var uq  = encodeURIComponent(d.ubrn);
        var dq  = encodeURIComponent(d.dob);
        document.getElementById('resultActions').innerHTML =
            '<a href="search-birth.php?ubrn=' + uq + '" class="act-btn act-primary" target="_blank"><i class="fas fa-file-alt"></i> বিস্তারিত তথ্য</a>' +
            '<a href="print-certificate.php?action=fetch&ubrn=' + uq + '&dob=' + dq + '" class="act-btn act-ghost" target="_blank"><i class="fas fa-certificate"></i> সনদ PDF</a>' +
            '<button onclick="window.print()" class="act-btn act-red"><i class="fas fa-print"></i> প্রিন্ট</button>';

        /* Show */
        var card = document.getElementById('resultCard');
        card.style.display = 'block';
        card.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    /* ── Copy DOB ── */
    window.copyDob = function () {
        var dob = document.getElementById('rDob').textContent;
        if (!dob || dob === '—') return;
        navigator.clipboard.writeText(dob).then(function () {
            var btn = document.querySelector('.copy-dob');
            btn.innerHTML = '<i class="fas fa-check me-1"></i> কপি হয়েছে!';
            btn.style.borderColor = '#10b981';
            btn.style.color = '#34d399';
            setTimeout(function () {
                btn.innerHTML = '<i class="fas fa-copy me-1"></i> কপি করুন';
                btn.style.borderColor = '';
                btn.style.color = '';
            }, 2000);
        });
    };

    function esc(s) {
        return String(s)
            .replace(/&/g,'&amp;')
            .replace(/</g,'&lt;')
            .replace(/>/g,'&gt;')
            .replace(/"/g,'&quot;');
    }
})();
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>