<?php
/**
 * BDRIS Office System – print-application.php
 * Beautiful official A4 layout with inline document viewer
 */
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once 'includes/ProxyHelper.php';

$proxy         = new ProxyHelper();
$jsonData      = null;
$error         = null;
$app_id_or_url = '';

if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw  = file_get_contents('php://input');
    $json = json_decode($raw, true);
    $app_id_or_url = $json['app_id'][0] ?? ($_POST['app_id'] ?? '');
} else {
    $app_id_or_url = $_GET['app_id'] ?? ($_GET['id'] ?? '');
}
$app_id_or_url = trim((string)$app_id_or_url);

function getActiveOfficeId($proxy) {
    $officeId = '';
    if (isset($_GET['officeId']) && trim((string)$_GET['officeId']) !== '') $officeId = trim((string)$_GET['officeId']);
    elseif (isset($_POST['officeId']) && trim((string)$_POST['officeId']) !== '') $officeId = trim((string)$_POST['officeId']);
    if ($officeId !== '' && !ctype_digit($officeId)) {
        $r = $proxy->getIntegerOfficeId($officeId);
        if ($r !== '') $officeId = $r;
    }
    $cookiesDir = __DIR__ . '/cookies';
    $officeTokenFile = $proxy->getActiveOfficeFile();
    if ($officeId !== '') {
        if (ctype_digit($officeId)) { if (!is_dir($cookiesDir)) @mkdir($cookiesDir,0755,true); @file_put_contents($officeTokenFile,$officeId); }
        return $officeId;
    }
    $activeToken = file_exists($officeTokenFile) ? trim((string)file_get_contents($officeTokenFile)) : '';
    if ($activeToken !== '' && !ctype_digit($activeToken)) {
        $r = $proxy->getIntegerOfficeId($activeToken);
        if ($r !== '') { $activeToken=$r; @file_put_contents($officeTokenFile,$activeToken); }
    }
    if ($activeToken === '') {
        $dashResp = $proxy->fetch('https://bdris.gov.bd/br/application','GET',[],false,'https://bdris.gov.bd/');
        $dashBody = (string)($dashResp['body'] ?? '');
        if (preg_match('/\/admin\/br\/applications\/search\?data=([A-Za-z0-9_\-]+)/i',$dashBody,$m)) $activeToken=$m[1];
        elseif (preg_match('/\/admin\/user\/chalan\?data=([A-Za-z0-9_\-]+)/i',$dashBody,$m)) $activeToken=$m[1];
        if ($activeToken !== '') {
            $r = $proxy->getIntegerOfficeId($activeToken);
            if ($r !== '') { $activeToken=$r; if (!is_dir($cookiesDir)) @mkdir($cookiesDir,0755,true); @file_put_contents($officeTokenFile,$activeToken); }
        }
    }
    return $activeToken;
}
function addOfficeParam(array $p,$officeId,$proxy){
    $officeId=(string)$officeId; if($officeId==='') return $p;
    if(ctype_digit($officeId)){$token=$proxy->getOfficeToken($officeId); if($token!=='') $p['data']=$token; $p['officeId']=$officeId;}
    else $p['data']=$officeId;
    return $p;
}
function isLoginPage($body){$s=strtolower((string)$body); return strpos($s,'<title>login</title>')!==false||strpos($s,'login-page')!==false;}
function isHtmlBody($body){$s=strtolower((string)$body); return strpos($s,'<html')!==false||strpos($s,'<!doctype')!==false;}

$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;

