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

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

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

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

$proxy = new ProxyHelper();

// Check relay cache first
$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'])) {
        $j = $cached['data'];
        $person = $j['personMaster']['data'] ?? ($j['personMaster'] ?? $j);
        $dob = $person['personBirthDate'] ?? $person['dateOfBirth'] ?? ($j['data'][0]['dateOfBirth'] ?? '');
        if ($dob !== '') {
            echo json_encode(['ok' => true, 'dob' => $dob, 'source' => 'Relay Cache']);
            exit;
        }
    }
}

$endpoints = [
    ['url' => 'https://everify.bdris.gov.bd/api/br/info/ubrn/'.urlencode($ubrn), 'ref' => 'https://everify.bdris.gov.bd/'],
    ['url' => 'https://bdris.gov.bd/api/br/info/ubrn/'.urlencode($ubrn), 'ref' => 'https://bdris.gov.bd/admin/br/advanced-search-by-name'],
    ['url' => 'https://everify.bdris.gov.bd/api/br/register/search/by-ubrn?ubrn='.urlencode($ubrn), 'ref' => 'https://everify.bdris.gov.bd/'],
    ['url' => 'https://bdris.gov.bd/api/br/register/search/by-ubrn?ubrn='.urlencode($ubrn), 'ref' => 'https://bdris.gov.bd/admin/br/search'],
];

foreach ($endpoints as $ep) {
    $resp = $proxy->fetch($ep['url'], 'GET', [], false, $ep['ref'], [], 10, 1, 200);
    if (($resp['status'] ?? 0) === 200) {
        $j = json_decode($resp['body'] ?? '', true);
        if ($j && !isset($j['EXCEPTION'])) {
            $person = $j['personMaster']['data'] ?? ($j['personMaster'] ?? $j);
            $dob = $person['personBirthDate'] ?? $person['dateOfBirth'] ?? ($j['data'][0]['dateOfBirth'] ?? '');
            if ($dob !== '') {
                echo json_encode(['ok' => true, 'dob' => $dob, 'source' => 'API (' . parse_url($ep['url'], PHP_URL_HOST) . ')']);
                exit;
            }
        }
    }
}

echo json_encode([
    'ok' => false, 
    'relay_needed' => true,
    'relay_url' => 'bdris-relay.php?ubrn=' . urlencode($ubrn),
    'error' => 'DOB পাওয়া যায়নি। এটি অন্য ইউনিয়নের হতে পারে। দয়া করে BDRIS রিলে ব্যবহার করুন:'
]);
exit;
