<?php
/**
 * register-by-app-id.php
 * আবেদন নম্বর দিয়ে সার্চ → অটো অফিস সিলেক্ট → স্ট্যাটাস + BRN/ডুপ্লিকেট
 */
ob_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once 'includes/ProxyHelper.php';

$proxy     = new ProxyHelper();
$appId     = isset($_GET['app_id']) ? trim(preg_replace('/[^0-9]/', '', (string)$_GET['app_id'])) : '';
$error     = null;
$appData   = null;
$dupData   = null;
$officeId  = '';
$foundOffice = '';
$searchDone  = false;

// ─── Helper: encrypted ID extractor ───────────────────────────────────────
$extractEncryptedId = function($val) use (&$extractEncryptedId) {
    if (is_array($val)) {
        foreach (['encryptedId','encryptedID','encrypted_id','encryptedApplicationId'] as $k) {
            if (!empty($val[$k]) && is_string($val[$k])) return trim($val[$k]);
        }
        foreach ($val as $v) {
            $r = $extractEncryptedId($v);
            if ($r !== '') return $r;
        }
    }
    return '';
};

// ─── Helper: is login page? ────────────────────────────────────────────────
function isLoginPage($body) {
    $s = strtolower((string)$body);
    return strpos($s, '<title>login</title>') !== false || strpos($s, 'login-page') !== false;
}

// ─── Helper: resolve active office ID ─────────────────────────────────────
function resolveOfficeId($proxy) {
    $cacheFile = $proxy->getActiveOfficeFile();
    $token = '';
    if (file_exists($cacheFile)) {
        $token = trim((string)file_get_contents($cacheFile));
    }
    if ($token === '') {
        $resp = $proxy->fetch('https://bdris.gov.bd/br/application', 'GET', [], false, 'https://bdris.gov.bd/');
        $body = $resp['body'] ?? '';
        if (preg_match('/\/admin\/br\/applications\/search\?data=([A-Za-z0-9_\-]+)/i', $body, $m)) {
            $token = $m[1];
        }
        if ($token !== '') @file_put_contents($cacheFile, $token);
    }
    // If token is numeric → it's already an integer office ID
    if (ctype_digit($token)) return $token;
    // Otherwise resolve to integer
    if ($token !== '') {
        $resolved = $proxy->getIntegerOfficeId($token);
        if ($resolved !== '') {
            @file_put_contents($cacheFile, $resolved);
            return $resolved;
        }
    }
    return $token;
}

