<!DOCTYPE html>
<html>
   <head>
      <!-- TABLES CSS CODE -->
      <?php include"comman/code_css.php"; ?>
      <style>
/* Dual Mode specific styles */
.dual-mode-container {
    margin-top: 20px;
}

.mode-card {
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.mode-card.online {
    border-left: 4px solid #27ae60;
    background-color: #f8fff8;
}

.mode-card.offline {
    border-left: 4px solid #e74c3c;
    background-color: #fff8f8;
}

.mode-card.current {
    border-left: 4px solid #3498db;
    background-color: #f0f8ff;
}

.status-indicator {
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-right: 8px;
}

.status-indicator.online {
    background-color: #27ae60;
}

.status-indicator.offline {
    background-color: #e74c3c;
}

.btn-mode {
    margin: 5px;
    min-width: 120px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin: 20px 0;
}

.stat-item {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 6px;
    text-align: center;
    border: 1px solid #e9ecef;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #2c3e50;
}

.stat-label {
    font-size: 12px;
    color: #6c757d;
    text-transform: uppercase;
    margin-top: 5px;
}
</style>
   </head>
   <body class="hold-transition skin-blue sidebar-mini">
      <!-- Change the theme color if it is set -->
      <div class="wrapper">
         <!-- Left side column. contains the logo and sidebar -->
         <?php include"sidebar.php"; ?>
         
         <!-- Content Wrapper. Contains page content -->
         <div class="content-wrapper">
            <!-- Content Header (Page header) -->
            <section class="content-header">
               <h1>
                  <i class="fa fa-exchange-alt text-primary"></i>
                  <?= $page_title; ?>
                  <small>Manage Database Mode Settings</small>
               </h1>
               <ol class="breadcrumb">
                  <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
                  <li class="active"><?= $page_title; ?></li>
               </ol>
            </section>
            <!-- Main content -->
            <section class="content">
               <!-- Alert Messages -->
               <div class="row">
                  <?php include "comman/code_flashdata.php"; ?>
               </div>
               
               <!-- Offline Transactions Queue -->
               <div class="row">
                  <div class="col-md-12">
                     <div class="box box-success">
                        <div class="box-header with-border">
                           <h3 class="box-title">
                              <i class="fa fa-database"></i> Offline Transactions Queue
                           </h3>
                        </div>
                        
                        <div class="box-body">
                           <!-- Queue Stats -->
                           <div class="row">
                              <div class="col-md-4">
                                 <div class="info-box bg-red">
                                    <span class="info-box-icon"><i class="fa fa-clock-o"></i></span>
                                    <div class="info-box-content">
                                       <span class="info-box-text">Pending</span>
                                       <span class="info-box-number" id="pending-count">0</span>
                                    </div>
                                 </div>
                              </div>
                              <div class="col-md-4">
                                 <div class="info-box bg-green">
                                    <span class="info-box-icon"><i class="fa fa-check"></i></span>
                                    <div class="info-box-content">
                                       <span class="info-box-text">Synced</span>
                                       <span class="info-box-number" id="synced-count">0</span>
                                    </div>
                                 </div>
                              </div>
                              <div class="col-md-4">
                                 <div class="info-box bg-yellow">
                                    <span class="info-box-icon"><i class="fa fa-wifi"></i></span>
                                    <div class="info-box-content">
                                       <span class="info-box-text">Connection</span>
                                       <span class="info-box-number" id="connection-status">Offline</span>
                                    </div>
                                 </div>
                              </div>
                           </div>
                           
                           <!-- Sync Controls -->
                           <div class="text-center" style="margin: 20px 0;">
                              <button class="btn btn-primary btn-lg" onclick="syncOfflineTransactions()" id="sync-btn">
                                 <i class="fa fa-sync"></i> Sync Pending Transactions
                              </button>
                              <button class="btn btn-info btn-lg" onclick="refreshQueue()" style="margin-left: 10px;">
                                 <i class="fa fa-refresh"></i> Refresh
                              </button>
                           </div>
                           
                           <!-- Transaction List -->
                           <div class="table-responsive">
                              <table class="table table-bordered table-striped">
                                 <thead>
                                    <tr>
                                       <th>#</th>
                                       <th>Type</th>
                                       <th>Date/Time</th>
                                       <th>Status</th>
                                       <th>Actions</th>
                                    </tr>
                                 </thead>
                                 <tbody id="queue-table-body">
                                    <tr>
                                       <td colspan="5" class="text-center">
                                          <i class="fa fa-spinner fa-spin"></i> Loading...
                                       </td>
                                    </tr>
                                 </tbody>
                              </table>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </section>
         </div>
         
         <!-- Footer -->
         <?php include"footer.php"; ?>
      </div>
      <!-- ./wrapper -->

      <!-- TABLES JS CODE -->
      <?php include"comman/code_js.php"; ?>
      <script>$(".dual-mode-active-li").addClass("active");</script>

      <script>
      function switchMode(mode) {
          if (confirm('Are you sure you want to switch to ' + mode + ' mode?')) {
              // AJAX call to switch mode
              $.ajax({
                  url: '<?php echo $base_url; ?>dual-mode/switch_mode',
                  type: 'POST',
                  data: {
                      mode: mode,
                      '<?php echo $this->security->get_csrf_token_name();?>': '<?php echo $this->security->get_csrf_hash();?>'
                  },
                  dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      showAlert('success', 'Mode switched successfully!');
                      setTimeout(function() {
                          location.reload();
                      }, 1500);
                  } else {
                      showAlert('error', 'Error: ' + (response.message || 'Failed to switch mode'));
                  }
              },
              error: function() {
                  showAlert('error', 'Error: Failed to switch mode');
              }
              });
          }
      }

      function syncData() {
          // AJAX call to sync data
          $.ajax({
              url: '<?php echo $base_url; ?>dual-mode/sync_data',
              type: 'POST',
              data: {
                  '<?php echo $this->security->get_csrf_token_name();?>': '<?php echo $this->security->get_csrf_hash();?>'
              },
              dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      showAlert('success', 'Data synchronized successfully!');
                      setTimeout(function() {
                          location.reload();
                      }, 1500);
                  } else {
                      showAlert('error', 'Error: ' + (response.message || 'Failed to sync data'));
                  }
              },
              error: function() {
                  showAlert('error', 'Error: Failed to sync data');
              }
          });
      }

      function toggleAutoSync() {
          // AJAX call to toggle auto sync
          $.ajax({
              url: '<?php echo $base_url; ?>dual-mode/toggle_auto_sync',
              type: 'POST',
              data: {
                  '<?php echo $this->security->get_csrf_token_name();?>': '<?php echo $this->security->get_csrf_hash();?>'
              },
              dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      showAlert('success', 'Auto sync toggled successfully!');
                      setTimeout(function() {
                          location.reload();
                      }, 1500);
                  } else {
                      showAlert('error', 'Error: ' + (response.message || 'Failed to toggle auto sync'));
                  }
              },
              error: function() {
                  showAlert('error', 'Error: Failed to toggle auto sync');
              }
          });
      }
      
      function enableDualMode() {
          $.ajax({
              url: '<?php echo $base_url; ?>dual-mode/enable_dual_mode',
              type: 'POST',
              data: {
                  '<?php echo $this->security->get_csrf_token_name();?>': '<?php echo $this->security->get_csrf_hash();?>'
              },
              dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      showAlert('success', 'Dual mode enabled successfully!');
                      setTimeout(function() {
                          location.reload();
                      }, 1500);
                  } else {
                      showAlert('error', 'Error: ' + (response.message || 'Failed to enable dual mode'));
                  }
              },
              error: function() {
                  showAlert('error', 'Error: Failed to enable dual mode');
              }
          });
      }
      
      function debugDualMode() {
          window.open('<?php echo $base_url; ?>dual-mode/debug', '_blank');
      }
      
      // Load offline transactions queue
      function loadQueue() {
          try {
              const queueStr = localStorage.getItem('offline_transactions_queue');
              const queue = queueStr ? JSON.parse(queueStr) : [];
              
              const pending = queue.filter(t => !t.synced);
              const synced = queue.filter(t => t.synced);
              
              // Update counts
              document.getElementById('pending-count').textContent = pending.length;
              document.getElementById('synced-count').textContent = synced.length;
              
              // Update connection status
              if (navigator.onLine) {
                  document.getElementById('connection-status').textContent = 'Online';
                  document.getElementById('sync-btn').disabled = false;
              } else {
                  document.getElementById('connection-status').textContent = 'Offline';
                  document.getElementById('sync-btn').disabled = true;
              }
              
              // Render table
              renderQueueTable(pending);
              
          } catch (e) {
              console.error('Error loading queue:', e);
              document.getElementById('queue-table-body').innerHTML = 
                  '<tr><td colspan="5" class="text-center text-danger"><i class="fa fa-exclamation-triangle"></i> Error loading queue</td></tr>';
          }
      }
      
      // Render queue table
      function renderQueueTable(transactions) {
          const tbody = document.getElementById('queue-table-body');
          
          if (transactions.length === 0) {
              tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted"><i class="fa fa-inbox"></i> No pending transactions</td></tr>';
              return;
          }
          
          let html = '';
          transactions.forEach((txn, index) => {
              const date = new Date(txn.timestamp);
              const formattedDate = date.toLocaleString();
              
              html += `
                  <tr>
                      <td>${index + 1}</td>
                      <td><span class="label label-info">${txn.type.toUpperCase()}</span></td>
                      <td>${formattedDate}</td>
                      <td><span class="label label-warning">Pending</span></td>
                      <td>
                          <button class="btn btn-xs btn-danger" onclick="deleteTransaction('${txn.id}')" title="Delete">
                              <i class="fa fa-trash"></i>
                          </button>
                      </td>
                  </tr>
              `;
          });
          
          tbody.innerHTML = html;
      }
      
      // Sync offline transactions
      function syncOfflineTransactions() {
          if (!navigator.onLine) {
              alert('Cannot sync while offline. Please check your internet connection.');
              return;
          }
          
          if (!window.OfflineSyncManager) {
              alert('Offline sync manager not initialized.');
              return;
          }
          
          // Trigger manual sync
          window.OfflineSyncManager.manualSync();
          
          // Show loading state
          document.getElementById('sync-btn').disabled = true;
          document.getElementById('sync-btn').innerHTML = '<i class="fa fa-spinner fa-spin"></i> Syncing...';
          
          // Refresh after sync (will be handled by auto-refresh)
          setTimeout(function() {
              location.reload();
          }, 3000);
      }
      
      // Refresh queue display
      function refreshQueue() {
          loadQueue();
      }
      
      // Delete a transaction from queue
      function deleteTransaction(txnId) {
          if (!confirm('Are you sure you want to delete this transaction from the queue?')) {
              return;
          }
          
          try {
              // Sync with OfflineSyncManager if available
              if (window.OfflineSyncManager && typeof window.OfflineSyncManager === 'object') {
                  // Remove from OfflineSyncManager's internal queue
                  window.OfflineSyncManager.queue = window.OfflineSyncManager.queue.filter(t => t.id !== txnId);
                  window.OfflineSyncManager.saveQueue();
                  window.OfflineSyncManager.updateStatusIndicator();
                  console.log('Deleted transaction', txnId, 'from OfflineSyncManager');
              }
              
              // Also update localStorage directly for reliability
              const queueStr = localStorage.getItem('offline_transactions_queue');
              const queue = queueStr ? JSON.parse(queueStr) : [];
              const filtered = queue.filter(t => t.id !== txnId);
              localStorage.setItem('offline_transactions_queue', JSON.stringify(filtered));
              
              // Reload the queue display
              loadQueue();
              
              // Show success message
              toastr.success('Transaction deleted from queue successfully.');
              
          } catch (e) {
              console.error('Error deleting transaction:', e);
              alert('Error deleting transaction: ' + e.message);
          }
      }
      
      // Auto-refresh queue every 5 seconds
      setInterval(function() {
          loadQueue();
      }, 5000);
      
      // Load queue on page load
      $(document).ready(function() {
          // Set baseURL for OfflineSyncManager
          window.baseURL = base_url;
          
          // Initialize offline sync manager
          if (typeof window.OfflineSyncManager !== 'undefined') {
              window.OfflineSyncManager.init();
          }
          
          loadQueue();
          
          // Listen for online/offline events
          window.addEventListener('online', function() {
              document.getElementById('connection-status').textContent = 'Online';
              document.getElementById('sync-btn').disabled = false;
              loadQueue();
          });
          
          window.addEventListener('offline', function() {
              document.getElementById('connection-status').textContent = 'Offline';
              document.getElementById('sync-btn').disabled = true;
              loadQueue();
          });
      });
      </script>

   </body>
</html>