if ($app_id_or_url !== '') {
    $officeId=getActiveOfficeId($proxy);
    $sessionExpired=false;
    if ($officeId !== '') {
        $permResp=$proxy->fetch('https://bdris.gov.bd/api/office/permission?officeId='.$officeId,'GET',[],false,'https://bdris.gov.bd/admin/br/applications/search',$bdrisHeaders);
        if(isLoginPage($permResp['body']??'')){ $sessionExpired=true; $error='BDRIS সেশন এক্সপায়ার হয়েছে। অনুগ্রহ করে ব্রাউজার এক্সটেনশন দিয়ে পুনরায় সংযুক্ত করুন।'; }
    }
    if (preg_match('/^\d+$/',$app_id_or_url)) {
        $appId=$app_id_or_url; $encryptedId='';
        if (!$sessionExpired) {
            $officeToken=$proxy->getOfficeToken($officeId);
            $refUrl='https://bdris.gov.bd/admin/br/applications/search'.($officeToken!==''?'?data='.urlencode($officeToken):'');
            $fUrl='https://bdris.gov.bd/api/br/application/details/'.urlencode($appId).'?officeId='.urlencode($officeId);
            $fResp=$proxy->fetch($fUrl,'GET',[],false,$refUrl,$bdrisHeaders);
            if(!isLoginPage($fResp['body']??'')&&(int)($fResp['status']??0)===200){
                $fj=$proxy->parseResponse($fResp);
                if(is_array($fj)) $encryptedId=(string)($fj['encryptedId']??$fj['encryptedID']??$fj['encrypted_id']??'');
            }
            if ($encryptedId==='') {
                $infoUrl='https://bdris.gov.bd/api/br/info/application/'.urlencode($appId).'?officeId='.urlencode($officeId);
                $infoResp=$proxy->fetch($infoUrl,'GET',[],false,$refUrl,$bdrisHeaders);
                if(!isLoginPage($infoResp['body']??'')&&(int)($infoResp['status']??0)===200){
                    $ij=$proxy->parseResponse($infoResp);
                    if(is_array($ij)) $encryptedId=(string)($ij['encryptedId']??$ij['encryptedID']??$ij['encrypted_id']??'');
                }
            }
        }
        if ($encryptedId===''&&!$sessionExpired) {
            $sparams=['status'=>'ALL','draw'=>1,'start'=>0,'length'=>20,'search[value]'=>$appId,'search[regex]'=>'false','order[0][column]'=>1,'order[0][dir]'=>'desc','order[0][name]'=>''];
            $sparams=addOfficeParam($sparams,$officeId,$proxy);
            $sresp=$proxy->fetch('https://bdris.gov.bd/api/br/applications/search','GET',$sparams,false,$refUrl??'',$bdrisHeaders,20,1,300);
            if(isLoginPage($sresp['body']??'')){$sessionExpired=true;$error='BDRIS সেশন এক্সপায়ার হয়েছে।';}
            elseif((int)($sresp['status']??0)===200){
                $sj=$proxy->parseResponse($sresp);
                if(isset($sj['data'])&&is_array($sj['data'])){
                    foreach($sj['data'] as $row){
                        if((string)($row['id']??$row['applicationNo']??'')===(string)$appId){$encryptedId=(string)($row['encryptedId']??$row['encryptedID']??'');break;}
                    }
                }
            }
        }
        if ($encryptedId!==''&&!$sessionExpired) {
            $detailsUrl='https://bdris.gov.bd/api/application/details?data='.urlencode($encryptedId);
            $dResp=$proxy->fetch($detailsUrl,'GET',[],false,$refUrl??'',$bdrisHeaders);
            if(!isLoginPage($dResp['body']??'')&&(int)($dResp['status']??0)===200){
                $jsonData=$proxy->parseResponse($dResp);
                if(isset($jsonData['officeId'])&&$jsonData['officeId']!=$officeId){
                    $realOfficeId=(string)$jsonData['officeId'];
                    $proxy->fetch('https://bdris.gov.bd/api/office/permission?officeId='.$realOfficeId,'GET',[],false,$refUrl??'',$bdrisHeaders);
                    $dResp2=$proxy->fetch($detailsUrl,'GET',[],false,$refUrl??'',$bdrisHeaders);
                    if((int)($dResp2['status']??0)===200){$j2=$proxy->parseResponse($dResp2); if($j2) $jsonData=$j2;}
                }
            }
        }
        if ($jsonData&&!isset($jsonData['docs'])&&!$sessionExpired) {
            $attUrl='https://bdris.gov.bd/api/br/application/attachments/'.urlencode($appId);
            $attResp=$proxy->fetch($attUrl,'GET',[],false,$refUrl??'',$bdrisHeaders);
            if((int)($attResp['status']??0)===200){
                $aj=json_decode($attResp['body'],true);
                if(isset($aj['data'])) $jsonData['docs']=$aj['data'];
                elseif(isset($aj['attachments'])) $jsonData['docs']=$aj['attachments'];
            }
        }
    } else {
        $encryptedId=$app_id_or_url;
        $officeToken=$proxy->getOfficeToken($officeId);
        $refUrl='https://bdris.gov.bd/admin/br/applications/search'.($officeToken!==''?'?data='.urlencode($officeToken):'');
        $eResp=$proxy->fetch('https://bdris.gov.bd/api/application/details?data='.urlencode($encryptedId),'GET',[],false,$refUrl,$bdrisHeaders);
        if(!isLoginPage($eResp['body']??'')&&(int)($eResp['status']??0)===200) $jsonData=$proxy->parseResponse($eResp);
    }
    if(!$jsonData&&!$error) $error='আবেদনটি BDRIS সার্ভারে খুঁজে পাওয়া যায়নি। আইডি সঠিক আছে কিনা যাচাই করুন।';
}

