<?php
/**
 * search-by-name.php — নাম দিয়ে জন্ম নিবন্ধন সার্চ
 * সক্রিয় অফিসের মধ্যে এবং সারা বাংলাদেশে সার্চ সমর্থন করে।
 */
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once 'includes/ProxyHelper.php';

$proxy = new ProxyHelper();

// ─── Helper: Active Office ─────────────────────────────────────────────────
function getActiveOfficeId($proxy) {
    if (!empty($_POST['officeId'])) {
        $o = trim($_POST['officeId']);
        if (!ctype_digit($o)) { $r = $proxy->getIntegerOfficeId($o); if ($r!='') $o=$r; }
        return $o;
    }
    $f = $proxy->getActiveOfficeFile();
    $t = file_exists($f) ? trim(file_get_contents($f)) : '';
    if ($t !== '' && !ctype_digit($t)) {
        $r = $proxy->getIntegerOfficeId($t); if ($r!='') { $t=$r; @file_put_contents($f,$t); }
    }
    if ($t === '') {
        $resp = $proxy->fetch('https://bdris.gov.bd/br/application','GET',[],false,'https://bdris.gov.bd/');
        $body = (string)($resp['body'] ?? '');
        if (preg_match('/\/admin\/br\/applications\/search\?data=([A-Za-z0-9_\-]+)/i',$body,$m)) { $t=$m[1]; }
        elseif (preg_match('/\/admin\/user\/chalan\?data=([A-Za-z0-9_\-]+)/i',$body,$m)) { $t=$m[1]; }
        if ($t!=='') { $r=$proxy->getIntegerOfficeId($t); if ($r!='') { $t=$r; @file_put_contents($f,$t); } }
    }
    return $t;
}

$hdrs = ['Accept: application/json, text/javascript, */*; q=0.01','X-Requested-With: XMLHttpRequest','client: bris'];

