<?php
   session_start();

   if (!isset($_SESSION['admin_username'])) {
      header("Location: login.php");
      exit;
   } else {

      require_once('config.php');

      // date_default_timezone_set("Africa/Lagos");

      // Include Helper Functions
      require_once('helpers/online_checker.php');         

      $admin_username = $_SESSION['admin_username'];

      // Fetch all users from the database
      $stmt = $pdo->query("SELECT * FROM visitors");
      $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
   }
?>

<!DOCTYPE html>
<html lang="en" data-bs-theme="">
   <head>
      <meta charset="utf-8">
      <title>SB ADMIN | Dashboard</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta name="description" content>
      <meta name="author" content>
      <link href="assets/css/vendor.min.css" rel="stylesheet">
      <link href="assets/css/app.min.css" rel="stylesheet">
      <link href="assets/plugins/jvectormap-next/jquery-jvectormap.css" rel="stylesheet">
   </head>
   <body>

         <div id="app" class="app app-sidebar-collapsed">

            <?php include('includes/header.php'); ?>         

            <button class="app-sidebar-mobile-backdrop" data-toggle-target=".app" data-toggle-class="app-sidebar-mobile-toggled"></button>

            <div id="content" class="app-content">
               <div class="row">

                     <?php include('includes/top-banner.php'); ?> 

                     <div class="col-xl-12">
                        <div class="card-header d-flex align-items-center bg-inverse bg-opacity-10 fw-400" id="statusMessage">                                
                           Click the button to start checking for updates.
                        </div>
                        <br>
                        <button id="startButton" class="btn btn-success">Activate Sound</button>    
                        <br><br>                   
                     </div>

                     <div class="col-xl-12">
                        <div class="card mb-3">
                           <div class="card-body">
                                 <table class="table table-bordered">
                                    <thead>
                                    <tr>
                                       <th scope="col">Visitor Username</th>
                                       <th scope="col">Online Status</th>
                                       <th scope="col">Action</th>     
                                       <th scope="col">Submission Status</th>
                                       <th scope="col">Current Page</th>
                                       <th scope="col">IP Address</th>   
                                       <th scope="col">Action</th>                                                                           
                                    </tr>
                                    </thead>
                                    <tbody id="userTableBody">
                                      <!-- Table rows go here. -->
                                    </tbody>
                                 </table>                                 
                           </div>
                           <div class="card-arrow">
                                 <div class="card-arrow-top-left"></div>
                                 <div class="card-arrow-top-right"></div>
                                 <div class="card-arrow-bottom-left"></div>
                                 <div class="card-arrow-bottom-right"></div>
                           </div>
                        </div>
                     </div>
               </div>
            </div>

            <!-- <?php include('includes/app_theme_panel.php'); ?> -->


            <a href="#" data-toggle="scroll-to-top" class="btn-scroll-top fade"><i class="fa fa-arrow-up"></i></a>
         </div>

         
      <script data-cfasync="false" src="assets/js/email-decode.min.js"></script>
      <script src="assets/js/vendor.min.js" type="46e2a7b9833c1b452032912a-text/javascript"></script>
      <script src="assets/js/app.min.js" type="46e2a7b9833c1b452032912a-text/javascript"></script>
      <script src="assets/plugins/jvectormap-next/jquery-jvectormap.min.js" type="46e2a7b9833c1b452032912a-text/javascript"></script>
      <script src="assets/plugins/jvectormap-content/world-mill.js" type="46e2a7b9833c1b452032912a-text/javascript"></script>
      <script src="assets/plugins/apexcharts/dist/apexcharts.min.js" type="46e2a7b9833c1b452032912a-text/javascript"></script>
      <script src="assets/js/demo/dashboard.demo.js" type="46e2a7b9833c1b452032912a-text/javascript"></script>
      <script async src="https://www.googletagmanager.com/gtag/js?id=G-Y3Q0VGQKY3" type="46e2a7b9833c1b452032912a-text/javascript"></script>
      <script type="46e2a7b9833c1b452032912a-text/javascript">
         window.dataLayer = window.dataLayer || [];
         function gtag(){dataLayer.push(arguments);}
         gtag('js', new Date());
         gtag('config', 'G-Y3Q0VGQKY3');
      </script>
      <script src="assets/js/rocket-loader.min.js" data-cf-settings="46e2a7b9833c1b452032912a-|49" defer></script> 
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- Include jQuery library -->

      <script>
        let lastUpdate = null;
        let context;
        let intervalId;

         document.querySelector('#startButton').addEventListener('click', function() {
            // Create the AudioContext only when the user interacts with the page
            context = new (window.AudioContext || window.webkitAudioContext)();
            // Start checking for updates
            checkForUpdates();
            intervalId = setInterval(checkForUpdates, 1000); // Check every 10 seconds
            $('#statusMessage').text('Checking for updates...');
         });

         function checkForUpdates()
         {
            $.ajax({
               url: 'helpers/fetch_data.php',
               method: 'GET',
               success: function(data) {
                     let response = JSON.parse(data);
                     let latestUpdate = response.latest_update;

                     if (lastUpdate && lastUpdate !== latestUpdate) {
                        // Play beep sound
                        var audio = new Audio('ping.wav');
                        audio.play();

                        // Update the status message
                        $('#statusMessage').text('New update detected at ' + latestUpdate);

                        // Stop checking for updates
                        clearInterval(intervalId);
                     } else {
                        $('#statusMessage').text('Sound Activated. Last checked at ' + new Date().toLocaleTimeString());
                     }

                     lastUpdate = latestUpdate;
               },
               error: function() {
                     $('#statusMessage').text('Error checking for updates');
               }
            });
         }


        function fetchTableData() {
            $.ajax({
                url: 'helpers/fetch_table_data.php',
                method: 'GET',
                success: function(data) {
                    $('#userTableBody').html(data);
                },
                error: function(error) {
                    console.error('Error fetching data:', error);
                }
            });
        }

        // Fetch table data every 2 seconds
        setInterval(fetchTableData, 2000);

        // Fetch table data immediately on page load
        fetchTableData();

      </script>
      
      
   </body>
</html>