// ─── Helper: search across upazila offices ─────────────────────────────────
function searchAcrossOffices($proxy, $appId, $primaryOfficeId, $bdrisHeaders) {
    // First try primary office
    $offices = [];
    if ($primaryOfficeId !== '') {
        $offices[$primaryOfficeId] = 'বর্তমান অফিস';
    }

    // Also get upazila siblings
    $upazilaFile = __DIR__ . '/cookies/active_upazila.txt';
    $upazilaGeoId = '';
    if (file_exists($upazilaFile)) $upazilaGeoId = trim(file_get_contents($upazilaFile));
    
    if ($upazilaGeoId === '') {
        $resp = $proxy->fetch('https://bdris.gov.bd/br/application', 'GET', [], false, 'https://bdris.gov.bd/');
        if (preg_match('/geoId\s*:\s*([0-9]+)/i', $resp['body'] ?? '', $m)) {
            $upazilaGeoId = $m[1];
            @file_put_contents($upazilaFile, $upazilaGeoId);
        }
    }

    if ($upazilaGeoId !== '') {
        $cacheFile = __DIR__ . "/cache/geo/geo_{$upazilaGeoId}_officeAddr_3_3.json";
        $unions = [];
        if (file_exists($cacheFile)) {
            $gd = json_decode(file_get_contents($cacheFile), true);
            $unions = $gd['geoObject'] ?? $gd ?? [];
        } else {
            $apiH = ['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";
            $rg = $proxy->fetch($urlGeo, 'GET', [], false, 'https://bdris.gov.bd/', $apiH);
            if (($rg['status'] ?? 0) === 200) {
                @mkdir(__DIR__ . '/cache/geo', 0755, true);
                @file_put_contents($cacheFile, $rg['body']);
                $gd = json_decode($rg['body'], true);
                $unions = $gd['geoObject'] ?? $gd ?? [];
            }
        }

        $mappCacheFile = __DIR__ . '/cache/office_mappings.json';
        $mappings = file_exists($mappCacheFile) ? (json_decode(file_get_contents($mappCacheFile), true) ?: []) : [];

        if (is_array($unions)) {
            $apiH2 = ['Accept: application/json, text/plain, */*','X-Requested-With: XMLHttpRequest','client: bris'];
            foreach ($unions as $u) {
                $uGeoId = $u['id'] ?? null;
                if (empty($uGeoId)) continue;
                $intOId = $mappings[$uGeoId]['officeId'] ?? '';
                if ($intOId === '') {
                    $urlToken = "https://bdris.gov.bd/api/office/find-office-geo-projection-by-geo-id/{$uGeoId}?geoGroup=officeAddr&geoOrder=4&geoType=5";
                    $rt = $proxy->fetch($urlToken, 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications', $apiH2);
                    $td = json_decode($rt['body'] ?? '', true);
                    $tok2 = $td['geoObject']['officeId'] ?? '';
                    if ($tok2 !== '') {
                        $rp = $proxy->fetch("https://bdris.gov.bd/admin/br/applications/search?data=" . urlencode($tok2), 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications');
                        $html = $rp['body'] ?? '';
                        if (preg_match('/(?:const|var|let)\s+officeId\s*=\s*([0-9]+)/i', $html, $m2)) $intOId = $m2[1];
                        if (!$intOId && preg_match('/"officeId":\s*([0-9]+)/i', $html, $m2)) $intOId = $m2[1];
                        if ($intOId) {
                            $mappings[$uGeoId] = ['name' => $u['nameEn'] ?? '', 'token' => $tok2, 'officeId' => $intOId];
                            @file_put_contents($mappCacheFile, json_encode($mappings, JSON_PRETTY_PRINT));
                        }
                    }
                }
                if ($intOId !== '' && $intOId !== $primaryOfficeId) {
                    $offices[$intOId] = $u['nameBn'] ?? $u['nameEn'] ?? "অফিস {$intOId}";
                }
            }
        }
    }

    // Try searching each office
    foreach ($offices as $oId => $oName) {
        $params = [
            'status' => 'ALL', 'draw' => 1, 'start' => 0, 'length' => 25,
            'search[value]' => $appId, 'search[regex]' => 'false',
            'order[0][column]' => 1, 'order[0][dir]' => 'desc', 'order[0][name]' => '',
            'officeId' => $oId
        ];
        // Try to get office token
        $oToken = $proxy->getOfficeToken($oId);
        if ($oToken !== '') $params['data'] = $oToken;

        $refUrl = 'https://bdris.gov.bd/admin/br/applications/search' . ($oToken ? '?data=' . urlencode($oToken) : '');
        $resp = $proxy->fetch('https://bdris.gov.bd/api/br/applications/search', 'GET', $params, false, $refUrl, $bdrisHeaders, 20, 1, 300);
        
        if (isLoginPage($resp['body'] ?? '')) continue;
        if (($resp['status'] ?? 0) !== 200) continue;

        $j = $proxy->parseResponse($resp);
        if (!$j || !isset($j['data'])) continue;

        foreach ($j['data'] as $row) {
            $rid = (string)($row['id'] ?? $row['applicationNo'] ?? '');
            if ($rid === (string)$appId) {
                return ['row' => $row, 'officeId' => $oId, 'officeName' => $oName];
            }
        }
    }
    return null;
}

// ═══════════════════════════════════════════════════════════
// MAIN LOGIC
// ═══════════════════════════════════════════════════════════
if ($appId !== '') {
    $searchDone = true;
    $bdrisHeaders = [
        'client: bris',
        'Accept: application/json, text/javascript, */*; q=0.01',
        'X-Requested-With: XMLHttpRequest',
    ];
    $csrf = $proxy->getCsrfToken();
    if ($csrf) $bdrisHeaders[] = 'X-CSRF-TOKEN: ' . $csrf;

    $relayNeeded = false;
    $relayUrl = '';
    
    // Step 0: Check Relay Cache (key = appId)
    $cacheFile = __DIR__ . '/cache/relay_' . $appId . '.json';
    if (file_exists($cacheFile)) {
        $cdata = json_decode(file_get_contents($cacheFile), true);
        if ($cdata && (time() - ($cdata['time'] ?? 0) < 300)) { // 5 min cache
            $raw = $cdata['data'];
            // বিভিন্ন ফর্ম্যাট হ্যান্ডেল
            if (isset($raw['data']) && is_array($raw['data'])) $raw = $raw['data'];
            if (is_array($raw) && !empty($raw)) {
                $appData = $raw;
                $foundOffice = 'relay থেকে পাওয়া';
                $searchDone = true;
            }
        }
    }

    // ✅ Step 1: সরাসরি global endpoints দিয়ে চেষ্টা (কোনো office context না দিয়ে)
    $encryptedId = '';
    $globalRef = 'https://bdris.gov.bd/admin/br/applications/search';

    // প্রথম: details endpoint
    $r1 = $proxy->fetch('https://bdris.gov.bd/api/br/application/details/' . urlencode($appId), 'GET', [], false, $globalRef, $bdrisHeaders);
    if (!isLoginPage($r1['body'] ?? '') && ($r1['status'] ?? 0) === 200) {
        $j1 = $proxy->parseResponse($r1);
        $encryptedId = $extractEncryptedId($j1);
        if ($encryptedId === '' && is_array($j1) && !empty($j1)) {
            $appData = $j1;
        }
    }

    // দ্বিতীয়: info endpoint
    if ($encryptedId === '' && !$appData) {
        $r2 = $proxy->fetch('https://bdris.gov.bd/api/br/info/application/' . urlencode($appId), 'GET', [], false, $globalRef, $bdrisHeaders);
        if (!isLoginPage($r2['body'] ?? '') && ($r2['status'] ?? 0) === 200) {
            $j2 = $proxy->parseResponse($r2);
            $encryptedId = $extractEncryptedId($j2);
            if ($encryptedId === '' && is_array($j2) && !empty($j2)) {
                $appData = $j2;
            }
        }
    }

    // তৃতীয়: application search API globally (office token ছাড়া)
    if ($encryptedId === '' && !$appData) {
        $globalSearchParams = [
            'status'      => 'ALL', 'draw' => 1, 'start' => 0, 'length' => 25,
            'search[value]' => $appId, 'search[regex]' => 'false',
            'order[0][column]' => 1, 'order[0][dir]' => 'desc', 'order[0][name]' => ''
        ];
        $rg = $proxy->fetch('https://bdris.gov.bd/api/br/applications/search', 'GET', $globalSearchParams, false, $globalRef, $bdrisHeaders, 20, 1, 300);
        if (!isLoginPage($rg['body'] ?? '') && ($rg['status'] ?? 0) === 200) {
            $jg = $proxy->parseResponse($rg);
            if ($jg && isset($jg['data'])) {
                foreach ($jg['data'] as $row) {
                    $rid = (string)($row['id'] ?? $row['applicationNo'] ?? '');
                    if ($rid === (string)$appId) {
                        $encryptedId = $extractEncryptedId($row);
                        $foundOffice = 'যেকোনো ইউনিয়ন';
                        if ($encryptedId === '') $appData = $row;
                        break;
                    }
                }
            }
        }
    }

    // ✅ Step 2: যদি এখনো পাওয়া যায়নি, office context দিয়ে চেষ্টা
    $officeId = resolveOfficeId($proxy);
    if ($encryptedId === '' && !$appData) {
        $searchResult = searchAcrossOffices($proxy, $appId, $officeId, $bdrisHeaders);
        if ($searchResult) {
            $encryptedId = $extractEncryptedId($searchResult['row']);
            $foundOffice = $searchResult['officeName'] . ' (ID: ' . $searchResult['officeId'] . ')';
            if ($encryptedId === '') {
                $appData = $searchResult['row'];
            }
            $officeId = $searchResult['officeId'];
        }
    }

    // ✅ Step 3: encrypted ID দিয়ে পুরো তথ্য আনো
    if ($encryptedId !== '' && !$appData) {
        $officeToken = $proxy->getOfficeToken($officeId);
        $refUrl = 'https://bdris.gov.bd/admin/br/applications/search' . ($officeToken ? '?data=' . urlencode($officeToken) : '');

        if ($officeId !== '') {
            $proxy->fetch('https://bdris.gov.bd/api/office/permission?officeId=' . $officeId, 'GET', [], false, $refUrl, $bdrisHeaders);
        }

        $dr = $proxy->fetch('https://bdris.gov.bd/api/application/details?data=' . urlencode($encryptedId), 'GET', [], false, $refUrl, $bdrisHeaders);
        if (!isLoginPage($dr['body'] ?? '') && ($dr['status'] ?? 0) === 200) {
            $appData = $proxy->parseResponse($dr);
        }
    }

    // ✅ Step 4: রেজিস্টার্ড হলে BRN তথ্য + ডুপ্লিকেট
    if ($appData) {
        $brn = $appData['birthRegistrationNumber'] ?? $appData['personBrn'] ?? $appData['ubrn'] ?? $appData['brn'] ?? '';
        if ($brn === '' && isset($appData['data']) && is_array($appData['data'])) {
            $brn = $appData['data']['birthRegistrationNumber'] ?? $appData['data']['personBrn'] ?? '';
        }
        
        $status = strtolower(trim((string)($appData['status'] ?? '')));
        $isReg = (strpos($status, 'register') !== false || strpos($status, 'নিবন্ধিত') !== false || strpos($status, 'approved') !== false);

        if ($brn === '' && $isReg) {
            $dob = $appData['personBirthDate'] ?? $appData['dateOfBirth'] ?? '';
            $byear = '';
            if (preg_match('/([0-9]{4})/', $dob, $m)) $byear = $m[1];
            
            $findBrn = function($data, $y) use (&$findBrn) {
                if (is_array($data)) {
                    foreach ($data as $v) {
                        $r = $findBrn($v, $y);
                        if ($r !== '') return $r;
                    }
                } elseif (is_string($data) && preg_match('/^([0-9]{4})[0-9]{13}$/', trim($data), $m)) {
                    if ($y === '' || $m[1] === $y) return trim($data);
                }
                return '';
            };
            
            $brn = $findBrn($appData, $byear);

            if ($brn === '') {
                $r_info = $proxy->fetch('https://bdris.gov.bd/api/br/info/application/' . urlencode($appId), 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications/search', $bdrisHeaders);
                if (($r_info['status'] ?? 0) === 200) {
                    $j_info = $proxy->parseResponse($r_info);
                    if ($j_info) {
                        $brn = $j_info['birthRegistrationNumber'] ?? $j_info['personBrn'] ?? ($j_info['data']['birthRegistrationNumber'] ?? '');
                        if ($brn === '') $brn = $findBrn($j_info, $byear);
                    }
                }
            }
            if ($brn === '') {
                $r_det = $proxy->fetch('https://bdris.gov.bd/api/br/application/details/' . urlencode($appId), 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications/search', $bdrisHeaders);
                if (($r_det['status'] ?? 0) === 200) {
                    $j_det = $proxy->parseResponse($r_det);
                    if ($j_det) {
                        $brn = $j_det['birthRegistrationNumber'] ?? $j_det['personBrn'] ?? ($j_det['data']['birthRegistrationNumber'] ?? '');
                        if ($brn === '') $brn = $findBrn($j_det, $byear);
                    }
                }
            }
        }

        // DEBUG: Save exactly what we ended up with to a log file
        $dbg = [
            'appId' => $appId,
            'status' => $status,
            'isReg' => $isReg,
            'found_brn' => $brn,
            'byear' => $byear ?? '',
            'appData_keys' => array_keys($appData),
            'appData' => $appData
        ];
        if (isset($r_info)) $dbg['r_info_status'] = $r_info['status'] ?? 0;
        if (isset($r_det)) $dbg['r_det_status'] = $r_det['status'] ?? 0;
        @file_put_contents(__DIR__ . '/debug_brn.txt', json_encode($dbg, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        if (strpos($status, 'duplicate') !== false || strpos($status, 'ডুপ্লিকেট') !== false || $brn === '') {
            if ($encryptedId !== '') {
                $dupResp = $proxy->fetch(
                    'https://bdris.gov.bd/api/br/all-possible-duplicates-by-birth-registration-application-id',
                    'GET', ['data' => $encryptedId], false,
                    'https://bdris.gov.bd/admin/br/applications/search', $bdrisHeaders
                );
                if (($dupResp['status'] ?? 0) === 200 && !isLoginPage($dupResp['body'] ?? '')) {
                    $dupRaw = $proxy->parseResponse($dupResp);
                    if ($dupRaw) $dupData = $dupRaw;
                }
            }
        }

        if (!isset($appData['docs'])) {
            $attR = $proxy->fetch('https://bdris.gov.bd/api/br/application/attachments/' . urlencode($appId), 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications/search', $bdrisHeaders);
            if (($attR['status'] ?? 0) === 200) {
                $aj = json_decode($attR['body'], true);
                if (isset($aj['data'])) $appData['docs'] = $aj['data'];
                elseif (isset($aj['attachments'])) $appData['docs'] = $aj['attachments'];
            }
        }
    } elseif (!$error) {
        $st = $r1['status'] ?? 0;
        $b = $r1['body'] ?? '';
        if ($st === 400 || $st === 403 || strpos($b, 'Request Rejected') !== false || strpos($b, 'TSPD_101_DID') !== false) {
            $error = 'BDRIS সার্ভার কানেকশন ব্লক করছে (WAF)। অনুগ্রহ করে কিছুক্ষণ পর আবার চেষ্টা করুন।';
            $relayNeeded = false;
        } elseif (isLoginPage($b)) {
            $error = 'BDRIS সেশন এক্সপায়ার হয়েছে। অনুগ্রহ করে ব্রাউজার এক্সটেনশন দিয়ে পুনরায় সংযুক্ত করুন।';
        } else {
            $error = 'আবেদন নম্বর <strong>' . htmlspecialchars($appId) . '</strong> BDRIS-এ খুঁজে পাওয়া যায়নি। আইডি সঠিক আছে কিনা যাচাই করুন।';
        }
    }
}

// ─── Normalize status ──────────────────────────────────────────────────────
function getStatusBadge($status) {
    $s = strtolower(trim((string)$status));
    if (strpos($s, 'register') !== false || strpos($s, 'নিবন্ধিত') !== false || strpos($s, 'approved') !== false) {
        return ['class' => 'bg-success', 'icon' => '✅', 'label' => $status];
    } elseif (strpos($s, 'duplicate') !== false || strpos($s, 'ডুপ্লিকেট') !== false) {
        return ['class' => 'bg-warning text-dark', 'icon' => '⚠️', 'label' => $status];
    } elseif (strpos($s, 'pending') !== false || strpos($s, 'অপেক্ষমাণ') !== false) {
        return ['class' => 'bg-info text-dark', 'icon' => '⏳', 'label' => $status];
    } elseif (strpos($s, 'reject') !== false || strpos($s, 'প্রত্যাখ্যাত') !== false) {
        return ['class' => 'bg-danger', 'icon' => '❌', 'label' => $status];
    }
    return ['class' => 'bg-secondary', 'icon' => '📋', 'label' => $status ?: 'অজানা'];
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>আবেদন অনুসন্ধান – জন্ম নিবন্ধন অফিস সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #0f4c81;
            --success: #198754;
            --warning-color: #d97706;
        }
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background: linear-gradient(135deg, #e8f0fe 0%, #f0fdf4 100%);
            min-height: 100vh;
        }
        .hero-card {
            background: linear-gradient(135deg, #0f4c81, #1a6fb5);
            border-radius: 18px;
            color: white;
            padding: 2rem;
            box-shadow: 0 10px 40px rgba(15,76,129,0.3);
        }
        .search-box {
            background: white;
            border-radius: 14px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            padding: 1.5rem;
        }
        .search-input {
            font-size: 1.2rem;
            border: 2px solid #dee2e6;
            border-radius: 10px 0 0 10px;
            padding: 0.75rem 1rem;
            transition: border-color 0.2s;
        }
        .search-input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(15,76,129,0.15);
        }
        .search-btn {
            background: linear-gradient(135deg, #0f4c81, #1a6fb5);
            border: none;
            border-radius: 0 10px 10px 0;
            font-size: 1.1rem;
            padding: 0.75rem 1.5rem;
            color: white;
            transition: all 0.2s;
        }
        .search-btn:hover { background: linear-gradient(135deg, #0d3d68, #155ea0); transform: translateY(-1px); }

        /* Status result card */
        .result-card {
            border-radius: 16px;
            box-shadow: 0 6px 24px rgba(0,0,0,0.1);
            overflow: hidden;
            animation: slideUp 0.4s ease;
        }
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(20px); }
            to   { opacity: 1; transform: translateY(0); }
        }
        .result-header {
            padding: 1.25rem 1.5rem;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .result-header.registered   { background: linear-gradient(135deg, #16a34a, #22c55e); color: white; }
        .result-header.duplicate    { background: linear-gradient(135deg, #d97706, #f59e0b); color: white; }
        .result-header.pending      { background: linear-gradient(135deg, #0284c7, #38bdf8); color: white; }
        .result-header.rejected     { background: linear-gradient(135deg, #dc2626, #ef4444); color: white; }
        .result-header.unknown      { background: linear-gradient(135deg, #475569, #64748b); color: white; }

        .status-icon { font-size: 2rem; }
        .info-table { font-size: 0.95rem; }
        .info-table th { width: 38%; background: #f8fafc; font-weight: 600; color: #374151; }
        .info-table td { color: #1f2937; }

        .brn-box {
            background: linear-gradient(135deg, #dcfce7, #bbf7d0);
            border: 2px solid #16a34a;
            border-radius: 12px;
            padding: 1rem 1.5rem;
        }
        .brn-number {
            font-size: 1.4rem;
            font-weight: 700;
            letter-spacing: 1px;
            color: #15803d;
        }
        .visit-btn {
            background: linear-gradient(135deg, #16a34a, #22c55e);
            border: none;
            border-radius: 8px;
            color: white;
            padding: 0.5rem 1.2rem;
            font-weight: 600;
            transition: all 0.2s;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }
        .visit-btn:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(22,163,74,0.4); color: white; }

        /* Duplicate cards */
        .dup-card {
            border: 1px solid #fbbf24;
            border-left: 4px solid #d97706;
            border-radius: 10px;
            background: #fffbeb;
            padding: 1rem;
            margin-bottom: 0.75rem;
            transition: all 0.2s;
        }
        .dup-card:hover { box-shadow: 0 4px 12px rgba(217,119,6,0.2); }
        .dup-brn { font-size: 1.1rem; font-weight: 700; color: #92400e; }

        .office-badge {
            background: #dbeafe;
            color: #1e40af;
            border-radius: 6px;
            padding: 4px 10px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        .loading-spinner {
            display: none;
        }
        .loading-spinner.show { display: inline-block; }
        @media (max-width: 576px) {
            .search-input { font-size: 1rem; }
        }
    </style>
</head>
<body>

<div class="container py-4" style="max-width: 860px;">

    <!-- Hero Header -->
    <div class="hero-card mb-4">
        <div class="d-flex align-items-center gap-3">
            <div style="font-size: 2.5rem;">🔍</div>
            <div>
                <h4 class="mb-1 fw-bold">আবেদন অনুসন্ধান</h4>
                <p class="mb-0 opacity-75">আবেদন নম্বর দিয়ে বর্তমান অবস্থা, BRN এবং ডুপ্লিকেট তথ্য দেখুন</p>
            </div>
            <div class="ms-auto">
                <a href="index.php" class="btn btn-light btn-sm rounded-pill">
                    <i class="fas fa-home me-1"></i> ড্যাশবোর্ড
                </a>
            </div>
        </div>
    </div>

    <!-- Search Box -->
    <div class="search-box mb-4">
        <form method="GET" id="searchForm" onsubmit="showLoader()">
            <label class="form-label fw-semibold text-secondary mb-2">
                <i class="fas fa-file-alt text-primary me-1"></i> আবেদন নম্বর লিখুন
            </label>
            <div class="input-group">
                <input type="text" name="app_id" id="appIdInput"
                       class="search-input form-control"
                       placeholder="যেমন: 261719422"
                       value="<?= htmlspecialchars($appId) ?>"
                       pattern="[0-9]+"
                       title="শুধু সংখ্যা দিন"
                       autofocus required>
                <button class="search-btn" type="submit" id="searchBtn">
                    <span class="loading-spinner spinner-border spinner-border-sm me-1" id="loader"></span>
                    <i class="fas fa-search me-1" id="searchIcon"></i>
                    <span>সার্চ করুন</span>
                </button>
            </div>
            <div class="form-text mt-2 text-muted">
                <i class="fas fa-info-circle me-1"></i>
                অফিস স্বয়ংক্রিয়ভাবে নির্বাচন হবে। সার্চে ৫–১৫ সেকেন্ড লাগতে পারে।
                <?php if ($officeId !== '' && $searchDone): ?>
                    <span class="ms-2 office-badge"><i class="fas fa-building me-1"></i>
                        অফিস আইডি: <?= htmlspecialchars($foundOffice ?: $officeId) ?>
                    </span>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <?php if ($error): ?>
    <!-- Error -->
    <div class="alert alert-danger rounded-3 shadow-sm">
        <i class="fas fa-exclamation-triangle me-2"></i>
        <?= $error ?>
        <div class="mt-2">
            <?php if ($relayNeeded): ?>
            <button class="btn btn-success fw-bold" onclick="openRelay('<?= htmlspecialchars($relayUrl) ?>')">
                <i class="fas fa-external-link-alt"></i> ব্রাউজার থেকে তথ্য নিন
            </button>
            <?php else: ?>
            <a href="verify_system.php" class="btn btn-sm btn-outline-danger">
                <i class="fas fa-plug me-1"></i> সংযোগ যাচাই করুন
            </a>
            <a href="connect-setup.php" class="btn btn-sm btn-warning ms-2">
                <i class="fas fa-sync me-1"></i> রিকানেক্ট
            </a>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($appData):
        $status = $appData['status'] ?? '';
        $brn    = $appData['birthRegistrationNumber'] ?? $appData['personBrn'] ?? '';
        $name   = $appData['personNameBn'] ?? $appData['personNameEn'] ?? '';
        $dob    = $appData['personBirthDate'] ?? $appData['dateOfBirth'] ?? '';
        $encId  = $appData['encryptedId'] ?? $appData['encryptedID'] ?? '';
        $officeName = $appData['officeNameBn'] ?? '';

        $statusL = strtolower($status);
        $isRegistered = (strpos($statusL, 'register') !== false || strpos($statusL, 'নিবন্ধিত') !== false || $brn !== '');
        $isDuplicate  = (strpos($statusL, 'duplicate') !== false || strpos($statusL, 'ডুপ্লিকেট') !== false);

        $headerClass = $isRegistered ? 'registered' : ($isDuplicate ? 'duplicate' : (strpos($statusL,'pending')!==false ? 'pending' : (strpos($statusL,'reject')!==false ? 'rejected' : 'unknown')));
        $badge = getStatusBadge($status);
    ?>

    <!-- ─── Application Result Card ─── -->
    <div class="result-card mb-4">
        <div class="result-header <?= $headerClass ?>">
            <div class="status-icon"><?= $badge['icon'] ?></div>
            <div>
                <div style="font-size:1.1rem; font-weight:700;">আবেদন নং: <?= htmlspecialchars($appId) ?></div>
                <div style="font-size:0.95rem; opacity:0.9;">
                    অবস্থা: <strong><?= htmlspecialchars($status ?: 'তথ্য পাওয়া গেছে') ?></strong>
                </div>
            </div>
            <?php if ($officeName): ?>
            <div class="ms-auto text-end" style="font-size:0.82rem; opacity:0.85;">
                <i class="fas fa-building me-1"></i><?= htmlspecialchars($officeName) ?>
            </div>
            <?php endif; ?>
        </div>

        <div class="p-3">

            <!-- BRN Box (if registered) -->
            <?php if ($brn !== ''): ?>
            <div class="brn-box mb-3 d-flex align-items-center gap-3 flex-wrap">
                <div>
                    <div class="text-success fw-semibold mb-1" style="font-size:0.85rem;">
                        <i class="fas fa-certificate me-1"></i> নতুন জন্ম নিবন্ধন নম্বর (BRN)
                    </div>
                    <div class="brn-number"><?= htmlspecialchars($brn) ?></div>
                </div>
                <div class="ms-auto d-flex gap-2 flex-wrap">
                    <a href="search-birth.php?birth_reg_no=<?= urlencode($brn) ?>&dob=<?= urlencode($dob) ?>"
                       target="_blank" class="visit-btn">
                        <i class="fas fa-external-link-alt"></i> সূত্র ভিজিট
                    </a>
                    <a href="print-certificate.php?brn=<?= urlencode($brn) ?>&dob=<?= urlencode($dob) ?>"
                       target="_blank" class="visit-btn" style="background: linear-gradient(135deg,#0f4c81,#1a6fb5);">
                        <i class="fas fa-print"></i> সনদ প্রিন্ট
                    </a>
                    <button onclick="navigator.clipboard.writeText('<?= addslashes($brn) ?>').then(()=>alert('কপি হয়েছে!'))"
                            class="btn btn-sm btn-outline-success rounded-pill">
                        <i class="fas fa-copy me-1"></i>কপি
                    </button>
                </div>
            </div>
            <?php endif; ?>

            <!-- Application Details Table -->
            <table class="table table-bordered info-table mb-0">
                <?php if ($name): ?>
                <tr><th>আবেদনকারীর নাম</th><td><?= htmlspecialchars($name) ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($appData['personNameEn']) && $appData['personNameEn'] !== $name): ?>
                <tr><th>নাম (ইংরেজি)</th><td><?= htmlspecialchars($appData['personNameEn']) ?></td></tr>
                <?php endif; ?>
                <?php if ($dob): ?>
                <tr><th>জন্ম তারিখ</th><td><?= htmlspecialchars($dob) ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($appData['gender'])): ?>
                <tr><th>লিঙ্গ</th><td><?= htmlspecialchars($appData['gender']) ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($appData['fatherNameBn'])): ?>
                <tr><th>পিতার নাম</th><td><?= htmlspecialchars($appData['fatherNameBn']) ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($appData['motherNameBn'])): ?>
                <tr><th>মাতার নাম</th><td><?= htmlspecialchars($appData['motherNameBn']) ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($appData['dateApplied'])): ?>
                <tr><th>আবেদনের তারিখ</th><td><?= htmlspecialchars($appData['dateApplied']) ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($appData['permAddrFullAddressBn'])): ?>
                <tr><th>স্থায়ী ঠিকানা</th><td><?= htmlspecialchars($appData['permAddrFullAddressBn']) ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($appData['applicantName'])): ?>
                <tr><th>দাখিলকারীর নাম</th><td><?= htmlspecialchars($appData['applicantName']) ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($appData['phone'])): ?>
                <tr><th>মোবাইল নম্বর</th><td><?= htmlspecialchars($appData['phone']) ?></td></tr>
                <?php endif; ?>
            </table>

            <!-- Action Buttons -->
            <div class="mt-3 d-flex gap-2 flex-wrap">
                <a href="print-application.php?app_id=<?= urlencode($appId) ?>"
                   target="_blank" class="btn btn-primary btn-sm rounded-pill">
                    <i class="fas fa-print me-1"></i> আবেদন প্রিন্ট
                </a>
                <?php if (!$isDuplicate): ?>
                <a href="duplicates.php?search_term=<?= urlencode($encId ?: $appId) ?>&officeId=<?= urlencode($officeId) ?>"
                   target="_blank" class="btn btn-warning btn-sm rounded-pill text-dark">
                    <i class="fas fa-copy me-1"></i> ডুপ্লিকেট চেক
                </a>
                <?php endif; ?>
                <?php if ($brn): ?>
                <a href="view-certificate.php?brn=<?= urlencode($brn) ?>&dob=<?= urlencode($dob) ?>"
                   target="_blank" class="btn btn-success btn-sm rounded-pill">
                    <i class="fas fa-eye me-1"></i> সনদ দেখুন
                </a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php endif; // $appData ?>


    <?php
    // ─── Duplicate Results ──────────────────────────────────────────────────
    $dupList = [];
    if ($dupData) {
        if (isset($dupData['data']['data'])) {
            $raw = $dupData['data']['data'];
            $dupList = isset($raw['id']) ? [$raw] : array_values((array)$raw);
        } elseif (isset($dupData['data']) && is_array($dupData['data'])) {
            $dupList = $dupData['data'];
        } elseif (isset($dupData[0])) {
            $dupList = $dupData;
        } elseif (isset($dupData['birthRegistrationNumber'])) {
            $dupList = [$dupData];
        }
    }
    if (!empty($dupList)):
    ?>
    <div class="result-card mb-4">
        <div class="result-header duplicate">
            <div class="status-icon">⚠️</div>
            <div>
                <div style="font-size:1.05rem; font-weight:700;">সম্ভাব্য ডুপ্লিকেট পাওয়া গেছে</div>
                <div style="font-size:0.88rem; opacity:0.9;">মোট: <?= count($dupList) ?> টি সম্ভাব্য ডুপ্লিকেট রেকর্ড</div>
            </div>
        </div>
        <div class="p-3">
            <?php foreach ($dupList as $idx => $dup):
                $dBrn  = $dup['birthRegistrationNumber'] ?? $dup['ubrn'] ?? '';
                $dName = $dup['personNameBn'] ?? '';
                $dDob  = $dup['personBirthDate'] ?? $dup['dateOfBirth'] ?? '';
                $dFather = $dup['fatherNameBn'] ?? '';
                $dMother = $dup['motherNameBn'] ?? '';
                $dOffice = $dup['officeNameBn'] ?? '';
            ?>
            <div class="dup-card">
                <div class="d-flex align-items-start justify-content-between flex-wrap gap-2">
                    <div>
                        <div class="dup-brn mb-1">
                            <i class="fas fa-id-card me-1"></i>
                            BRN: <?= $dBrn ? htmlspecialchars($dBrn) : '<span class="text-muted">N/A</span>' ?>
                        </div>
                        <div class="d-flex flex-wrap gap-3 text-sm" style="font-size:0.9rem;">
                            <?php if ($dName): ?><span><strong>নাম:</strong> <?= htmlspecialchars($dName) ?></span><?php endif; ?>
                            <?php if ($dDob): ?><span><strong>জন্ম:</strong> <?= htmlspecialchars($dDob) ?></span><?php endif; ?>
                            <?php if ($dFather): ?><span><strong>পিতা:</strong> <?= htmlspecialchars($dFather) ?></span><?php endif; ?>
                            <?php if ($dMother): ?><span><strong>মাতা:</strong> <?= htmlspecialchars($dMother) ?></span><?php endif; ?>
                        </div>
                        <?php if ($dOffice): ?>
                        <div class="mt-1"><span class="office-badge"><i class="fas fa-building me-1"></i><?= htmlspecialchars($dOffice) ?></span></div>
                        <?php endif; ?>
                    </div>
                    <?php if ($dBrn && !empty($dDob)): ?>
                    <div class="d-flex gap-1 flex-wrap mt-1">
                        <a href="search-birth.php?birth_reg_no=<?= urlencode($dBrn) ?>&dob=<?= urlencode($dDob) ?>"
                           target="_blank" class="visit-btn" style="font-size:0.82rem; padding: 4px 10px;">
                            <i class="fas fa-external-link-alt"></i> সূত্র
                        </a>
                        <a href="view-certificate.php?brn=<?= urlencode($dBrn) ?>&dob=<?= urlencode($dDob) ?>"
                           target="_blank" class="btn btn-sm btn-outline-warning rounded-pill" style="font-size:0.82rem;">
                            <i class="fas fa-eye"></i> সনদ
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>


    <?php if (!$searchDone): ?>
    <!-- Quick Guide when no search done -->
    <div class="row g-3 mt-1">
        <div class="col-md-4">
            <div class="card h-100 border-0 shadow-sm text-center p-3">
                <div style="font-size:2rem;">📋</div>
                <h6 class="fw-bold mt-2">আবেদনের অবস্থা</h6>
                <p class="text-muted small mb-0">আবেদন নম্বর দিলে বর্তমান স্ট্যাটাস জানা যাবে।</p>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card h-100 border-0 shadow-sm text-center p-3">
                <div style="font-size:2rem;">🎫</div>
                <h6 class="fw-bold mt-2">BRN ও সূত্র</h6>
                <p class="text-muted small mb-0">রেজিস্টার হলে নতুন নিবন্ধন নম্বর ও ভিজিট লিংক দেখাবে।</p>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card h-100 border-0 shadow-sm text-center p-3">
                <div style="font-size:2rem;">⚠️</div>
                <h6 class="fw-bold mt-2">ডুপ্লিকেট তথ্য</h6>
                <p class="text-muted small mb-0">পসিবল ডুপ্লিকেট হলে সেগুলোর আংশিক বিবরণ দেখাবে।</p>
            </div>
        </div>
    </div>
    <?php endif; ?>

</div><!-- /container -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function showLoader() {
    document.getElementById('loader').classList.add('show');
    document.getElementById('searchIcon').style.display = 'none';
    document.getElementById('searchBtn').disabled = true;
}
// Auto-focus and numeric only
document.getElementById('appIdInput').addEventListener('input', function() {
    this.value = this.value.replace(/[^0-9]/g, '');
});

function openRelay(url) {
    const w = 600, h = 450;
    const left = (screen.width/2)-(w/2);
    const top = (screen.height/2)-(h/2);
    const popup = window.open(url, 'BDRIS Relay', `width=${w},height=${h},top=${top},left=${left}`);

    // পপআপ বন্ধ হলে reload করো
    const timer = setInterval(function() {
        if (popup && popup.closed) {
            clearInterval(timer);
            // reload সাথে app_id param রাখো
            const currentUrl = new URL(window.location.href);
            window.location.href = currentUrl.href;
        }
    }, 800);

    // message आসলে সাথে সাথে reload
    window.addEventListener('message', function handler(e) {
        if (e.data && e.data.type === 'bdris_result') {
            clearInterval(timer);
            window.removeEventListener('message', handler);
            // সংক্ষিপ্ত মেসেজ দেখাও
            document.querySelector('.alert-danger')?.remove();
            const info = document.createElement('div');
            info.className = 'alert alert-success rounded-3';
            info.innerHTML = '<i class="fas fa-check-circle me-2"></i> তথ্য পাওয়া গেছে! পেজ রিফ্রেশ হচ্ছে...';
            document.querySelector('.container')?.prepend(info);
            setTimeout(() => {
                const url = new URL(window.location.href);
                window.location.href = url.href;
            }, 800);
        } else if (e.data && e.data.type === 'bdris_error') {
            clearInterval(timer);
            window.removeEventListener('message', handler);
            alert('তথ্য পাওয়া যায়নি। BDRIS লাইভ ট্যাবে লগিন আছে কিনা চেক করুন।');
        }
    });
}
</script>
</body>
</html>