// ─── AJAX: search ──────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='search') {
    header('Content-Type: application/json; charset=utf-8');

    $name  = trim($_POST['personName'] ?? '');
    $lang  = trim($_POST['nameLang'] ?? 'BENGALI') === 'ENGLISH' ? 'ENGLISH' : 'BENGALI';
    // ✅ ডিফল্ট এখন 'global' — যেকোনো ইউনিয়নে সার্চ
    $scope = trim($_POST['scope'] ?? 'global'); // 'office' or 'global'

    if ($name === '') { echo json_encode(['error'=>'নাম লিখুন']); exit; }

    $officeId = getActiveOfficeId($proxy);
    $cacheKey = md5($name . '_' . $lang . '_' . $scope);
    
    // Step 0: Check Relay Cache
    $cacheFile = __DIR__ . '/cache/relay_' . $cacheKey . '.json';
    if (file_exists($cacheFile)) {
        $cdata = json_decode(file_get_contents($cacheFile), true);
        if ($cdata && (time() - $cdata['time'] < 60)) {
            $data = $cdata['data'];
            $records = [];
            if (isset($data['data']) && is_array($data['data']))       $records = $data['data'];
            elseif (isset($data['records']) && is_array($data['records'])) $records = $data['records'];
            elseif (is_array($data) && isset($data[0]))                $records = $data;
            echo json_encode(['success'=>true, 'data'=>$records, 'officeId'=>$officeId, 'total'=>count($records)]);
            exit;
        }
    }

    // ✅ সর্বদা GLOBAL সার্চ করব (যেকোনো ইউনিয়ন) — office token ছাড়া
    // scope='office' হলেও আগে global চেষ্টা করব, তারপর office
    $baseParams = [
        'personNameBn'   => $lang==='BENGALI' ? $name : '',
        'personNameEn'   => $lang==='ENGLISH' ? $name : '',
        'nameLang'       => $lang,
        'draw'           => 1,
        'start'          => 0,
        'length'         => 200, // বেশি ফলাফল
        'search[value]'  => '',
        'search[regex]'  => 'false',
        'order[0][column]' => 0,
        'order[0][dir]'    => 'desc',
        'order[0][name]'   => '',
    ];

    $endpoints = [
        'https://bdris.gov.bd/api/br/advanced-search-by-name',
        'https://bdris.gov.bd/api/br/advanced/search-by-name',
        'https://bdris.gov.bd/api/br/search/by-name',
    ];

    $globalReferer = 'https://bdris.gov.bd/admin/br/advanced-search-by-name';

    $found = false;
    $resp  = null;

    // ── পদক্ষেপ ১: সবার আগে Global search (কোনো office token নেই) ──
    foreach ($endpoints as $ep) {
        $resp = $proxy->fetch($ep, 'POST', $baseParams, false, $globalReferer, $hdrs, 30, 2);
        if (($resp['status']??0) === 200) {
            $b = $resp['body'] ?? '';
            if (stripos($b,'<title>Login</title>')===false && stripos($b,'login-page')===false && stripos($b,'<html')===false) {
                $found = true;
                break;
            }
        }
    }

    // ── পদক্ষেপ ২: যদি global কাজ না করে, office-specific চেষ্টা করো ──
    if (!$found && $officeId !== '') {
        $tok = $proxy->getOfficeToken($officeId);
        if ($tok !== '') {
            $officeParams = $baseParams;
            $officeParams['data']     = $tok;
            $officeParams['officeId'] = $officeId;
            $officeReferer = $globalReferer . '?data=' . urlencode($tok);
            foreach ($endpoints as $ep) {
                $resp2 = $proxy->fetch($ep, 'POST', $officeParams, false, $officeReferer, $hdrs, 25, 1);
                if (($resp2['status']??0)===200) {
                    $b2 = $resp2['body'] ?? '';
                    if (stripos($b2,'<title>Login</title>')===false && stripos($b2,'login-page')===false && stripos($b2,'<html')===false) {
                        $resp  = $resp2;
                        $found = true;
                        break;
                    }
                }
            }
        }
    }

    if (!$found) {
        $st = $resp['status'] ?? 0;
        $b  = $resp['body']   ?? '';
        if ($st === 400 || $st === 403 || stripos($b, 'Request Rejected') !== false || stripos($b, 'TSPD_101_DID') !== false) {
            $relayUrl = 'bdris-relay.php?type=name&key=' . urlencode($cacheKey) . '&nameBn=' . urlencode($baseParams['personNameBn']) . '&nameEn=' . urlencode($baseParams['personNameEn']) . '&nameLang=' . urlencode($lang) . '&officeId=' . urlencode($officeId);
            echo json_encode(['relay_needed' => true, 'relay_url' => $relayUrl, 'error' => 'BDRIS সার্ভার কানেকশন ব্লক করছে (WAF)। ব্রাউজার পপআপ থেকে ডেটা নিতে হবে।']);
        } elseif (stripos($b,'<title>Login</title>')!==false || stripos($b,'login-page')!==false) {
            echo json_encode(['error'=>'BDRIS সেশন মেয়াদোত্তীর্ণ! ব্রাউজার এক্সটেনশন দিয়ে পুনরায় সংযুক্ত করুন।', 'session_expired'=>true]);
        } elseif ($st === 401) {
            echo json_encode(['error'=>'BDRIS সেশন মেয়াদোত্তীর্ণ (HTTP '.$st.')। ব্রাউজার এক্সটেনশন থেকে নতুন সেশন পাঠান।', 'session_expired'=>true]);
        } else {
            echo json_encode(['error'=>'API সংযোগ ব্যর্থ (HTTP '.$st.'). সেশন যাচাই করুন।']);
        }
        exit;
    }

    $data = json_decode($resp['body'], true);

    // Handle different response shapes
    $records = [];
    if (isset($data['data']) && is_array($data['data']))       $records = $data['data'];
    elseif (isset($data['records']) && is_array($data['records'])) $records = $data['records'];
    elseif (is_array($data) && isset($data[0]))                $records = $data;

    $scopeLabel = ($scope === 'global') ? 'সারা বাংলাদেশ' : 'অফিস+গ্লোবাল';
    echo json_encode(['success'=>true, 'data'=>$records, 'officeId'=>$officeId, 'scope'=>$scopeLabel, 'total'=>count($records)]);
    exit;
}

// ─── AJAX: get_dob ─────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='get_dob') {
    header('Content-Type: application/json; charset=utf-8');
    $brn = trim($_POST['brn'] ?? '');
    if ($brn==='') { echo json_encode(['dob'=>'—']); exit; }
    $officeId = getActiveOfficeId($proxy);

    $endpoints = [
        'https://bdris.gov.bd/api/br/info/ubrn/'.urlencode($brn),
        'https://bdris.gov.bd/api/br/register/search/by-ubrn?ubrn='.urlencode($brn),
    ];
    foreach ($endpoints as $ep) {
        $r = $proxy->fetch($ep,'GET',[],false,'https://bdris.gov.bd/admin/br/advanced-search-by-name',$hdrs,8,1);
        if (($r['status']??0)===200) {
            $j=json_decode($r['body']??'',true);
            $dob=$j['personBirthDate']??$j['dateOfBirth']??($j['data'][0]['dateOfBirth']??'');
            if ($dob!=='') { echo json_encode(['dob'=>$dob]); exit; }
        }
    }
    echo json_encode(['dob'=>'—']); exit;
}