// ─── helpers ───────────────────────────────────────────────────────────────
function fld($d,$keys,$def='—'){
    if(!is_array($d)) return $def;
    foreach((array)$keys as $k){ if(!empty($d[$k])) return htmlspecialchars((string)$d[$k]); }
    return $def;
}
function statusBadge($s){
    $sl=strtolower(trim((string)$s));
    if($sl==='') return '<span class="badge bg-secondary">—</span>';
    if(strpos($sl,'register')!==false||strpos($sl,'approved')!==false||strpos($sl,'নিবন্ধিত')!==false) return '<span class="badge-status registered">✅ '.$s.'</span>';
    if(strpos($sl,'duplicate')!==false||strpos($sl,'ডুপ্লিকেট')!==false) return '<span class="badge-status duplicate">⚠️ '.$s.'</span>';
    if(strpos($sl,'pending')!==false||strpos($sl,'অপেক্ষ')!==false) return '<span class="badge-status pending">⏳ '.$s.'</span>';
    if(strpos($sl,'reject')!==false||strpos($sl,'প্রত্যাখ')!==false) return '<span class="badge-status rejected">❌ '.$s.'</span>';
    return '<span class="badge-status unknown">📋 '.htmlspecialchars($s).'</span>';
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $app_id_or_url ? 'আবেদন #'.$app_id_or_url.' – বিস্তারিত' : 'আবেদন বিস্তারিত' ?></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&family=Noto+Serif+Bengali:wght@400;700&display=swap" rel="stylesheet">
<style>
/* ═══════ GLOBAL ═══════ */
:root{
    --green:#1a6b3c;--green-light:#22c55e;--green-pale:#f0fdf4;
    --blue:#1e40af;--blue-light:#3b82f6;--blue-pale:#eff6ff;
    --amber:#d97706;--amber-light:#fbbf24;--amber-pale:#fffbeb;
    --red:#dc2626;--red-pale:#fef2f2;
    --border:#e2e8f0;--text:#1e293b;--muted:#64748b;
}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Hind Siliguri',sans-serif;background:#e8edf3;color:var(--text);font-size:14px;line-height:1.6;}

/* ═══════ TOOLBAR ═══════ */
.toolbar{
    position:sticky;top:0;z-index:100;
    background:linear-gradient(135deg,#1a3a5c,#1e4d8c);
    color:#fff;padding:10px 20px;
    display:flex;align-items:center;gap:12px;flex-wrap:wrap;
    box-shadow:0 3px 12px rgba(0,0,0,0.25);
}
.toolbar .app-id-badge{
    background:rgba(255,255,255,0.15);border-radius:8px;
    padding:4px 14px;font-weight:700;font-size:1rem;letter-spacing:.5px;
}
.toolbar .btn-tb{
    border:none;border-radius:8px;padding:7px 16px;font-size:.85rem;
    font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:6px;
    transition:all .2s;text-decoration:none;
}
.btn-tb.print{background:var(--green-light);color:#fff;}
.btn-tb.print:hover{background:#16a34a;}
.btn-tb.dup{background:var(--amber-light);color:#78350f;}
.btn-tb.dup:hover{background:#f59e0b;}
.btn-tb.raw{background:rgba(255,255,255,.15);color:#fff;}
.btn-tb.raw:hover{background:rgba(255,255,255,.25);}
.btn-tb.back{background:rgba(255,255,255,.1);color:#fff;}
.toolbar .ms-auto{margin-left:auto!important;}

/* ═══════ STATUS BADGES ═══════ */
.badge-status{display:inline-flex;align-items:center;gap:5px;border-radius:20px;padding:4px 14px;font-size:.82rem;font-weight:600;}
.badge-status.registered{background:#dcfce7;color:#15803d;}
.badge-status.duplicate{background:#fef3c7;color:#92400e;}
.badge-status.pending{background:#dbeafe;color:#1e40af;}
.badge-status.rejected{background:#fee2e2;color:#b91c1c;}
.badge-status.unknown{background:#f1f5f9;color:#475569;}

/* ═══════ MAIN LAYOUT ═══════ */
.page-wrap{max-width:900px;margin:0 auto;padding:16px;}

/* ═══════ DOCUMENT CARD ═══════ */
.doc-card{
    background:#fff;border-radius:16px;
    box-shadow:0 4px 24px rgba(0,0,0,0.1);
    overflow:hidden;margin-bottom:20px;
}

/* ═══════ GOV HEADER ═══════ */
.gov-header{
    background:linear-gradient(160deg,#f0fdf4 0%,#dcfce7 100%);
    border-bottom:3px solid var(--green);
    padding:20px;text-align:center;position:relative;
}
.gov-logo{width:70px;height:auto;margin-bottom:10px;filter:drop-shadow(0 2px 6px rgba(0,0,0,.15));}
.gov-title{font-size:1.3rem;font-weight:700;color:#14532d;line-height:1.3;}
.gov-sub{font-size:1rem;color:#166534;margin-top:2px;}
.gov-addr{font-size:.88rem;color:var(--muted);margin-top:2px;}
.gov-stamp{
    position:absolute;top:10px;right:16px;
    background:#fff;border:2px solid var(--green);
    border-radius:8px;padding:6px 12px;text-align:center;
    font-size:.78rem;color:var(--green);font-weight:600;
    box-shadow:0 2px 8px rgba(22,163,74,.2);
}
.gov-stamp .app-num{font-size:1rem;font-weight:700;letter-spacing:.5px;}
.gov-stamp .status-wrap{margin-top:3px;}

/* ═══════ SECTIONS ═══════ */
.section{padding:0 20px 16px;}
.section-title{
    display:flex;align-items:center;gap:8px;
    font-size:.88rem;font-weight:700;color:#1e40af;
    letter-spacing:.5px;text-transform:uppercase;
    margin:16px 0 10px;
    padding-bottom:6px;border-bottom:2px solid #dbeafe;
}
.section-title i{font-size:.9rem;}

/* ═══════ INFO TABLE ═══════ */
.info-grid{
    display:grid;grid-template-columns:1fr 1fr;gap:0;
    border:1px solid var(--border);border-radius:10px;overflow:hidden;
}
.info-grid.single{grid-template-columns:1fr;}
.info-row{
    display:contents;
}
.info-row .lbl,.info-row .val{
    padding:8px 14px;border-bottom:1px solid var(--border);
    display:flex;align-items:center;
}
.info-row:last-child .lbl,.info-row:last-child .val{border-bottom:none;}
.info-row .lbl{
    background:#f8fafc;font-weight:600;color:#374151;
    font-size:.82rem;border-right:1px solid var(--border);
    white-space:nowrap;
}
.info-row .val{color:#1e293b;font-size:.88rem;word-break:break-word;}
.val .highlight{font-weight:700;color:var(--green);font-size:1rem;letter-spacing:.3px;}
.val .brn-link{
    display:inline-flex;align-items:center;gap:5px;
    background:#dcfce7;border:1px solid #16a34a;
    border-radius:6px;padding:3px 10px;
    color:#15803d;font-weight:700;font-size:.9rem;
    text-decoration:none;margin-right:6px;
    transition:all .2s;
}
.val .brn-link:hover{background:#bbf7d0;transform:translateY(-1px);}

/* ═══════ DOCUMENTS ═══════ */
.docs-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:14px;padding:0 20px 20px;}
.doc-item{
    border:1px solid var(--border);border-radius:12px;overflow:hidden;
    box-shadow:0 2px 8px rgba(0,0,0,.06);background:#fff;
    transition:box-shadow .2s;
}
.doc-item:hover{box-shadow:0 4px 16px rgba(0,0,0,.12);}
.doc-item-header{
    background:#f8fafc;padding:8px 12px;
    font-size:.78rem;font-weight:600;color:#475569;
    border-bottom:1px solid var(--border);
    display:flex;align-items:center;gap:6px;
}
.doc-img-wrap{
    position:relative;background:#f1f5f9;min-height:180px;
    display:flex;align-items:center;justify-content:center;cursor:pointer;
    overflow:hidden;
}
.doc-img-wrap img{
    width:100%;height:auto;max-height:280px;object-fit:contain;
    transition:transform .3s;
}
.doc-img-wrap:hover img{transform:scale(1.03);}
.doc-img-wrap .img-loader{
    position:absolute;inset:0;background:#f1f5f9;
    display:flex;align-items:center;justify-content:center;
    flex-direction:column;gap:8px;color:var(--muted);font-size:.8rem;
}
.doc-img-wrap .img-loader .spinner-border{width:1.5rem;height:1.5rem;border-width:.2em;}
.doc-actions{
    padding:8px 12px;display:flex;gap:6px;justify-content:flex-end;
    background:#f8fafc;border-top:1px solid var(--border);
}
.doc-actions a,.doc-actions button{
    font-size:.75rem;padding:4px 10px;border-radius:6px;
    border:1px solid var(--border);background:#fff;
    color:#374151;text-decoration:none;cursor:pointer;
    transition:all .15s;display:inline-flex;align-items:center;gap:4px;
}
.doc-actions a:hover,.doc-actions button:hover{background:#f1f5f9;}
.doc-actions a.open{background:var(--blue-pale);color:var(--blue);border-color:#bfdbfe;}
.doc-actions a.open:hover{background:#dbeafe;}

/* ═══════ LIGHTBOX ═══════ */
#lightbox{
    display:none;position:fixed;inset:0;z-index:9999;
    background:rgba(0,0,0,.88);align-items:center;justify-content:center;
}
#lightbox.active{display:flex;}
#lightbox img{
    max-width:92vw;max-height:92vh;object-fit:contain;
    border-radius:8px;box-shadow:0 10px 40px rgba(0,0,0,.6);
}
#lightbox .lb-close{
    position:absolute;top:16px;right:20px;
    width:40px;height:40px;border-radius:50%;
    background:rgba(255,255,255,.15);border:none;
    color:#fff;font-size:1.3rem;cursor:pointer;
    display:flex;align-items:center;justify-content:center;
    transition:background .2s;
}
#lightbox .lb-close:hover{background:rgba(255,255,255,.3);}
#lightbox .lb-caption{
    position:absolute;bottom:20px;left:50%;transform:translateX(-50%);
    background:rgba(0,0,0,.6);color:#fff;border-radius:8px;
    padding:6px 18px;font-size:.85rem;white-space:nowrap;
}

/* ═══════ SEARCH BAR ═══════ */
.search-bar{
    background:#fff;border-radius:14px;
    box-shadow:0 4px 16px rgba(0,0,0,.08);
    padding:16px 20px;margin-bottom:16px;
}
.search-bar .input-group input{
    border-radius:10px 0 0 10px!important;font-size:1rem;
    border:2px solid #dee2e6;padding:10px 14px;
}
.search-bar .input-group input:focus{border-color:var(--blue-light);box-shadow:none;}
.search-bar .btn-search{
    background:linear-gradient(135deg,#1e40af,#2563eb);
    color:#fff;border:none;border-radius:0 10px 10px 0!important;
    padding:10px 22px;font-size:1rem;font-weight:600;
    transition:all .2s;
}
.search-bar .btn-search:hover{background:linear-gradient(135deg,#1e3a8a,#1d4ed8);}

/* ═══════ ERROR ═══════ */
.err-card{
    background:#fff;border-radius:14px;
    box-shadow:0 4px 16px rgba(0,0,0,.08);
    border-left:5px solid var(--red);
    padding:20px;
}

/* ═══════ PRINT ═══════ */
@page {
    size: A4;
    margin: 10mm;
}
@media print{
    .toolbar,.search-bar,.doc-actions,.no-print{display:none!important;}
    body{background:#fff; font-size: 12px;}
    .page-wrap{max-width:none;padding:0;}
    .doc-card{box-shadow:none!important;border:none!important;margin:0!important;}
    
    table td, table th { padding: 4px 6px !important; font-size: 12px !important; }
    .table-bordered { margin-bottom: 5px !important; }
    div[style*="padding: 20px"] { padding: 10px !important; }
    div[style*="padding: 15px"] { padding: 5px 10px !important; }
    div[style*="margin-bottom: 20px"] { margin-bottom: 10px !important; }
    
    .docs-container { display: flex; flex-wrap: wrap; gap: 15px; align-items: flex-start; justify-content: center; page-break-inside: avoid; margin-top: 10px !important; }
    .doc-print-item { width: 48%; page-break-inside: avoid; border: none !important; padding: 0 !important; }
    .doc-print-item > div { height: auto !important; min-height: 250px; margin-bottom: 5px !important; background: transparent !important; }
    .doc-print-item img { max-width: 100%; max-height: 350px; display: block; margin: 0 auto; object-fit: contain; }
    .gov-stamp{position:static;margin:5px auto 0;display:inline-block;}
}

@media(max-width:600px){
    .info-grid{grid-template-columns:1fr;}
    .info-row .lbl{border-right:none;border-bottom:1px solid var(--border);}
    .info-row .val{border-bottom:1px solid var(--border);}
    .docs-grid{grid-template-columns:1fr;}
    .gov-stamp{position:static;margin:10px auto 0;}
    .doc-attachment-card { width: 100% !important; }
}
.doc-attachment-card { width: calc(50% - 10px); }
</style>
</head>
<body>

<!-- TOOLBAR -->
<div class="toolbar no-print">
    <a href="index.php" class="btn-tb back"><i class="fas fa-home"></i></a>
    <?php if ($app_id_or_url): ?>
    <div class="app-id-badge"><i class="fas fa-file-alt me-1"></i>#<?= htmlspecialchars($app_id_or_url) ?></div>
    <?php endif; ?>
    <?php if ($jsonData): ?>
    <button onclick="window.print()" class="btn-tb print"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
    <button class="btn-tb raw" onclick="document.getElementById('rawModal').classList.toggle('d-none')"><i class="fas fa-database"></i> র ডাটা</button>
    <?php
        $encId = $jsonData['encryptedId'] ?? $jsonData['encryptedID'] ?? '';
        $brn   = $jsonData['birthRegistrationNumber'] ?? $jsonData['personBrn'] ?? '';
        $dob   = $jsonData['personBirthDate'] ?? $jsonData['dateOfBirth'] ?? '';
    ?>
    <?php if ($encId): ?>
    <a href="duplicates.php?search_term=<?= urlencode($encId) ?>&officeId=<?= urlencode($officeId??'') ?>" target="_blank" class="btn-tb dup"><i class="fas fa-copy"></i> ডুপ্লিকেট চেক</a>
    <?php endif; ?>
    <?php if ($brn): ?>
    <a href="search-birth.php?birth_reg_no=<?= urlencode($brn) ?>&dob=<?= urlencode($dob) ?>" target="_blank" class="btn-tb" style="background:#10b981;color:#fff;"><i class="fas fa-external-link-alt"></i> সূত্র ভিজিট</a>
    <?php endif; ?>
    <?php endif; ?>
    <span class="ms-auto" style="font-size:.78rem;opacity:.7;"><i class="fas fa-server me-1"></i>BDRIS Office System</span>
</div>

<div class="page-wrap">

<!-- SEARCH -->
<div class="search-bar no-print">
    <form method="GET" id="sf">
        <div class="input-group">
            <input type="text" name="app_id" id="sid"
                   value="<?= htmlspecialchars($app_id_or_url) ?>"
                   placeholder="আবেদন নম্বর দিন…" required
                   oninput="this.value=this.value.replace(/[^0-9]/g,'')">
            <button type="submit" class="btn-search" onclick="this.innerHTML='<i class=\'fas fa-spinner fa-spin\'></i> লোড হচ্ছে…'">
                <i class="fas fa-search me-1"></i>বিস্তারিত আনুন
            </button>
        </div>
    </form>
</div>

<?php if ($error): ?>
<div class="err-card no-print">
    <div style="display:flex;gap:12px;align-items:flex-start;">
        <div style="font-size:1.8rem;">❌</div>
        <div>
            <div style="font-weight:700;font-size:1rem;margin-bottom:4px;">তথ্য পাওয়া যায়নি</div>
            <div style="color:#475569;"><?= $error ?></div>
            <div style="margin-top:12px;display:flex;gap:8px;flex-wrap:wrap;">
                <a href="verify_system.php" class="btn btn-sm btn-outline-danger rounded-pill"><i class="fas fa-plug me-1"></i>সংযোগ যাচাই</a>
                <a href="connect-setup.php" class="btn btn-sm btn-warning rounded-pill"><i class="fas fa-sync me-1"></i>রিকানেক্ট</a>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if ($jsonData):
    $status   = $jsonData['status'] ?? '';
    $appIdDisp= $jsonData['id'] ?? $jsonData['applicationId'] ?? $app_id_or_url;
    $union    = $jsonData['officeNameBn'] ?? '';
    $upazila  = $jsonData['permAddrUpazilaBn'] ?? $jsonData['upazilaNameBn'] ?? '';
    $district = $jsonData['permAddrDistrictBn'] ?? $jsonData['zilaNameBn'] ?? $jsonData['districtNameBn'] ?? '';
    if (!$upazila||!$district) {
        $full=$jsonData['permAddrFullAddressBn']??'';
        if($full){$parts=array_map('trim',explode(',',$full));$c=count($parts);if($c>=4){if(!$district)$district=$parts[$c-3];if(!$upazila)$upazila=$parts[$c-4];}}
    }
    $locText=trim($upazila.($upazila&&$district?', ':'').$district);
?>

<!-- MAIN DOCUMENT CARD -->
<div class="doc-card" style="border-radius: 0; box-shadow: none; border: 1px solid #ddd; margin-bottom: 20px;">

    <!-- Government Header -->
    <div style="text-align: center; padding: 20px 20px 10px;">
        <img src="https://upload.wikimedia.org/wikipedia/commons/8/84/Government_Seal_of_Bangladesh.svg" alt="বাংলাদেশ সরকার" style="width: 50px; margin-bottom: 5px;">
        <div style="font-size: 1.1rem; font-weight: 700; color: #166534;">গণপ্রজাতন্ত্রী বাংলাদেশ সরকার</div>
        <div style="font-size: 0.95rem; font-weight: 700; color: #166534;"><?= htmlspecialchars($union) ?></div>
        <?php if($locText): ?><div style="font-size: 0.85rem; color: #166534;"><?= htmlspecialchars($locText) ?></div><?php endif; ?>
    </div>
    
    <div style="border-bottom: 2px solid #166534; margin: 0 15px 15px;"></div>

    <!-- Info Section -->
    <div style="padding: 0 15px 15px;">
        <div style="font-size: 1rem; font-weight: 700; color: #166534; margin-bottom: 10px; display: flex; align-items: center; gap: 6px;">
            <i class="fas fa-list-alt"></i> তথ্য
        </div>
        <table class="table table-bordered table-sm" style="font-size: 0.85rem; margin-bottom: 0;">
            <thead style="background-color: #f8f9fa;">
                <tr>
                    <th style="width: 30%;">Field</th>
                    <th>Value</th>
                </tr>
            </thead>
            <tbody>
                <!-- Custom fields to match screenshot at top -->
                <?php if(!empty($jsonData['prsntAddrFullAddressBn'])): ?>
                <tr>
                    <td style="font-weight: 600;">বর্তমান ঠিকানা (বাংলা)</td>
                    <td><?= fld($jsonData,'prsntAddrFullAddressBn') ?></td>
                </tr>
                <?php endif; ?>
                <?php if(!empty($jsonData['prsntAddrFullAddressEn'])): ?>
                <tr>
                    <td style="font-weight: 600;">বর্তমান ঠিকানা (ইংরেজি)</td>
                    <td><?= fld($jsonData,'prsntAddrFullAddressEn') ?></td>
                </tr>
                <?php endif; ?>
                
                <!-- Dump all JSON keys except complex ones -->
                <?php foreach($jsonData as $k => $v): 
                    if(in_array($k, ['docs', 'attachments', 'prsntAddrFullAddressBn', 'prsntAddrFullAddressEn', 'encryptedId', 'encryptedID'])) continue;
                    if(is_array($v) || is_object($v)) continue;
                    $valStr = trim((string)$v);
                    if($valStr === '' || strtolower($valStr) === 'null') continue; // Hide null or empty values
                    
                    $isStatus = strtolower($k) === 'status' || strtolower($k) === 'applicationstatus';
                    $valHtml = htmlspecialchars($valStr);
                    if($isStatus) {
                        $bg = (stripos($valStr, 'approved') !== false || stripos($valStr, 'done') !== false || mb_strpos($valStr, 'অনুমোদিত') !== false) ? '#16a34a' : '#f59e0b';
                        $valHtml = '<span style="background: '.$bg.'; color: #fff; padding: 4px 10px; border-radius: 6px; font-weight: 700; font-size: 0.95em; display: inline-block;">'.$valHtml.'</span>';
                    }
                ?>
                <tr>
                    <td style="font-weight: 600;"><?= htmlspecialchars($k) ?></td>
                    <td><?= $valHtml ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- DOCUMENTS -->
    <?php if(!empty($jsonData['docs'])): ?>
    <div style="padding: 15px; page-break-inside: avoid; border-top: 2px solid #166534;">
        <div style="font-size: 1.1rem; font-weight: 600; color: #1e293b; margin-bottom: 12px; display: flex; align-items: center; justify-content: center; gap: 8px;">
            <i class="fas fa-paperclip" style="color: #64748b;"></i> আবেদনের সংযুক্তি (<?=count($jsonData['docs'])?>)
        </div>
        
        <div class="docs-container" style="display: flex; gap: 20px; flex-wrap: wrap; justify-content: center;">
        <?php foreach($jsonData['docs'] as $idx=>$doc):
            if(empty($doc['id'])) continue;
            $docEncId = $doc['id'];
            $imgUrl = 'image-proxy.php?id=' . urlencode($docEncId);
            $typeName=$doc['attachmentTypeNameBn']??('নথি '.($idx+1));
        ?>
        <div class="doc-print-item doc-attachment-card" style="border: 1px solid #e2e8f0; border-radius: 12px; padding: 15px; background: #fff; text-align: center;">
            <div style="height: 250px; background: #f1f5f9; display: flex; align-items: center; justify-content: center; margin-bottom: 15px; border-radius: 8px; overflow: hidden; position: relative;">
                <div class="img-loader no-print" id="loader-<?=$idx?>">
                    <div class="spinner-border text-secondary spinner-border-sm"></div>
                </div>
                <img src="<?=htmlspecialchars($imgUrl)?>"
                     alt="<?=htmlspecialchars($typeName)?>"
                     onload="document.getElementById('loader-<?=$idx?>').style.display='none';this.style.display='block';"
                     onerror="document.getElementById('loader-<?=$idx?>').innerHTML='<small style=\'color:#94a3b8;\'>লোড ব্যর্থ</small>';this.style.display='none';"
                     style="display:none; max-width: 100%; max-height: 100%; object-fit: contain;">
            </div>
            <div class="doc-actions no-print" style="display: flex; gap: 10px; justify-content: center;">
                <button onclick="openLightbox('<?=addslashes($imgUrl)?>','<?=addslashes(htmlspecialchars($typeName))?>')" style="border: 1px solid #16a34a; background: transparent; color: #16a34a; padding: 6px 16px; font-size: 0.9rem; border-radius: 4px; font-weight: 500; transition: all .2s;">ভিউ</button>
                <a href="<?=htmlspecialchars($imgUrl)?>" download="<?=urlencode($typeName)?>.jpg" style="border: 1px solid #64748b; background: transparent; color: #475569; padding: 6px 16px; font-size: 0.9rem; border-radius: 4px; text-decoration: none; font-weight: 500; transition: all .2s;">ডাউনলোড</a>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

</div><!-- /doc-card -->

<?php endif; // $jsonData ?>

</div><!-- /page-wrap -->

<!-- LIGHTBOX -->
<div id="lightbox" style="overflow:auto;">
    <button class="lb-close" onclick="closeLightbox()"><i class="fas fa-times"></i></button>
    <div style="position:relative; width:100%; height:100%; display:flex; align-items:center; justify-content:center;">
        <img id="lbImg" src="" alt="" style="transition: transform 0.2s;">
    </div>
    <div class="lb-caption" id="lbCaption"></div>
    <div style="position:absolute; bottom:60px; left:50%; transform:translateX(-50%); display:flex; gap:10px; background:rgba(0,0,0,0.6); padding:8px 16px; border-radius:30px;">
        <button onclick="zoomImg(0.25)" style="background:none; border:none; color:#fff; font-size:1.2rem; cursor:pointer;"><i class="fas fa-search-plus"></i></button>
        <button onclick="zoomImg(-0.25)" style="background:none; border:none; color:#fff; font-size:1.2rem; cursor:pointer;"><i class="fas fa-search-minus"></i></button>
        <button onclick="resetZoom()" style="background:none; border:none; color:#fff; font-size:1.2rem; cursor:pointer;"><i class="fas fa-expand"></i></button>
    </div>
</div>

<!-- RAW JSON (hidden) -->
<?php if($jsonData): ?>
<div id="rawModal" class="d-none no-print" style="position:fixed;inset:0;z-index:9998;background:rgba(0,0,0,.7);display:flex;align-items:center;justify-content:center;">
    <div style="background:#fff;color:#1e293b;border-radius:12px;width:90vw;max-width:800px;max-height:85vh;overflow:auto;padding:20px;position:relative;">
        <button onclick="document.getElementById('rawModal').classList.add('d-none')"
                style="position:absolute;top:10px;right:12px;background:#f1f5f9;border:1px solid #cbd5e1;color:#1e293b;font-size:1.2rem;cursor:pointer;border-radius:50%;width:32px;height:32px;display:flex;align-items:center;justify-content:center;"><i class="fas fa-times"></i></button>
        <div style="font-size:1.1rem;font-weight:700;color:#16a34a;margin-bottom:12px;border-bottom:1px solid #e2e8f0;padding-bottom:8px;">
            <i class="fas fa-database"></i> র ডাটা (আবেদন #<?=htmlspecialchars($app_id_or_url)?>)
        </div>
        <table class="table table-bordered table-sm table-striped" style="font-size: 0.85rem;">
            <thead><tr class="table-dark"><th>Key</th><th>Value</th></tr></thead>
            <tbody>
                <?php 
                $flatData = [];
                array_walk_recursive($jsonData, function($a, $b) use (&$flatData) { $flatData[$b] = $a; });
                foreach($flatData as $k => $v): 
                    $vStr = trim((string)$v);
                    if($vStr === '' || strtolower($vStr) === 'null') continue; // Hide nulls
                ?>
                <tr>
                    <td style="font-weight: 600; width: 35%;"><?= htmlspecialchars($k) ?></td>
                    <td style="word-break: break-all;"><?= htmlspecialchars($vStr) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<script>
// ─── Lazy-load images ───────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded',function(){
    const imgs=document.querySelectorAll('img[data-src]');
    if('IntersectionObserver' in window){
        const obs=new IntersectionObserver((entries)=>{
            entries.forEach(e=>{
                if(e.isIntersecting){
                    const img=e.target;
                    img.src=img.dataset.src;
                    obs.unobserve(img);
                }
            });
        },{rootMargin:'200px'});
        imgs.forEach(img=>obs.observe(img));
    } else {
        imgs.forEach(img=>img.src=img.dataset.src);
    }
});

// ─── Lightbox ───────────────────────────────────────────────────────────────
let currentZoom = 1;
function zoomImg(val) {
    currentZoom += val;
    if(currentZoom < 0.2) currentZoom = 0.2;
    document.getElementById('lbImg').style.transform = `scale(${currentZoom})`;
}
function resetZoom() {
    currentZoom = 1;
    document.getElementById('lbImg').style.transform = `scale(1)`;
}
function openLightbox(src,caption,el){
    const lb=document.getElementById('lightbox');
    const img=document.getElementById('lbImg');
    resetZoom();
    img.src=src;
    document.getElementById('lbCaption').textContent=caption||'';
    lb.classList.add('active');
}
function closeLightbox(){
    document.getElementById('lightbox').classList.remove('active');
    document.getElementById('lbImg').src='';
    resetZoom();
}
document.getElementById('lightbox').addEventListener('click',function(e){
    if(e.target===this || e.target.tagName.toLowerCase() === 'div' && e.target.parentElement.id === 'lightbox') closeLightbox();
});
document.addEventListener('keydown',e=>{ if(e.key==='Escape') closeLightbox(); });

// ─── Copy notification ───────────────────────────────────────────────────────
document.querySelectorAll('[onclick*="clipboard"]').forEach(btn=>{
    btn.addEventListener('click',function(){
        const orig=this.innerHTML;
        this.innerHTML='<i class="fas fa-check"></i>';
        setTimeout(()=>this.innerHTML=orig,1500);
    });
});
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>