<?php
// get_br_copy.php
require_once __DIR__ . '/includes/ProxyHelper.php';

header('Content-Type: application/json; charset=utf-8');

$ubrn = trim($_GET['ubrn'] ?? '');
$dob = trim($_GET['dob'] ?? '');

if (strlen($ubrn) < 10 || strlen($ubrn) > 17 || !ctype_digit($ubrn) || $dob === '') {
    echo json_encode(['ok' => false, 'error' => 'Invalid UBRN or DOB']);
    exit;
}

$proxy = new ProxyHelper();

$dobYmd = $dob;
if (preg_match('/^(\d{2})\/(\d{2})\/(\d{4})$/', $dob, $m)) {
    $dobYmd = $m[3] . '-' . $m[2] . '-' . $m[1];
}

$url = 'https://bdris.gov.bd/api/br/user-search-by-ubrn-and-dob?ubrn='.urlencode($ubrn).'&personBirthDate='.urlencode($dobYmd);
$ref = 'https://bdris.gov.bd/admin/br/applications/search';

$resp = $proxy->fetch($url, 'GET', [], false, $ref, [], 15, 1, 200);

if (($resp['status'] ?? 0) === 200) {
    $j = json_decode($resp['body'] ?? '', true);
    if ($j && !empty($j['data']) && !empty($j['data'][0])) {
        $data = $j['data'][0];
        $copyText = "নিবন্ধন নম্বর (UBRN): " . ($data['ubrn'] ?? '') . "\n";
        $copyText .= "জন্ম তারিখ (DOB): " . ($data['personBirthDate'] ?? '') . "\n";
        $copyText .= "নাম (বাংলা): " . ($data['personNameBn'] ?? '') . "\n";
        $copyText .= "Name (English): " . ($data['personNameEn'] ?? '') . "\n";
        $copyText .= "পিতার নাম (বাংলা): " . ($data['fatherNameBn'] ?? '') . "\n";
        $copyText .= "Father Name (English): " . ($data['fatherNameEn'] ?? '') . "\n";
        $copyText .= "মাতার নাম (বাংলা): " . ($data['motherNameBn'] ?? '') . "\n";
        $copyText .= "Mother Name (English): " . ($data['motherNameEn'] ?? '') . "\n";
        $copyText .= "লিঙ্গ: " . ($data['gender'] ?? '') . "\n";
        $copyText .= "জন্মস্থান: " . ($data['birthPlaceBn'] ?? '') . "\n";
        
        echo json_encode(['ok' => true, 'copy' => $copyText]);
        exit;
    }
}

echo json_encode(['ok' => false, 'error' => 'ডাটা পাওয়া যায়নি বা সেশন নেই']);
exit;