// ─── Page Data ─────────────────────────────────────────────────────────────
$officeId  = getActiveOfficeId($proxy);
$officeFile = $proxy->getActiveOfficeFile();
$officeRaw  = file_exists($officeFile) ? trim(file_get_contents($officeFile)) : '';
?>
<!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{
  --green:#1a6b3c;--green2:#22c55e;--green-pale:#f0fdf4;
  --blue:#1e40af;--blue2:#3b82f6;--blue-pale:#eff6ff;
  --border:#e2e8f0;--text:#1e293b;--muted:#64748b;
}
*{box-sizing:border-box;}
body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#e8edf3 0%,#f0f4f8 100%);min-height:100vh;color:var(--text);}

/* ── TOOLBAR ── */
.toolbar{
  background:linear-gradient(135deg,#1a3a5c,#1e4d8c);
  color:#fff;padding:10px 20px;
  display:flex;align-items:center;gap:10px;flex-wrap:wrap;
  box-shadow:0 3px 12px rgba(0,0,0,.25);position:sticky;top:0;z-index:50;
}
.toolbar .page-title{font-size:1rem;font-weight:700;display:flex;align-items:center;gap:8px;}
.toolbar .btn-tb{
  border:none;border-radius:8px;padding:7px 16px;font-size:.82rem;font-weight:600;
  cursor:pointer;display:inline-flex;align-items:center;gap:6px;text-decoration:none;transition:all .2s;
}
.btn-home{background:rgba(255,255,255,.15);color:#fff;}
.btn-home:hover{background:rgba(255,255,255,.25);color:#fff;}
.office-badge{
  background:rgba(255,255,255,.15);border-radius:20px;
  padding:4px 14px;font-size:.78rem;display:flex;align-items:center;gap:5px;
}

/* ── SEARCH CARD ── */
.search-wrap{max-width:900px;margin:24px auto;padding:0 16px;}
.search-card{
  background:#fff;border-radius:18px;
  box-shadow:0 6px 30px rgba(0,0,0,.1);overflow:hidden;
}
.search-header{
  background:linear-gradient(135deg,#166534,#16a34a);
  color:#fff;padding:20px 24px;
  display:flex;align-items:center;gap:12px;
}
.search-header .icon-wrap{
  width:48px;height:48px;border-radius:12px;
  background:rgba(255,255,255,.2);
  display:flex;align-items:center;justify-content:center;font-size:1.3rem;
}
.search-header h4{margin:0;font-size:1.2rem;font-weight:700;}
.search-header p{margin:0;font-size:.82rem;opacity:.85;}
.search-body{padding:24px;}

/* ── SEARCH FORM ── */
.form-row{display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end;}
.form-group{flex:1;min-width:180px;}
.form-group label{font-weight:600;font-size:.85rem;margin-bottom:6px;display:block;color:#374151;}
.form-group input,.form-group select{
  width:100%;padding:11px 14px;border:2px solid #e2e8f0;border-radius:10px;
  font-size:1rem;font-family:'Hind Siliguri',sans-serif;color:#1e293b;
  transition:border-color .2s;background:#fff;
}
.form-group input:focus,.form-group select:focus{border-color:#16a34a;outline:none;box-shadow:0 0 0 3px rgba(22,163,74,.1);}
.btn-search{
  background:linear-gradient(135deg,#166534,#16a34a);
  color:#fff;border:none;border-radius:10px;padding:12px 28px;
  font-size:1rem;font-weight:700;cursor:pointer;
  display:flex;align-items:center;gap:8px;white-space:nowrap;
  transition:all .2s;font-family:'Hind Siliguri',sans-serif;
}
.btn-search:hover{background:linear-gradient(135deg,#14532d,#166534);transform:translateY(-1px);}
.btn-search:disabled{opacity:.6;cursor:not-allowed;transform:none;}

/* ── SCOPE TOGGLE ── */
.scope-toggle{display:flex;gap:8px;margin-top:12px;}
.scope-btn{
  border:2px solid #e2e8f0;background:#fff;border-radius:8px;padding:6px 16px;
  font-size:.8rem;font-weight:600;cursor:pointer;transition:all .2s;color:#64748b;
}
.scope-btn.active{border-color:#16a34a;background:#f0fdf4;color:#166534;}

/* ── STATUS ── */
.status-bar{
  background:#f8fafc;border-top:1px solid var(--border);
  padding:10px 24px;display:flex;align-items:center;gap:8px;font-size:.82rem;color:var(--muted);
}
.status-dot{width:8px;height:8px;border-radius:50%;background:#16a34a;animation:pulse 1.5s infinite;}
@keyframes pulse{0%,100%{opacity:1;}50%{opacity:.4;}}

/* ── RESULTS ── */
.results-card{
  background:#fff;border-radius:18px;
  box-shadow:0 4px 20px rgba(0,0,0,.08);
  margin-top:16px;overflow:hidden;
}
.results-header{
  background:#f8fafc;border-bottom:2px solid var(--border);
  padding:14px 20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;
}
.results-header h5{margin:0;font-size:.95rem;font-weight:700;color:#1e293b;}
.count-badge{
  background:linear-gradient(135deg,#166534,#16a34a);
  color:#fff;border-radius:20px;padding:4px 14px;font-size:.8rem;font-weight:700;
}

/* ── TABLE ── */
.table-wrap{overflow-x:auto;}
table{width:100%;border-collapse:collapse;}
thead th{
  background:#f1f5f9;font-size:.8rem;font-weight:700;color:#374151;
  padding:10px 14px;text-align:left;border-bottom:2px solid var(--border);
  white-space:nowrap;
}
tbody tr{border-bottom:1px solid #f1f5f9;transition:background .15s;}
tbody tr:hover{background:#f8fffe;}
tbody td{padding:10px 14px;font-size:.85rem;color:#1e293b;vertical-align:middle;}
.brn-badge{
  font-family:monospace;font-size:.88rem;font-weight:700;
  background:#dcfce7;color:#15803d;border:1px solid #86efac;
  border-radius:6px;padding:3px 10px;display:inline-block;
  cursor:pointer;transition:all .2s;
}
.brn-badge:hover{background:#bbf7d0;}
.name-bn{font-weight:700;color:#1e293b;}
.name-en{color:#64748b;font-size:.82rem;}
.dob-cell{color:#374151;white-space:nowrap;}
.action-btns{display:flex;gap:6px;flex-wrap:wrap;}
.btn-act{
  font-size:.75rem;padding:5px 12px;border-radius:7px;border:none;
  cursor:pointer;font-weight:600;display:inline-flex;align-items:center;gap:4px;
  text-decoration:none;transition:all .15s;font-family:'Hind Siliguri',sans-serif;
}
.btn-view{background:#dbeafe;color:#1e40af;}
.btn-view:hover{background:#bfdbfe;color:#1e3a8a;}
.btn-cert{background:#dcfce7;color:#15803d;}
.btn-cert:hover{background:#bbf7d0;color:#14532d;}
.btn-copy{background:#f1f5f9;color:#475569;}
.btn-copy:hover{background:#e2e8f0;}

/* ── ALERTS ── */
.alert-custom{
  border-radius:12px;padding:14px 18px;margin-top:16px;
  display:flex;align-items:flex-start;gap:10px;
}
.alert-warn{background:#fffbeb;border:1px solid #fcd34d;color:#92400e;}
.alert-err{background:#fef2f2;border:1px solid #fca5a5;color:#b91c1c;}
.alert-info{background:#eff6ff;border:1px solid #93c5fd;color:#1e40af;}
.alert-custom .icon{font-size:1.2rem;margin-top:2px;}

/* ── SKELETON ── */
.skeleton{background:linear-gradient(90deg,#f1f5f9 25%,#e2e8f0 50%,#f1f5f9 75%);background-size:200% 100%;animation:shimmer 1.5s infinite;border-radius:6px;height:16px;display:inline-block;}
@keyframes shimmer{0%{background-position:200% 0;}100%{background-position:-200% 0;}}

/* ── EMPTY ── */
.empty-state{text-align:center;padding:40px;color:var(--muted);}
.empty-state .icon{font-size:3rem;margin-bottom:12px;opacity:.4;}

@media(max-width:600px){
  .form-row{flex-direction:column;}
  .btn-search{width:100%;justify-content:center;}
}
</style>
</head>
<body>

<!-- TOOLBAR -->
<div class="toolbar">
  <a href="index.php" class="btn-tb btn-home"><i class="fas fa-home"></i> ড্যাশবোর্ড</a>
  <div class="page-title"><i class="fas fa-search"></i> নাম দিয়ে সার্চ</div>
  <?php if($officeId): ?>
  <div class="office-badge"><i class="fas fa-building"></i> অফিস ID: <?=htmlspecialchars($officeId)?></div>
  <?php endif; ?>
  <a href="verify_system.php" class="btn-tb btn-home ms-auto" style="background:rgba(255,200,0,.2);"><i class="fas fa-plug"></i> সংযোগ যাচাই</a>
</div>

<div class="search-wrap">

  <!-- SEARCH CARD -->
  <div class="search-card">
    <div class="search-header">
      <div class="icon-wrap"><i class="fas fa-search"></i></div>
      <div>
        <h4>নাম দিয়ে জন্ম নিবন্ধন সার্চ</h4>
        <p>বাংলা বা ইংরেজি নাম দিয়ে সক্রিয় অফিস বা সারা বাংলাদেশে সার্চ করুন</p>
      </div>
    </div>
    <div class="search-body">
      <form id="searchForm">
        <div class="form-row">
          <div class="form-group" style="flex:2;">
            <label><i class="fas fa-user" style="color:#16a34a;margin-right:4px;"></i>ব্যক্তির নাম</label>
            <input type="text" id="personName" placeholder="উদাহরণ: মোঃ রফিকুল ইসলাম / MD RAFIQUL ISLAM" autocomplete="off">
          </div>
          <div class="form-group" style="flex:1;">
            <label><i class="fas fa-language" style="color:#16a34a;margin-right:4px;"></i>ভাষা</label>
            <select id="nameLang">
              <option value="BENGALI" selected>বাংলা</option>
              <option value="ENGLISH">English</option>
            </select>
          </div>
          <div style="flex-shrink:0;">
            <label style="font-weight:600;font-size:.85rem;margin-bottom:6px;display:block;color:transparent;">.</label>
            <button type="submit" class="btn-search" id="searchBtn">
              <i class="fas fa-search"></i> সার্চ করুন
            </button>
          </div>
        </div>

        <!-- Scope Toggle - ডিফল্ট: সারা বাংলাদেশ -->
        <div class="scope-toggle">
          <div style="font-size:.8rem;color:var(--muted);display:flex;align-items:center;gap:6px;margin-right:4px;">
            <i class="fas fa-filter"></i> সার্চ পরিসীমা:
          </div>
          <button type="button" class="scope-btn" id="scopeOffice" onclick="setScope('office')">
            <i class="fas fa-building"></i> সক্রিয় অফিস <?php if($officeId): ?>(ID: <?=htmlspecialchars($officeId)?>)<?php endif; ?>
          </button>
          <button type="button" class="scope-btn active" id="scopeGlobal" onclick="setScope('global')">
            <i class="fas fa-globe-asia"></i> ✅ সারা বাংলাদেশ
          </button>
        </div>

        <!-- ✅ নতুন: Relay দিয়ে সরাসরি ব্রাউজার সেশন থেকে সার্চ -->
        <div style="margin-top:8px;">
          <button type="button" id="relaySearchBtn"
            onclick="openRelayNameSearch()"
            style="background:linear-gradient(135deg,#065f46,#047857);color:#fff;border:none;border-radius:10px;padding:8px 18px;font-size:.9rem;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:6px;">
            <i class="fas fa-globe"></i> 🌏 সারা বাংলাদেশ (ব্রাউজার রিলে)
            <small style="opacity:.8;font-size:.78rem;">(WAF bypass)</small>
          </button>
          <div style="font-size:.75rem;color:var(--muted);margin-top:4px;">
            BDRIS ট্যাবে লগিন থাকলে এই বাটনে সব বাংলাদেশের তথ্য দেখাবে।
          </div>
        </div>
      </form>

      <div class="status-bar" id="statusBar">
        <div class="status-dot"></div>
        <span id="statusText">প্রস্তুত — নাম লিখে সার্চ বাটন চাপুন</span>
      </div>
    </div>
  </div>

  <!-- RESULTS / MESSAGES -->
  <div id="alertBox" style="display:none;"></div>

  <div id="resultsSection" style="display:none;" class="results-card">
    <div class="results-header">
      <h5><i class="fas fa-list-ul" style="color:#16a34a;"></i> সার্চ ফলাফল</h5>
      <span class="count-badge" id="countBadge">0 টি রেকর্ড</span>
    </div>
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th style="width:40px;">#</th>
            <th>নিবন্ধন নম্বর (BRN)</th>
            <th>নাম (বাংলা)</th>
            <th>নাম (ইংরেজি)</th>
            <th>জন্ম তারিখ</th>
            <th style="width:180px;">একশন</th>
          </tr>
        </thead>
        <tbody id="resultBody">
        </tbody>
      </table>
    </div>
  </div>

</div><!-- /search-wrap -->

<script>
// ✅ ডিফল্ট scope: global (সারা বাংলাদেশ)
let currentScope = 'global';

function setScope(s) {
  currentScope = s;
  document.getElementById('scopeOffice').classList.toggle('active', s==='office');
  document.getElementById('scopeGlobal').classList.toggle('active', s==='global');
}

function showAlert(type, msg) {
  const ab = document.getElementById('alertBox');
  const icons = {warn:'exclamation-triangle',err:'times-circle',info:'info-circle'};
  ab.className = 'alert-custom alert-' + type;
  ab.innerHTML = `<div class="icon"><i class="fas fa-${icons[type]||'info-circle'}"></i></div><div>${msg}</div>`;
  ab.style.display = 'flex';
}

function hideAlert() { document.getElementById('alertBox').style.display='none'; }

function setStatus(msg, spin=false) {
  const el = document.getElementById('statusText');
  el.innerHTML = spin ? `<i class="fas fa-spinner fa-spin" style="margin-right:5px;"></i>${msg}` : msg;
}

document.getElementById('searchForm').addEventListener('submit', function(e) {
  e.preventDefault();
  const name = document.getElementById('personName').value.trim();
  if (!name) { showAlert('warn','নাম লিখুন'); return; }

  const btn = document.getElementById('searchBtn');
  btn.disabled = true;
  btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> সার্চ হচ্ছে…';
  hideAlert();
  document.getElementById('resultsSection').style.display = 'none';
  setStatus('BDRIS সার্ভারে খোঁজা হচ্ছে… অনুগ্রহ করে অপেক্ষা করুন', true);

  const fd = new FormData();
  fd.append('action', 'search');
  fd.append('personName', name);
  fd.append('nameLang', document.getElementById('nameLang').value);
  fd.append('scope', currentScope);

  fetch('', {method:'POST', body:fd})
  .then(r => r.json())
  .then(data => {
    btn.disabled = false;
    btn.innerHTML = '<i class="fas fa-search"></i> সার্চ করুন';

    if (data.error) {
      setStatus('সার্চ ব্যর্থ');
      if (data.relay_needed) {
        showAlert('err', `<strong>WAF ব্লক!</strong><br>${data.error}<br><br>
          <button onclick="openRelay('${data.relay_url}')" style="background:#16a34a;color:#fff;padding:8px 16px;border-radius:8px;border:none;font-weight:700;cursor:pointer;">
            <i class="fas fa-external-link-alt"></i> ব্রাউজার থেকে ডেটা নিন
          </button>`);
      } else if (data.session_expired) {
        showAlert('err', `<strong>সেশন মেয়াদোত্তীর্ণ!</strong><br>${data.error}<br><br>
          <a href="connect-setup.php" style="background:#dc2626;color:#fff;padding:8px 16px;border-radius:8px;text-decoration:none;font-weight:700;">
            <i class="fas fa-plug"></i> এখনই রিকানেক্ট করুন
          </a>`);
      } else {
        showAlert('err', `<strong>সমস্যা:</strong> ${data.error}<br><small><a href="connect-setup.php" style="color:inherit;">→ পুনরায় সংযুক্ত করুন</a></small>`);
      }
      return;
    }

    const records = data.data || [];
    document.getElementById('countBadge').textContent = records.length + ' টি রেকর্ড';
    const scopeLabel = data.scope || 'সারা বাংলাদেশ';
    setStatus(`"${name}" — ${records.length} টি রেকর্ড পাওয়া গেছে (${scopeLabel})`);

    if (records.length === 0) {
      showAlert('info', `"<strong>${name}</strong>" নামে কোনো নিবন্ধন পাওয়া যায়নি।<br><small>অন্য বানান চেষ্টা করুন বা নামের বানান পরীক্ষা করুন।</small>`);
      return;
    }

    const tbody = document.getElementById('resultBody');
    let html = '';
    records.forEach((row, i) => {
      const brn   = row.ubrn || row.birthRegistrationNumber || row.brn || '';
      const nameBn = row.personNameBN || row.personNameBn || row.nameBn || '—';
      const nameEn = row.personNameEN || row.personNameEn || row.nameEn || '—';
      const dob    = row.personBirthDate || row.dateOfBirth || '';
      const dobId  = 'dob-' + i;

      const dobCell = dob
        ? `<span class="dob-cell">${dob}</span>`
        : `<span class="skeleton" id="${dobId}" style="width:80px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>`;

      const copyBtn = brn ? `<button class="btn-act btn-copy" onclick="copyBrn('${brn}',this)" title="কপি করুন"><i class="fas fa-copy"></i></button>` : '';
      const viewBtn = brn ? `<a href="search-birth.php?ubrn=${encodeURIComponent(brn)}" target="_blank" class="btn-act btn-view"><i class="fas fa-eye"></i> ভিউ</a>` : '';
      const certBtn = brn && dob ? `<a href="print-certificate.php?ubrn=${encodeURIComponent(brn)}&dob=${encodeURIComponent(dob)}" target="_blank" class="btn-act btn-cert"><i class="fas fa-certificate"></i> সনদ</a>` : '';

      html += `<tr>
        <td style="color:var(--muted);font-size:.8rem;">${i+1}</td>
        <td>
          ${brn ? `<span class="brn-badge" onclick="copyBrn('${brn}',this)" title="ক্লিক করে কপি করুন">${brn}</span>` : '<span style="color:var(--muted);">—</span>'}
        </td>
        <td><span class="name-bn">${nameBn}</span></td>
        <td><span class="name-en">${nameEn}</span></td>
        <td>${dobCell}</td>
        <td><div class="action-btns">${viewBtn}${certBtn}${copyBtn}</div></td>
      </tr>`;

      // Async fetch DOB
      if (!dob && brn) {
        setTimeout(() => fetchDob(brn, dobId), i * 200);
      }
    });

    tbody.innerHTML = html;
    document.getElementById('resultsSection').style.display = 'block';
  })
  .catch(err => {
    btn.disabled = false;
    btn.innerHTML = '<i class="fas fa-search"></i> সার্চ করুন';
    setStatus('নেটওয়ার্ক সমস্যা');
    showAlert('err', 'নেটওয়ার্ক বা সার্ভার সমস্যা। পুনরায় চেষ্টা করুন।');
  });
});

function fetchDob(brn, elId) {
  const fd = new FormData();
  fd.append('action','get_dob');
  fd.append('brn', brn);
  fetch('',{method:'POST',body:fd})
  .then(r=>r.json())
  .then(d=>{
    const el=document.getElementById(elId);
    if(el) el.outerHTML=`<span class="dob-cell">${d.dob||'—'}</span>`;
  }).catch(()=>{
    const el=document.getElementById(elId);
    if(el) el.outerHTML=`<span style="color:var(--muted);">—</span>`;
  });
}

function copyBrn(brn, el) {
  navigator.clipboard.writeText(brn).then(()=>{
    const orig = el.innerHTML;
    el.innerHTML = '<i class="fas fa-check"></i> কপি!';
    el.style.background='#bbf7d0';
    setTimeout(()=>{ el.innerHTML=orig; el.style.background=''; }, 1500);
  }).catch(()=>{
    const t=document.createElement('textarea');
    t.value=brn; document.body.appendChild(t); t.select();
    document.execCommand('copy'); document.body.removeChild(t);
  });
}

// Auto-detect language on input
document.getElementById('personName').addEventListener('input', function(){
  const v = this.value;
  const isBengali = /[\u0980-\u09FF]/.test(v);
  if (v.length > 0) {
    document.getElementById('nameLang').value = isBengali ? 'BENGALI' : 'ENGLISH';
  }
});

// ✅ Relay results render করার ফাংশন
function renderRelayResults(records, label) {
  if (!records || records.length === 0) {
    showAlert('info', `রিলে সার্চে কোনো ফলাফল পাওয়া যায়নি।<br><small>BDRIS-এ লগিন আছে কিনা চেক করুন।</small>`);
    return;
  }
  document.getElementById('countBadge').textContent = records.length + ' টি রেকর্ড';
  setStatus(`রিলে সার্চ — ${records.length} টি রেকর্ড (${label || 'সারা বাংলাদেশ'})`);

  const tbody = document.getElementById('resultBody');
  let html = '';
  records.forEach((row, i) => {
    const brn    = row.ubrn || row.birthRegistrationNumber || row.brn || '';
    const nameBn = row.personNameBN || row.personNameBn || row.nameBn || '—';
    const nameEn = row.personNameEN || row.personNameEn || row.nameEn || '—';
    const dob    = row.personBirthDate || row.dateOfBirth || '';
    const dobId  = 'relay-dob-' + i;

    const dobCell = dob
      ? `<span class="dob-cell">${dob}</span>`
      : `<span class="skeleton" id="${dobId}" style="width:80px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>`;

    const copyBtn = brn ? `<button class="btn-act btn-copy" onclick="copyBrn('${brn}',this)" title="কপি করুন"><i class="fas fa-copy"></i></button>` : '';
    const viewBtn = brn ? `<a href="search-birth.php?ubrn=${encodeURIComponent(brn)}" target="_blank" class="btn-act btn-view"><i class="fas fa-eye"></i> ভিউ</a>` : '';
    const certBtn = brn && dob ? `<a href="print-certificate.php?ubrn=${encodeURIComponent(brn)}&dob=${encodeURIComponent(dob)}" target="_blank" class="btn-act btn-cert"><i class="fas fa-certificate"></i> সনদ</a>` : '';

    html += `<tr>
      <td style="color:var(--muted);font-size:.8rem;">${i+1}</td>
      <td>${brn ? `<span class="brn-badge" onclick="copyBrn('${brn}',this)" title="ক্লিক করে কপি করুন">${brn}</span>` : '<span style="color:var(--muted);">—</span>'}</td>
      <td><span class="name-bn">${nameBn}</span></td>
      <td><span class="name-en">${nameEn}</span></td>
      <td>${dobCell}</td>
      <td><div class="action-btns">${viewBtn}${certBtn}${copyBtn}</div></td>
    </tr>`;

    if (!dob && brn) setTimeout(() => fetchDob(brn, dobId), i * 150);
  });

  tbody.innerHTML = html;
  document.getElementById('resultsSection').style.display = 'block';
}

// ✅ Relay দিয়ে সারা বাংলাদেশ নাম সার্চ
function openRelayNameSearch() {
  const name = document.getElementById('personName').value.trim();
  if (!name) { showAlert('warn', 'আগে নাম লিখুন'); return; }

  const lang = document.getElementById('nameLang').value || 'BENGALI';
  const nameBn = lang === 'BENGALI' ? name : '';
  const nameEn = lang === 'ENGLISH' ? name : '';

  const params = new URLSearchParams({
    type: 'name',
    key: name,
    nameBn: nameBn,
    nameEn: nameEn,
    nameLang: lang
  });

  const relayUrl = 'bdris-relay.php?' + params.toString();
  const w = 600, h = 480;
  const left = (screen.width/2)-(w/2);
  const top = (screen.height/2)-(h/2);

  const btn = document.getElementById('relaySearchBtn');
  btn.disabled = true;
  btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> রিলে চলছে…';
  setStatus('ব্রাউজার রিলে দিয়ে সারা বাংলাদেশে খোঁজা হচ্ছে…', true);

  const popup = window.open(relayUrl, 'NameRelay', `width=${w},height=${h},top=${top},left=${left}`);

  // Popup বন্ধ হলে reset
  const pollClose = setInterval(() => {
    if (popup && popup.closed) {
      clearInterval(pollClose);
      btn.disabled = false;
      btn.innerHTML = '<i class="fas fa-globe"></i> 🌏 সারা বাংলাদেশ (ব্রাউজার রিলে)';
      setStatus('রিলে সার্চ সম্পন্ন');
    }
  }, 700);

  // Message listener
  function relayHandler(e) {
    if (!e.data || e.data.type !== 'bdris_result') return;
    clearInterval(pollClose);
    window.removeEventListener('message', relayHandler);
    btn.disabled = false;
    btn.innerHTML = '<i class="fas fa-globe"></i> 🌏 সারা বাংলাদেশ (ব্রাউজার রিলে)';

    const relayData = e.data.data;
    let records = [];
    if (relayData && relayData.data && Array.isArray(relayData.data)) records = relayData.data;
    else if (relayData && relayData.records && Array.isArray(relayData.records)) records = relayData.records;
    else if (Array.isArray(relayData)) records = relayData;

    renderRelayResults(records, 'সারা বাংলাদেশ (রিলে)');
  }
  window.addEventListener('message', relayHandler);
}

function openRelay(url) {
    const w = 500, h = 400;
    const left = (screen.width/2)-(w/2);
    const top = (screen.height/2)-(h/2);
    window.open(url, "BDRIS Relay", `width=${w},height=${h},top=${top},left=${left}`);
    window.addEventListener('message', function handler(e) {
        if (e.data && e.data.type === 'bdris_result') {
            window.removeEventListener('message', handler);
            document.getElementById('searchBtn').click();
        } else if (e.data && e.data.type === 'bdris_error') {
            window.removeEventListener('message', handler);
            alert('তথ্য পাওয়া যায়নি। BDRIS এ লগিন করা আছে কিনা চেক করুন।');
        }
    });
}
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
