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

$proxy = new ProxyHelper();
$results = null;
$error = null;
$debugLog = []; // Initialize debug log
$tryUrls = [
    'https://bdris.gov.bd/api/br/all-possible-duplicates-by-birth-registration-application-id'
];

$extractEncryptedId = function($val) use (&$extractEncryptedId) {
    if (is_array($val)) {
        foreach (['encryptedId','encryptedID','encrypted_id','encryptedApplicationId','encrypted_application_id'] as $k) {
            if (isset($val[$k]) && is_string($val[$k]) && trim($val[$k]) !== '') return trim($val[$k]);
        }
        foreach ($val as $v) {
            $r = $extractEncryptedId($v);
            if (is_string($r) && $r !== '') return $r;
        }
    }
    return '';
};

$termInput = '';
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $termInput = (string)($_POST['search_term'] ?? '');
} else {
    $termInput = (string)($_GET['data'] ?? ($_GET['encryptedId'] ?? ($_GET['search_term'] ?? '')));
}
$termInput = trim($termInput);
$termApi = $termInput;

$officeId = '';
if (isset($_POST['officeId']) && trim((string)$_POST['officeId']) !== '') {
    $officeId = trim((string)$_POST['officeId']);
} elseif (isset($_GET['officeId']) && trim((string)$_GET['officeId']) !== '') {
    $officeId = trim((string)$_GET['officeId']);
} else {
    $cacheFile = $proxy->getActiveOfficeFile();
    if (file_exists($cacheFile)) {
        $officeId = trim(file_get_contents($cacheFile));
    }
}

// Function to dynamically scrape and cache the active office token if needed
function resolveActiveOfficeToken($proxy, $forceRefresh = false) {
    $cacheFile = $proxy->getActiveOfficeFile();
    $token = '';
    if (!$forceRefresh && file_exists($cacheFile)) {
        $token = trim(file_get_contents($cacheFile));
    }
    
    if ($token === '' || $forceRefresh) {
        $respDash = $proxy->fetch('https://bdris.gov.bd/br/application', 'GET', [], false, 'https://bdris.gov.bd/');
        $dashBody = $respDash['body'] ?? '';
        if (preg_match('/\/admin\/br\/applications\/search\?data=([A-Za-z0-9_\-]+)/i', $dashBody, $m)) {
            $token = $m[1];
        } elseif (preg_match('/\/admin\/user\/chalan\?data=([A-Za-z0-9_\-]+)/i', $dashBody, $m)) {
            $token = $m[1];
        }
        if ($token !== '') {
            @file_put_contents($cacheFile, $token);
        }
    }
    return $token;
}

if ($officeId === '') {
    $officeId = resolveActiveOfficeToken($proxy);
}

