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

$proxy = new ProxyHelper();
$searchResult = null;
$error = null;
$birth_reg_no = '';
$rawMode = (isset($_GET['rdata']) && (string)$_GET['rdata'] === '1');
$rawMeta = null;

// --- আপনার অরিজিনাল লজিক ফাংশনসমূহ ---
function safeParseJson($proxy, $resp) {
    if (method_exists($proxy, 'parseJson')) return $proxy->parseJson($resp);
    $body = $resp['body'] ?? '';
    return json_decode($body, true);
}

function normalizeDob($value) {
    $value = trim($value);
    if ($value === '') return ['', ''];
    if (preg_match('/^(\d{2})\/(\d{2})\/(\d{4})$/', $value, $m)) {
        $d = $m[1]; $mth = $m[2]; $y = $m[3];
    } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value, $m)) {
        $y = $m[1]; $mth = $m[2]; $d = $m[3];
    } else { return [$value, $value]; }
    return [sprintf('%02d/%02d/%04d', $d, $mth, $y), sprintf('%04d-%02d-%02d', $y, $mth, $d)];
}

// --- ডাটা প্রসেসিং (POST / GET) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw_ubrn = $_POST['birth_reg_no'] ?? '';
    $birth_reg_no = preg_replace('/\D/', '', $raw_ubrn);
} elseif (isset($_GET['ubrn']) && $_GET['ubrn'] !== '') {
    $raw_ubrn = $_GET['ubrn'];
    $birth_reg_no = preg_replace('/\D/', '', $raw_ubrn);
}

if ($birth_reg_no) {
    $relayNeeded = false;
    $relayUrl = '';
    
    // Step 0: Check Relay Cache
    $cacheFile = __DIR__ . '/cache/relay_' . $birth_reg_no . '.json';
    if (file_exists($cacheFile)) {
        $cdata = json_decode(file_get_contents($cacheFile), true);
        if ($cdata && (time() - $cdata['time'] < 60)) {
            $searchResult = $cdata['data'];
            if (isset($searchResult['personMaster'])) {
                 // Format is handled down below
            }
        }
    }

    if (!$searchResult) {
        $infoUrl = 'https://everify.bdris.gov.bd/api/br/info/ubrn/' . urlencode($birth_reg_no);
        $respInfo = $proxy->fetch($infoUrl, 'GET', [], false, 'https://everify.bdris.gov.bd/');

        if (($respInfo['status'] ?? 0) !== 200) {
            $infoUrl = 'https://bdris.gov.bd/api/br/info/ubrn/' . urlencode($birth_reg_no);
            $respInfo = $proxy->fetch($infoUrl, 'GET', [], false, 'https://bdris.gov.bd/');
        }

        if ($rawMode) {
            $format = strtolower(trim((string)($_GET['format'] ?? '')));
            $rawMeta = [
                'status' => (int)($respInfo['status'] ?? 0),
                'url' => (string)$infoUrl,
                'body' => (string)($respInfo['body'] ?? ''),
                'error' => (string)($respInfo['error'] ?? ''),
            ];
            if ($rawMeta['body'] !== '') {
                $decoded = json_decode($rawMeta['body'], true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $rawMeta['json'] = $decoded;
                }
            }
            $payload = json_encode($rawMeta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
            if ($payload === false) $payload = '';
            ob_clean();
            if ($format === 'json') {
                header('Content-Type: application/json; charset=utf-8');
                echo $payload;
                exit;
            }
            header('Content-Type: text/html; charset=utf-8');
            echo '<!doctype html><html lang="bn"><head><meta charset="utf-8"><title>R Data</title>';
            echo '<meta name="viewport" content="width=device-width,initial-scale=1"></head><body style="margin:0;padding:12px;font-family:monospace;background:#fff;">';
            echo '<pre style="white-space:pre-wrap;word-break:break-word;margin:0;">' . htmlspecialchars($payload, ENT_QUOTES, 'UTF-8') . '</pre>';
            echo '</body></html>';
            exit;
        }

        if (($respInfo['status'] ?? 0) === 200) {
            $parsed = safeParseJson($proxy, $respInfo);
            if ($parsed && !isset($parsed['EXCEPTION'])) {
                $searchResult = $parsed;
            }
        }

        if (!$searchResult) {
            $apiUrl = 'https://everify.bdris.gov.bd/api/br/register/search/by-ubrn?ubrn=' . urlencode($birth_reg_no);
            $resp = $proxy->fetch($apiUrl, 'GET', [], false, 'https://everify.bdris.gov.bd/');

            if (($resp['status'] ?? 0) !== 200) {
                $apiUrl = 'https://bdris.gov.bd/api/br/register/search/by-ubrn?ubrn=' . urlencode($birth_reg_no);
                $resp = $proxy->fetch($apiUrl, 'GET', [], false, 'https://bdris.gov.bd/');
            }

            if (($resp['status'] ?? 0) === 200) {
                $searchResult = $proxy->parseJson($resp);
            }

            // WAF বা এরর চেক
            $st = $respInfo['status'] ?? ($resp['status'] ?? 0);
            $b  = $respInfo['body']   ?? ($resp['body']   ?? '');
            if (!$searchResult && ($st === 400 || $st === 403 || strpos($b, 'Request Rejected') !== false || strpos($b, 'TSPD_101_DID') !== false)) {
                $error = 'BDRIS সার্ভার কানেকশন ব্লক করছে (WAF)। <br>নিচের বাটন চাপুন।';
                $relayNeeded = true;
                $relayUrl = 'bdris-relay.php?type=ubrn&key=' . urlencode($birth_reg_no);
            } elseif (!$searchResult) {
                $error = 'তথ্য পাওয়া যায়নি।';
            }
        } // end inner if(!$searchResult)
    } // end outer if(!$searchResult from cache)
} // end if($birth_reg_no)
?>

<?php include 'includes/header.php'; ?>

<link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
<link href="https://fonts.maateen.me/solaiman-lipi/font.css" rel="stylesheet">
<style>
    body { background: #f0f2f5; font-family: 'SolaimanLipi','Hind Siliguri', sans-serif; color: #111; }
    
    /* এ৪ প্রিন্ট সেটআপ */
    @page { size: A4; margin: 10mm; }
    @media print {
        .no-print, .navbar { display: none !important; }
        .result-sheet { margin: 0 !important; padding: 10px !important; width: 100% !important; box-shadow: none !important; border: none !important; }
        body { background: white !important; }
        table { border: 1px solid #333 !important; }
        th, td { border: 1px solid #333 !important; padding: 4px 8px !important; font-size: 13px !important; }
    }

    /* সার্চ কার্ড */
    .search-card { max-width: 900px; margin: 15px auto; background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); border-top: 4px solid #1a5e1d; }
    
    /* রেজাল্ট শিট - অত্যন্ত স্পষ্ট ও ক্লিয়ার ডিজাইন */
    .result-sheet { max-width: 900px; margin: 10px auto; background: white; padding: 30px 40px; box-shadow: 0 0 20px rgba(0,0,0,0.1); position: relative; border-radius: 2px; }
    
    .doc-header { text-align: center; border-bottom: 2px solid #1a5e1d; padding-bottom: 8px; margin-bottom: 12px; }
    .doc-header img { width: 65px; margin-bottom: 5px; }
    .doc-header h1 { margin: 0; font-size: 24px; color: #1a5e1d; font-weight: 700; letter-spacing: 0.3px; }
    .union-name { font-size: 18px; font-weight: bold; color: #333; }

    /* টেবিল ও গ্যাপ কমানো */
    .section-header { background: #f1f8f1; padding: 5px 12px; border-left: 5px solid #1a5e1d; font-weight: 700; font-size: 15px; margin-top: 15px; margin-bottom: 5px; color: #1a5e1d; }
    
    table { width: 100%; border-collapse: collapse; margin-bottom: 5px; }
    th { width: 33%; text-align: left; padding: 6px 12px; border: 1px solid #ddd; background: #fcfcfc; font-size: 13.5px; color: #444; }
    td { padding: 6px 12px; border: 1px solid #ddd; font-size: 15px; color: #000; font-weight: 600; }
    
    /* আইডি ও নম্বর হাইলাইট (Full View) */
    .val-highlight { color: #004085; font-weight: 700; font-family: 'Courier New', Courier, monospace; font-size: 16px; }

    .btn-pdf { background: #e44d26; color: white; padding: 10px 30px; border-radius: 4px; text-decoration: none; font-weight: bold; font-size: 15px; display: inline-block; margin-top: 15px; border: none; cursor: pointer; }
</style>

<div class="container-fluid">
    <!-- ১. সার্চ বক্স -->
    <div class="search-card no-print">
        <form action="" method="POST" class="row g-2 align-items-end">
            <div class="col-md-6">
                <label class="form-label small fw-bold">জন্ম নিবন্ধন নম্বর (১৭ ডিজিট)</label>
                <input type="text" class="form-control" name="birth_reg_no" placeholder="উদাঃ 2014XXXXXXXXXXXXX" value="<?= htmlspecialchars($birth_reg_no) ?>" required>
            </div>
            <div class="col-md-4">
                <label class="form-label small fw-bold">জন্ম তারিখ</label>
                <input type="date" class="form-control" name="dob" value="<?= htmlspecialchars($_POST['dob'] ?? '') ?>">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-success w-100 fw-bold">ডাটা খুঁজুন</button>
            </div>
        </form>
        </form>
    </div>

    <?php if ($error): ?>
    <div class="alert alert-danger rounded shadow-sm text-center">
        <i class="fas fa-exclamation-triangle me-2"></i>
        <?= $error ?>
        <?php if ($relayNeeded): ?>
        <div class="mt-2">
            <button class="btn btn-success fw-bold" onclick="openRelay('<?= htmlspecialchars($relayUrl) ?>')">
                <i class="fas fa-external-link-alt"></i> ব্রাউজার থেকে তথ্য নিন
            </button>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <?php if ($searchResult): ?>
        <?php
            $person = $searchResult['personMaster']['data'] ?? ($searchResult['personMaster'] ?? $searchResult);
            $ubrn   = $searchResult['ubrn'] ?? $person['ubrn'] ?? $person['birthRegistrationNumber'] ?? '';
            $dobSrc = $person['personBirthDate'] ?? ($person['dateOfBirth'] ?? '');
            $dobDmy = normalizeDob((string)$dobSrc)[0] ?? (string)$dobSrc;
            $rDataUrl = "search-birth.php?" . http_build_query([
                'rdata' => '1',
                'ubrn' => (string)$ubrn,
            ]);

            $pdfUrl = "view-certificate.php?" . http_build_query([
                'office_name' => $person['registrationOfficeName'] ?? '',
                'area_name'   => $person['fullPermAddrBn'] ?? $person['permanentAddressBn'] ?? '',
                'reg_num'     => $ubrn,
                'dob'         => $person['personBirthDate'] ?? $person['dateOfBirth'] ?? '',
                'gender'      => $person['gender'] ?? $person['personSex'] ?? '',
                'name_bn'     => $person['personNameBn'] ?? $person['nameBn'] ?? '',
                'name_en'     => $person['personNameEn'] ?? $person['nameEn'] ?? '',
                'father_bn'   => $person['fatherNameBn'] ?? '',
                'father_en'   => $person['fatherNameEn'] ?? '',
                'mother_bn'   => $person['motherNameBn'] ?? '',
                'mother_en'   => $person['motherNameEn'] ?? '',
                'p_birth'     => $person['fullBirthPlaceBn'] ?? $person['birthPlaceBn'] ?? '',
                'perm_addr'   => $person['fullPermAddrBn'] ?? $person['permanentAddressBn'] ?? '',
                'reg_date'    => $person['dateOfRegistration'] ?? ($searchResult['dateOfRegistration'] ?? '')
            ]);

            // পরিবারের অন্যান্য ভাই-বোন
            $familyList = $person['familyUbrnList'] ?? [];

            $norm = function($v) {
                if ($v === null) return '';
                if (is_array($v)) $v = implode(' ', array_map('strval', $v));
                $s = trim((string)$v);
                $s = preg_replace('/\s+/', ' ', $s);
                return $s;
            };
            $has = function($v) use ($norm) {
                $s = $norm($v);
                if ($s === '') return false;
                $low = strtolower($s);
                if ($low === 'n/a' || $low === 'na') return false;
                if ($s === 'পাওয়া যায়নি' || $s === 'তথ্য পাওয়া যায়নি') return false;
                return true;
            };
            $esc = function($v) {
                return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
            };
            $row = function($label, $value, $highlight = false) use ($has, $esc) {
                if (!$has($value)) return '';
                $cls = $highlight ? ' class="val-highlight"' : '';
                return '<tr><th>' . $esc($label) . '</th><td' . $cls . '>' . $value . '</td></tr>';
            };
            $getFirst = function($keys, $default = '') use ($person, $has) {
                foreach ($keys as $k) {
                    $v = $person[$k] ?? null;
                    $s = is_string($v) ? trim($v) : (is_numeric($v) ? (string)$v : '');
                    if ($has($s)) return $s;
                }
                return $default;
            };
        ?>

        <div class="result-sheet">
            <div class="doc-header" style="position: relative;">
                <a href="<?= htmlspecialchars($rDataUrl) ?>" target="_blank" class="btn btn-sm btn-outline-secondary no-print" style="position:absolute; top:10px; right:10px; padding:2px 8px; font-size:12px; line-height:1.2;">R Data</a>
                <img src="https://upload.wikimedia.org/wikipedia/commons/8/84/Government_Seal_of_Bangladesh.svg" alt="Seal">
                <h1>জন্ম নিবন্ধন বিস্তারিত তথ্য (Search Copy)</h1>
                <div class="union-name"><?= htmlspecialchars($person['registrationOfficeName'] ?? 'নিবন্ধন কার্যালয়') ?></div>
            </div>

            <!-- সেকশন ১: ব্যক্তিগত তথ্য -->
            <?php
                $s1 = [];
                $s1[] = $row('জন্ম নিবন্ধন নম্বর (UBRN)', $esc($ubrn), true);
                $nameBn = $getFirst(['personNameBn','nameBn'], '');
                $nameEn = $getFirst(['personNameEn','nameEn'], '');
                $nameHtml = '';
                if ($has($nameBn) || $has($nameEn)) {
                    $nameHtml = $esc($nameBn);
                    if ($has($nameEn)) $nameHtml .= '<br><small>' . $esc($nameEn) . '</small>';
                    $s1[] = $row('নিবন্ধিত ব্যক্তির নাম', $nameHtml);
                }
                $dob = $getFirst(['personBirthDate','dateOfBirth'], '');
                $sex = $getFirst(['gender','personSex'], '');
                if ($has($dob) || $has($sex)) {
                    $s1[] = $row('জন্ম তারিখ / লিঙ্গ', $esc($dob) . ($has($sex) ? (' / ' . $esc($sex)) : ''));
                }
                $mobile = $getFirst(['mobile','phone','mobileNo'], '');
                $s1[] = $row('মোবাইল নম্বর (সম্পূর্ণ)', $esc($mobile), true);
                $uid = $getFirst(['uid'], '');
                $sec = $getFirst(['securityCode'], '');
                if ($has($uid) || $has($sec)) {
                    $s1[] = $row('ব্যক্তিগত UID / সিকিউরিটি কোড', $esc($uid) . ($has($sec) ? (' / ' . $esc($sec)) : ''));
                }
                $s1 = array_values(array_filter($s1, function($x){ return is_string($x) && $x !== ''; }));
            ?>
            <?php if (!empty($s1)): ?>
                <div class="section-header">১. নিবন্ধিত ব্যক্তির মৌলিক তথ্য</div>
                <table><?= implode('', $s1) ?></table>
            <?php endif; ?>

            <!-- সেকশন ২: পিতা ও মাতা -->
            <?php
                $s2 = [];
                $fatherBn = $getFirst(['fatherNameBn'], '');
                $fatherEn = $getFirst(['fatherNameEn'], '');
                if ($has($fatherBn) || $has($fatherEn)) {
                    $h = $esc($fatherBn);
                    if ($has($fatherEn)) $h .= '<br><small>' . $esc($fatherEn) . '</small>';
                    $s2[] = $row('পিতার নাম (বাংলা ও ইংরেজি)', $h);
                }
                $s2[] = $row('পিতার নিবন্ধন নম্বর (BRN)', $esc($getFirst(['fatherBrn','fatherBirthRegNo'], '')), true);
                $s2[] = $row('পিতার এনআইডি (NID)', $esc($getFirst(['fatherNid'], '')));

                $motherBn = $getFirst(['motherNameBn'], '');
                $motherEn = $getFirst(['motherNameEn'], '');
                if ($has($motherBn) || $has($motherEn)) {
                    $h = $esc($motherBn);
                    if ($has($motherEn)) $h .= '<br><small>' . $esc($motherEn) . '</small>';
                    $s2[] = $row('মাতার নাম (বাংলা ও ইংরেজি)', $h);
                }
                $s2[] = $row('মাতার নিবন্ধন নম্বর (BRN)', $esc($getFirst(['motherBrn','motherBirthRegNo'], '')), true);
                $s2[] = $row('মাতার এনআইডি (NID)', $esc($getFirst(['motherNid'], '')));

                $s2 = array_values(array_filter($s2, function($x){ return is_string($x) && $x !== ''; }));
            ?>
            <?php if (!empty($s2)): ?>
                <div class="section-header">২. পিতা ও মাতার বিস্তারিত তথ্য</div>
                <table><?= implode('', $s2) ?></table>
            <?php endif; ?>

            <!-- সেকশন ৩: পরিবারের তথ্য -->
            <?php
                $s3 = [];
                $thChild = $getFirst(['thChild'], '');
                if ($has($thChild)) {
                    $s3[] = $row('সন্তানের ক্রমিক নং', 'পিতা-মাতার <strong>' . $esc($thChild) . '</strong> নং সন্তান');
                }
                $fam = '';
                if (is_array($familyList) && !empty($familyList)) {
                    $cleanFam = [];
                    foreach ($familyList as $x) {
                        $x = trim((string)$x);
                        if ($x === '') continue;
                        $cleanFam[$x] = true;
                    }
                    if (!empty($cleanFam)) $fam = implode(', ', array_keys($cleanFam));
                }
                $s3[] = $row('পরিবারের অন্যান্য সদস্যদের UBRN', $esc($fam), true);
                $s3 = array_values(array_filter($s3, function($x){ return is_string($x) && $x !== ''; }));
            ?>
            <?php if (!empty($s3)): ?>
                <div class="section-header">৩. পরিবারের ভাই-বোন ও অতিরিক্ত তথ্য</div>
                <table><?= implode('', $s3) ?></table>
            <?php endif; ?>

            <!-- সেকশন ৪: অফিস রেকর্ড -->
            <?php
                $s4 = [];
                $officeName = $getFirst(['registrationOfficeName','registrationOfficeNameBn'], '');
                $officeId = $getFirst(['birthRegisterId','registrationOfficeId'], '');
                if ($has($officeName) || $has($officeId)) {
                    $txt = $esc($officeName);
                    if ($has($officeId)) $txt .= ' (ID: ' . $esc($officeId) . ')';
                    $s4[] = $row('নিবন্ধন কার্যালয় ও আইডি', $txt);
                }
                $book = $getFirst(['bookNumber'], '');
                $page = $getFirst(['pageNumber'], '');
                $line = $getFirst(['lineNumber'], '');
                if ($has($book) || $has($page) || $has($line)) {
                    $txt = '';
                    if ($has($book)) $txt .= 'বই: ' . $esc($book);
                    if ($has($page)) $txt .= ($txt !== '' ? ', ' : '') . 'পৃষ্ঠা: ' . $esc($page);
                    if ($has($line)) $txt .= ($txt !== '' ? ', ' : '') . 'লাইন: ' . $esc($line);
                    $s4[] = $row('বই / পৃষ্ঠা / লাইন নং', $txt);
                }
                $birthPlaceFull = $getFirst(['fullBirthPlaceBn','birthPlaceBn'], '');
                if ($has($birthPlaceFull)) {
                    $s4[] = $row('পূর্ণ জন্মস্থান', '<small>' . $esc($birthPlaceFull) . '</small>');
                }
                $prsntBn = $getFirst(['fullPrsntAddrBn','prsntAddrBn','presentAddressBn','prsntAddressBn'], '');
                $prsntEn = $getFirst(['fullPrsntAddrEn','prsntAddrEn','presentAddressEn','prsntAddressEn'], '');
                if ($has($prsntBn) || $has($prsntEn)) {
                    $h = $has($prsntBn) ? ('<small>' . $esc($prsntBn) . '</small>') : '';
                    if ($has($prsntEn)) $h .= ($h !== '' ? '<br>' : '') . '<small>' . $esc($prsntEn) . '</small>';
                    $s4[] = $row('বর্তমান ঠিকানা (Bangla/English)', $h);
                }

                $permBn = $getFirst(['fullPermAddrBn','permAddrBn','permanentAddressBn'], '');
                $permEn = $getFirst(['fullPermAddrEn','permAddrEn','permanentAddressEn','permanentAddressEnglish'], '');
                if ($has($permBn) || $has($permEn)) {
                    $h = $has($permBn) ? ('<small>' . $esc($permBn) . '</small>') : '';
                    if ($has($permEn)) $h .= ($h !== '' ? '<br>' : '') . '<small>' . $esc($permEn) . '</small>';
                    $s4[] = $row('স্থায়ী ঠিকানা (Bangla/English)', $h);
                }
                $s4 = array_values(array_filter($s4, function($x){ return is_string($x) && $x !== ''; }));
            ?>
            <?php if (!empty($s4)): ?>
                <div class="section-header">৪. অফিস রেকর্ড ও ঠিকানার বিবরণ</div>
                <table><?= implode('', $s4) ?></table>
            <?php endif; ?>

            <!-- অ্যাকশন বাটন -->
            <div class="footer-action no-print" style="text-align: center;">
                <button onclick="window.print()" class="btn btn-dark fw-bold me-2"><i class="fa fa-print"></i> প্রিন্ট কপি</button>
                <a href="print-certificate.php?action=fetch&ubrn=<?= urlencode((string)$ubrn) ?>&dob=<?= urlencode((string)$dobDmy) ?>" target="_blank" class="btn-pdf"><i class="fa fa-file-pdf"></i> ডিজিটাল পিডিএফ সনদ</a>
            </div>
        </div>
    <?php endif; ?>
</div>

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