// Helper function to resolve encrypted token to integer office ID
function getIntegerOfficeId($proxy, $officeToken) {
    if (empty($officeToken)) return '';
    if (strlen($officeToken) <= 15) return $officeToken; // already integer
    
    $cacheFile = __DIR__ . '/cache/office_mappings.json';
    $mappings = [];
    if (file_exists($cacheFile)) {
        $mappings = json_decode(file_get_contents($cacheFile), true);
    }
    
    // Look up by token in mappings
    foreach ($mappings as $geoId => $data) {
        if (($data['token'] ?? '') === $officeToken) {
            return $data['officeId'];
        }
    }
    
    // If not found in cache, fetch search page to parse
    $urlPage = "https://bdris.gov.bd/admin/br/applications/search?data=" . urlencode($officeToken);
    $baseHeaders = [
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: en-US,en;q=0.9,bn;q=0.8'
    ];
    $respPage = $proxy->fetch($urlPage, 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications', $baseHeaders);
    if (($respPage['status'] ?? 0) === 200) {
        $html = $respPage['body'] ?? '';
        $intOfficeId = null;
        if (preg_match('/(?:const|var|let)\s+officeId\s*=\s*([0-9]+)/i', $html, $m)) {
            $intOfficeId = $m[1];
        }
        if (empty($intOfficeId) || $intOfficeId == 'null') {
            if (preg_match('/"officeId":\s*([0-9]+)/i', $html, $m)) {
                $intOfficeId = $m[1];
            }
        }
        if (!empty($intOfficeId)) {
            // Save to mappings (temp geoId)
            $mappings['temp_' . time()] = [
                'token' => $officeToken,
                'officeId' => $intOfficeId
            ];
            @file_put_contents($cacheFile, json_encode($mappings, JSON_PRETTY_PRINT));
            return $intOfficeId;
        }
    }
    return '';
}

// Function to resolve all integer office IDs under the active upazila
function getActiveUpazilaOfficeIds($proxy) {
    $upazilaGeoIdFile = __DIR__ . '/cookies/active_upazila.txt';
    $upazilaGeoId = '';
    if (file_exists($upazilaGeoIdFile)) {
        $upazilaGeoId = trim(file_get_contents($upazilaGeoIdFile));
    }
    if ($upazilaGeoId === '') {
        $respDash = $proxy->fetch('https://bdris.gov.bd/br/application', 'GET', [], false, 'https://bdris.gov.bd/');
        if (preg_match('/geoId\s*:\s*([0-9]+)/i', $respDash['body'] ?? '', $m)) {
            $upazilaGeoId = $m[1];
            @file_put_contents($upazilaGeoIdFile, $upazilaGeoId);
        }
    }
    
    if ($upazilaGeoId === '') return [];
    
    $cacheFile = __DIR__ . '/cache/office_mappings.json';
    $mappings = [];
    if (file_exists($cacheFile)) {
        $mappings = json_decode(file_get_contents($cacheFile), true);
    }
    
    $geoCacheFile = __DIR__ . "/cache/geo/geo_{$upazilaGeoId}_officeAddr_3_3.json";
    $unions = [];
    if (file_exists($geoCacheFile)) {
        $geoData = json_decode(file_get_contents($geoCacheFile), true);
        $unions = $geoData['geoObject'] ?? $geoData ?? [];
    } else {
        $apiHeaders = [
            'Accept: application/json, text/plain, */*',
            'X-Requested-With: XMLHttpRequest',
            'client: bris'
        ];
        $urlGeo = "https://bdris.gov.bd/v1/api/geo/parentGeoIdWithGeoGroupAndGeoOrder/{$upazilaGeoId}?geoGroup=officeAddr&geoOrder=3&geoType=3";
        $respGeo = $proxy->fetch($urlGeo, 'GET', [], false, 'https://bdris.gov.bd/', $apiHeaders);
        if (($respGeo['status'] ?? 0) === 200) {
            @file_put_contents($geoCacheFile, $respGeo['body']);
            $geoData = json_decode($respGeo['body'], true);
            $unions = $geoData['geoObject'] ?? $geoData ?? [];
        }
    }
    
    if (!is_array($unions) || empty($unions)) return [];
    
    $officeIds = [];
    $baseHeaders = [
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: en-US,en;q=0.9,bn;q=0.8'
    ];
    $apiHeaders = [
        'Accept: application/json, text/plain, */*',
        'X-Requested-With: XMLHttpRequest',
        'client: bris'
    ];
    
    foreach ($unions as $u) {
        $uGeoId = $u['id'] ?? null;
        if (empty($uGeoId)) continue;
        
        $intOfficeId = $mappings[$uGeoId]['officeId'] ?? null;
        if (empty($intOfficeId)) {
            $urlToken = "https://bdris.gov.bd/api/office/find-office-geo-projection-by-geo-id/{$uGeoId}?geoGroup=officeAddr&geoOrder=4&geoType=5";
            $respToken = $proxy->fetch($urlToken, 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications', $apiHeaders);
            $tokenData = json_decode($respToken['body'] ?? '', true);
            $token = $tokenData['geoObject']['officeId'] ?? '';
            if (!empty($token)) {
                $urlPage = "https://bdris.gov.bd/admin/br/applications/search?data=" . urlencode($token);
                $respPage = $proxy->fetch($urlPage, 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications', $baseHeaders);
                $html = $respPage['body'] ?? '';
                
                if (preg_match('/(?:const|var|let)\s+officeId\s*=\s*([0-9]+)/i', $html, $m)) {
                    $intOfficeId = $m[1];
                }
                if (empty($intOfficeId) || $intOfficeId == 'null') {
                    if (preg_match('/"officeId":\s*([0-9]+)/i', $html, $m)) {
                        $intOfficeId = $m[1];
                    }
                }
                if (!empty($intOfficeId)) {
                    $mappings[$uGeoId] = [
                        'name' => $u['nameEn'] ?? '',
                        'token' => $token,
                        'officeId' => $intOfficeId
                    ];
                    @file_put_contents($cacheFile, json_encode($mappings, JSON_PRETTY_PRINT));
                }
            }
        }
        
        if (!empty($intOfficeId)) {
            $officeIds[$intOfficeId] = $u['nameBn'] ?? $u['nameEn'] ?? '';
        }
    }
    
    return $officeIds;
}

if ($termApi !== '') {
        $bdrisHeaders = ['client: bris'];

        if (preg_match('/^\d+$/', $termApi)) {
            $appId = $termApi;
            $enc = '';

            $respTry = $proxy->fetch('https://bdris.gov.bd/api/br/application/details/' . urlencode($appId), 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications/search', $bdrisHeaders);
            if (($respTry['status'] ?? 0) === 200) {
                $j = $proxy->parseResponse($respTry);
                $enc = $extractEncryptedId($j);
            }

            if ($enc === '') {
                $respTry = $proxy->fetch('https://bdris.gov.bd/api/br/info/application/' . urlencode($appId), 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications/search', $bdrisHeaders);
                if (($respTry['status'] ?? 0) === 200) {
                    $j = $proxy->parseResponse($respTry);
                    $enc = $extractEncryptedId($j);
                }
            }

            if ($enc === '') {
                $upazilaOffices = getActiveUpazilaOfficeIds($proxy);
                $searchOfficeIds = [];
                $resolvedIntOfficeId = getIntegerOfficeId($proxy, $officeId);
                if ($resolvedIntOfficeId !== '') {
                    $searchOfficeIds[$resolvedIntOfficeId] = 'Current Office';
                }
                foreach ($upazilaOffices as $oId => $oName) {
                    $searchOfficeIds[$oId] = $oName;
                }
                
                // We only scan status 'ALL' first to make it extremely fast (~1s per office).
                // If that fails, we can try other statuses as fallback.
                $statusTry = ['ALL'];
                
                foreach ($searchOfficeIds as $oId => $oName) {
                    foreach ($statusTry as $st) {
                        $params = [
                            'status' => $st,
                            'draw' => 1,
                            'start' => 0,
                            'length' => 25,
                            'search[value]' => $appId,
                            'search[regex]' => 'false',
                            'order[0][column]' => 1,
                            'order[0][dir]' => 'desc',
                            'order[0][name]' => ''
                        ];
                        $params['officeId'] = $oId;
                        
                        $respTry = $proxy->fetch('https://bdris.gov.bd/api/br/applications/search', 'GET', $params, false, 'https://bdris.gov.bd/admin/br/applications/search', $bdrisHeaders);
                        $trimBody = strtolower(ltrim($respTry['body'] ?? ''));
                        $isHtml = ($trimBody !== '' && (strpos($trimBody, '<!doctype') === 0 || strpos($trimBody, '<html') === 0));
                        
                        if (($respTry['status'] ?? 0) === 200 && !$isHtml) {
                            $j = $proxy->parseResponse($respTry);
                            $rows = $j['data'] ?? [];
                            if (is_array($rows)) {
                                foreach ($rows as $row) {
                                    $rid = isset($row['id']) ? (string)$row['id'] : '';
                                    if ($rid !== '' && $rid === (string)$appId) {
                                        $enc = $extractEncryptedId($row);
                                        break 3;
                                    }
                                }
                            }
                        }
                    }
                }
            }


            if ($enc !== '') {
                $termApi = $enc;
            }
        }

        $response = null;
        foreach ($tryUrls as $u) {
            $referer = 'https://bdris.gov.bd/admin/br/applications/search';

            $response = $proxy->fetch($u, 'GET', ['data' => $termApi], false, $referer, $bdrisHeaders);

            // Log for debug
            $status = $response['status'] ?? 0;
            $bodyText0 = (string)($response['body'] ?? '');
            $bodyLen = strlen($bodyText0);
            $trim0 = strtolower(ltrim($bodyText0));
            $isHtml = ($trim0 !== '' && (strpos($trim0, '<!doctype') === 0 || strpos($trim0, '<html') === 0));
            $is404 = (stripos($bodyText0, '<title>BDRIS| Page not found</title>') !== false || stripos($bodyText0, 'Page not found') !== false);
            $debugLog[] = [
                'url' => $u,
                'status' => $status,
                'result' => ($status === 200 && !$is404 && !$isHtml) ? 'Success' : ($is404 ? '404 (Soft)' : ($isHtml ? 'HTML (Blocked/Login)' : 'Fail')),
                'len' => $bodyLen
            ];

            if ($status === 200) {
                // Check if 404 disguised as 200
                if (!$is404 && !$isHtml) {
                    break;
                }
            }
        }
        $allSoft404 = false;
        if (!empty($debugLog)) {
            $allSoft404 = true;
            foreach ($debugLog as $logItem) {
                if ($logItem['result'] !== '404 (Soft)') {
                    $allSoft404 = false;
                    break;
                }
            }
        }
        if ($allSoft404) {
            $error = 'BDRIS সাইটে ডুপ্লিকেট সার্চের URL "Page not found" দেখাচ্ছে। সম্ভবত নতুন আপডেটে এই সার্ভিস পরিবর্তন হয়েছে।';
        } elseif (($response['status'] ?? 0) === 200) {
            $data = $proxy->parseResponse($response);
            if ($data) {
                // Normalize XML structure to match expected JSON structure
                if (isset($data['data']['data'])) {
                     // XML DataTableResponseEntity structure
                     $list = $data['data']['data'];
                     // If single item, it might be associative, wrap it
                     if (isset($list['id'])) {
                         $list = [$list];
                     }
                     $results = [
                         'recordsTotal' => $data['recordsTotal'] ?? count($list),
                         'data' => $list
                     ];
                } else {
                    $results = $data;
                }
            } else {
                $bodyText = $response['body'] ?? '';
                if (stripos($bodyText, 'requested URL was rejected') !== false) {
                    $error = '&#2480;&#2495;&#2453;&#2507;&#2527;&#2503;&#2488;&#2509;&#2463; &#2476;&#2509;&#2482;&#2453; &#2453;&#2480;&#2494; &#2489;&#2527;&#2503;&#2459;&#2503;&#2404; &#2453;&#2497;&#2453;&#2495;, &#2480;&#2503;&#2475;&#2494;&#2480;&#2494;&#2480; &#2451; &#2437;&#2480;&#2495;&#2460;&#2495;&#2472; &#2464;&#2495;&#2453; &#2453;&#2480;&#2503; &#2438;&#2476;&#2494;&#2480; &#2458;&#2503;&#2487;&#2509;&#2463;&#2494; &#2453;&#2480;&#2497;&#2472;&#2404;';
                } elseif (stripos($bodyText, '<title>Login</title>') !== false || stripos($bodyText, 'login-page') !== false) {
                    $error = 'BDRIS &#2488;&#2503;&#2486;&#2472; &#2474;&#2494;&#2451;&#2527;&#2494; &#2479;&#2494;&#2527;&#2472;&#2495; &#2476;&#2494; &#2447;&#2453;&#2509;&#2488;&#2474;&#2494;&#2527;&#2494;&#2480; &#2489;&#2527;&#2503;&#2459;&#2503;&#2404; &#2437;&#2472;&#2497;&#2455;&#2509;&#2480;&#2489; &#2453;&#2480;&#2503; &#2476;&#2509;&#2480;&#2494;&#2441;&#2460;&#2494;&#2480; &#2447;&#2453;&#2509;&#2488;&#2463;&#2503;&#2472;&#2486;&#2472; &#2470;&#2495;&#2527;&#2503; &#2438;&#2476;&#2494;&#2480; &#2453;&#2494;&#2472;&#2503;&#2453;&#2509;&#2463; &#2453;&#2480;&#2497;&#2472;&#2404;';
                } else {
                    if (preg_match('/^\d+$/', (string)$termInput) && $termApi !== (string)$termInput) {
                        $error = 'JSON &#2465;&#2494;&#2463;&#2494; &#2474;&#2494;&#2451;&#2527;&#2494; &#2479;&#2494;&#2527;&#2472;&#2495;&#2404;';
                    } elseif (preg_match('/^\d+$/', (string)$termInput)) {
                        $error = '&#2437;&#2476;&#2503;&#2470;&#2472; &#2472;&#2478;&#2509;&#2476;&#2480; &#2470;&#2495;&#2527;&#2503; &#2454;&#2497;&#2433;&#2460;&#2494; &#2489;&#2509;&#2479;&#2503; &#2472;&#2494;&#2404; &#2437;&#2472;&#2497;&#2455;&#2509;&#2480;&#2489; &#2453;&#2480;&#2503; &#2478;&#2494;&#2472;&#2497;&#2527;&#2494;&#2482; &#2488;&#2503;&#2486;&#2472; Reconnect &#2453;&#2480;&#2503; &#2438;&#2476;&#2494;&#2480; &#2458;&#2503;&#2487;&#2509;&#2463;&#2494; &#2453;&#2480;&#2497;&#2472;&#2404;';
                    } else {
                    $error = 'JSON &#2465;&#2494;&#2463;&#2494; &#2474;&#2494;&#2451;&#2527;&#2494; &#2479;&#2494;&#2527;&#2472;&#2495;&#2404;';
                    }
                }
            }
        } else {
            if (!$allSoft404) {
                $bodyText = $response['body'] ?? '';
                if (stripos($bodyText, '<title>Login</title>') !== false || stripos($bodyText, 'login-page') !== false) {
                    $error = 'BDRIS &#2488;&#2503;&#2486;&#2472; &#2474;&#2494;&#2451;&#2527;&#2494; &#2479;&#2494;&#2527;&#2472;&#2495; &#2476;&#2494; &#2447;&#2453;&#2509;&#2488;&#2474;&#2494;&#2527;&#2494;&#2480; &#2489;&#2527;&#2503;&#2459;&#2503;&#2404; &#2437;&#2472;&#2497;&#2455;&#2509;&#2480;&#2489; &#2453;&#2480;&#2503; &#2476;&#2509;&#2480;&#2494;&#2441;&#2460;&#2494;&#2480; &#2447;&#2453;&#2509;&#2488;&#2463;&#2503;&#2472;&#2486;&#2472; &#2470;&#2495;&#2527;&#2503; &#2438;&#2476;&#2494;&#2480; &#2453;&#2494;&#2472;&#2503;&#2453;&#2509;&#2463; &#2453;&#2480;&#2497;&#2472;&#2404; <a href="verify_system.php" class="btn btn-sm btn-warning">Check Connection</a>';
                } else {
                    $error = '&#2482;&#2494;&#2439;&#2477; &#2465;&#2494;&#2463;&#2494; &#2438;&#2472;&#2468;&#2503; &#2488;&#2478;&#2488;&#2509;&#2479;&#2494; &#2489;&#2527;&#2503;&#2459;&#2503; (HTTP ' . ($response['status'] ?? 0) . '). <a href="verify_system.php" class="btn btn-sm btn-warning">Check Connection</a>';
                }
            }
        }
    }
?>

<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card mt-4">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0">Possible Duplicate</h4>
            </div>
            <div class="card-body">
                <form action="" method="POST">
                    <div class="mb-3">
                        <label for="search_term" class="form-label">অনুসন্ধান (আবেদন নম্বর বা Encrypted ID)</label>
                        <input type="text" class="form-control" id="search_term" name="search_term" value="<?php echo htmlspecialchars($termInput ?? ''); ?>" placeholder="আবেদন নম্বর বা encrypted data" required>
                    </div>
                    <div class="mb-3">
                        <label for="office_id" class="form-label">অফিস আইডি (স্বয়ংক্রিয়ভাবে ক্যাশ থেকে নেওয়া হবে)</label>
                        <input type="text" class="form-control" id="office_id" name="officeId" value="<?php echo htmlspecialchars($officeId ?? ''); ?>" placeholder="যেমন: ৪২৬">
                        <div class="form-text text-muted">সরাসরি ইনপুট না দিলে পূর্বের নির্বাচিত ইউনিয়ন/পৌরসভার একটিভ অফিস আইডি ব্যবহার করা হবে।</div>
                    </div>
                    <button type="submit" class="btn btn-primary">যাচাই করুন</button>
                    <a href="index.php" class="btn btn-secondary">ফিরে যান</a>
                </form>
            </div>
        </div>
    </div>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger mt-3"><?php echo $error; ?></div>
    
    <!-- Debug Output -->
    <div class="card mt-3">
        <div class="card-header bg-warning text-dark">URL Debug Report</div>
        <div class="card-body">
            <ul>
            <?php foreach ($debugLog as $log): ?>
                <li>
                    <strong><?php echo htmlspecialchars($log['url']); ?></strong><br>
                    Status: <?php echo $log['status']; ?> | Result: <?php echo $log['result']; ?> | Size: <?php echo $log['len']; ?> bytes
                </li>
            <?php endforeach; ?>
            </ul>
        </div>
    </div>

    <?php if (isset($response['body'])): ?>
        <div class="card mt-3">
            <div class="card-header">Last Raw Response</div>
            <div class="card-body"><pre><?php echo htmlspecialchars($response['body']); ?></pre></div>
        </div>
    <?php endif; ?>
<?php endif; ?>

<?php if ($results): ?>
<div class="container-fluid mt-4">
    <div class="card">
        <div class="card-header bg-white border-bottom-0">
            <h5 class="text-info">&#2488;&#2478;&#2509;&#2477;&#2494;&#2476;&#2509;&#2479; &#2465;&#2497;&#2474;&#2509;&#2482;&#2495;&#2453;&#2503;&#2463;&#2488;&#2478;&#2497;&#2489;</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped table-hover mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th>&#2460;&#2472;&#2509;&#2478; &#2472;&#2495;&#2476;&#2472;&#2509;&#2471;&#2472; &#2472;&#2478;&#2509;&#2476;&#2480;</th>
                            <th>&#2460;&#2472;&#2509;&#2478; &#2468;&#2494;&#2480;&#2495;&#2454;</th>
                            <th>&#2472;&#2495;&#2476;&#2472;&#2509;&#2471;&#2495;&#2468; &#2476;&#2509;&#2479;&#2453;&#2509;&#2468;&#2495;&#2480; &#2472;&#2494;&#2478;</th>
                            <th>&#2474;&#2495;&#2468;&#2494;&#2480; &#2472;&#2494;&#2478;</th>
                            <th>&#2478;&#2494;&#2468;&#2494;&#2480; &#2472;&#2494;&#2478;</th>
                            <th>&#2437;&#2475;&#2495;&#2488;&#2503;&#2480; &#2472;&#2494;&#2478;</th>
                            <th>&#2437;&#2499;&#2494;&#2453;&#2486;&#2472;</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $list = $results['data'] ?? [];
                        if (empty($list)) {
                            if (isset($results['birthRegistrationNumber']) || isset($results['ubrn'])) {
                                $list = [$results];
                            } elseif (isset($results[0]) && is_array($results[0])) {
                                $list = $results;
                            }
                        }
                        foreach ($list as $row): 
                        ?>
                        <tr>
                            <td><?php echo htmlspecialchars($row['birthRegistrationNumber'] ?? $row['ubrn'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($row['personBirthDate'] ?? $row['dateOfBirth'] ?? ''); ?></td>
                            <td>
                                <div><?php echo htmlspecialchars($row['personNameBn'] ?? ''); ?></div>
                            </td>
                            <td>
                                <div><?php echo htmlspecialchars($row['fatherNameBn'] ?? ''); ?></div>
                            </td>
                            <td>
                                <div><?php echo htmlspecialchars($row['motherNameBn'] ?? ''); ?></div>
                            </td>
                            <td><?php echo htmlspecialchars($row['officeNameBn'] ?? ''); ?></td>
                            <td>
                                <form action="search-birth.php" method="POST" target="_blank" class="d-inline">
                                    <input type="hidden" name="birth_reg_no" value="<?php echo htmlspecialchars($row['birthRegistrationNumber'] ?? $row['ubrn'] ?? ''); ?>">
                                    <input type="hidden" name="dob" value="<?php echo htmlspecialchars($row['personBirthDate'] ?? $row['dateOfBirth'] ?? ''); ?>">
                                    <button type="submit" class="btn btn-sm btn-info text-white rounded-circle">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <?php if (isset($results['recordsTotal'])): ?>
            <div class="p-3 text-muted">
                Showing <?php echo count($list); ?> entries (Total: <?php echo $results['recordsTotal']; ?>)
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="card mt-3">
        <div class="card-header">
            <button class="btn btn-warning btn-sm" type="button" data-bs-toggle="collapse" data-bs-target="#rawJson" aria-expanded="false">
                Show Raw JSON
            </button>
        </div>
        <div class="collapse" id="rawJson">
            <div class="card-body">
                <pre><?php echo htmlspecialchars(json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?></pre>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

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