<?php
// Debug session check
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
if (!isset($_SESSION['user'])) {
    header('Location: ?app_route=login');
    exit;
}

include realpath(dirname(__DIR__) . '/include/header.php');

// Enhanced system monitoring data
$load = sys_getloadavg();
$core_count = (int) shell_exec("nproc") ?: 1;
$cpu_percent = round(($load[0] / $core_count) * 100, 1);

// RAM usage
$meminfo = @file_get_contents("/proc/meminfo");
$ram_percent = 'N/A';
$total_mem_gb = 0;
$used_mem_gb = 0;
$free_mem_gb = 0;

if ($meminfo && preg_match("/MemTotal:\s+(\d+) kB/", $meminfo, $total) && preg_match("/MemAvailable:\s+(\d+) kB/", $meminfo, $available)) {
  $total_mem = $total[1] / 1024;
  $free_mem = $available[1] / 1024;
  $used_mem = $total_mem - $free_mem;
  $ram_percent = round(($used_mem / $total_mem) * 100, 1);
  
  $total_mem_gb = round($total_mem / 1024, 2);
  $used_mem_gb = round($used_mem / 1024, 2);
  $free_mem_gb = round($free_mem / 1024, 2);
}

// Disk usage
$disk_total = disk_total_space('/');
$disk_free = disk_free_space('/');
$disk_used = $disk_total - $disk_free;
$disk_percent = round(($disk_used / $disk_total) * 100, 1);

// Network stats (simplified)
$network_stats = [
  'rx_packets' => 'N/A',
  'tx_packets' => 'N/A',
  'rx_bytes' => 'N/A',
  'tx_bytes' => 'N/A'
];

// Try to get network stats on Linux
if (file_exists('/proc/net/dev')) {
  $net_data = file_get_contents('/proc/net/dev');
  if (preg_match('/eth0:\s*(\d+)\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)\s+(\d+)/', $net_data, $matches)) {
    $network_stats['rx_bytes'] = formatBytes($matches[1]);
    $network_stats['rx_packets'] = number_format($matches[2]);
    $network_stats['tx_bytes'] = formatBytes($matches[3]);
    $network_stats['tx_packets'] = number_format($matches[4]);
  }
}

// System uptime
$uptime_seconds = 0;
$uptime_string = 'N/A';
if (file_exists('/proc/uptime')) {
  $uptime_data = file_get_contents('/proc/uptime');
  $uptime_seconds = (int) floatval(explode(' ', $uptime_data)[0]);
  $uptime_string = formatUptime($uptime_seconds);
}

// PHP info
$php_version = PHP_VERSION;
$php_memory_limit = ini_get('memory_limit');
$php_max_execution_time = ini_get('max_execution_time');
$php_upload_max_filesize = ini_get('upload_max_filesize');

// Database performance metrics
$db_queries_per_second = 0;
$db_connections = 0;
$db_slow_queries = 0;

try {
  // Get database status
  $sql = "SHOW STATUS WHERE Variable_name IN ('Queries', 'Connections', 'Slow_queries', 'Threads_connected', 'Uptime')";
  $stmt = $conn->query($sql);
  $db_status = [];
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $db_status[$row['Variable_name']] = $row['Value'];
  }
  
  if (isset($db_status['Queries']) && isset($db_status['Uptime']) && $db_status['Uptime'] > 0) {
    $db_queries_per_second = round($db_status['Queries'] / $db_status['Uptime'], 2);
  }
  $db_connections = $db_status['Threads_connected'] ?? 0;
  $db_slow_queries = $db_status['Slow_queries'] ?? 0;
} catch (Exception $e) {
  // Ignore database errors for monitoring
}

// Helper functions
function formatBytes($bytes, $precision = 2) {
  $units = array('B', 'KB', 'MB', 'GB', 'TB');
  for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
    $bytes /= 1024;
  }
  return round($bytes, $precision) . ' ' . $units[$i];
}

function formatUptime($seconds) {
  $days = floor($seconds / 86400);
  $hours = floor(($seconds % 86400) / 3600);
  $minutes = floor(($seconds % 3600) / 60);
  return "{$days}d {$hours}h {$minutes}m";
}

// Color function
function getColor($value)
{
  if (!is_numeric($value)) return 'secondary';
  if ($value <= 50) return 'success';
  if ($value <= 80) return 'warning';
  return 'danger';
}

$cpu_color = getColor($cpu_percent);
$ram_color = getColor($ram_percent);
$disk_color = getColor($disk_percent);
?>

<div class="col-xl-12">
  <!-- System Overview Row -->
  <div class="row mb-4">
    <div class="col-12">
      <div class="page-title-box">
        <h4 class="page-title">System Dashboard</h4>
        <p class="text-muted">Real-time monitoring and statistics</p>
      </div>
    </div>
  </div>

  <!-- Key Metrics Row -->
  <div class="row">
    <div class="col-md-3">
      <div class="card mini-stats-wid">
        <div class="card-body">
          <div class="d-flex">
            <div class="flex-grow-1">
              <p class="text-muted fw-medium">System Users</p>
              <h4 class="mb-0">
                <?php
                $sql = "SELECT COUNT(*) as total FROM system_user";
                $stmt = $conn->query($sql);
                $row = $stmt->fetch(PDO::FETCH_ASSOC);
                echo number_format($row['total']);
                ?>
              </h4>
              <p class="text-muted mb-0">
                <span class="text-success me-2">
                  <i class="mdi mdi-arrow-up"></i>
                </span>
                Active accounts
              </p>
            </div>
            <div class="flex-shrink-0 align-self-center">
              <div class="mini-stat-icon avatar-sm rounded-circle bg-primary">
                <span class="avatar-title">
                  <i class="bx bx-user font-size-24"></i>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-3">
      <div class="card mini-stats-wid">
        <div class="card-body">
          <div class="d-flex">
            <div class="flex-grow-1">
              <p class="text-muted fw-medium">ISP Users</p>
              <h4 class="mb-0">
                <?php
                $sql = "SELECT COUNT(*) as total FROM users";
                $stmt = $conn->query($sql);
                $row = $stmt->fetch(PDO::FETCH_ASSOC);
                echo number_format($row['total']);
                ?>
              </h4>
              <p class="text-muted mb-0">
                <span class="text-info me-2">
                  <i class="mdi mdi-account-network"></i>
                </span>
                Customer accounts
              </p>
            </div>
            <div class="flex-shrink-0 align-self-center">
              <div class="avatar-sm rounded-circle bg-success mini-stat-icon">
                <span class="avatar-title rounded-circle bg-success">
                  <i class="bx bx-user-voice font-size-24"></i>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-3">
      <div class="card mini-stats-wid">
        <div class="card-body">
          <div class="d-flex">
            <div class="flex-grow-1">
              <p class="text-muted fw-medium">Active Licenses</p>
              <h4 class="mb-0">
                <?php
                $sql = "SELECT COUNT(*) as total FROM licenses WHERE status = 'active'";
                $stmt = $conn->query($sql);
                $row = $stmt->fetch(PDO::FETCH_ASSOC);
                echo number_format($row['total']);
                ?>
              </h4>
              <p class="text-muted mb-0">
                <span class="text-success me-2">
                  <i class="mdi mdi-license"></i>
                </span>
                Valid licenses
              </p>
            </div>
            <div class="flex-shrink-0 align-self-center">
              <div class="mini-stat-icon avatar-sm rounded-circle bg-warning">
                <span class="avatar-title">
                  <i class="bx bx-certification font-size-24"></i>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-3">
      <div class="card mini-stats-wid">
        <div class="card-body">
          <div class="d-flex">
            <div class="flex-grow-1">
              <p class="text-muted fw-medium">System Uptime</p>
              <h4 class="mb-0 font-size-16"><?php echo $uptime_string; ?></h4>
              <p class="text-muted mb-0">
                <span class="text-success me-2">
                  <i class="mdi mdi-clock-check"></i>
                </span>
                Running stable
              </p>
            </div>
            <div class="flex-shrink-0 align-self-center">
              <div class="mini-stat-icon avatar-sm rounded-circle bg-info">
                <span class="avatar-title">
                  <i class="bx bx-time font-size-24"></i>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- System Performance Row -->
  <div class="row">
    <div class="col-md-3">
      <div class="card">
        <div class="card-body">
          <div class="d-flex">
            <div class="flex-grow-1">
              <p class="text-muted fw-medium">CPU Usage</p>
              <h4 class="mb-2">
                <span class="text-<?php echo $cpu_color; ?>"><?php echo $cpu_percent; ?>%</span>
              </h4>
              <div class="progress" style="height: 6px;">
                <div class="progress-bar bg-<?php echo $cpu_color; ?>" 
                     style="width: <?php echo $cpu_percent; ?>%"></div>
              </div>
              <p class="text-muted mb-0 mt-2">
                <small>Load: <?php echo implode(', ', array_map(function($l) { return round($l, 2); }, $load)); ?></small>
              </p>
            </div>
            <div class="flex-shrink-0 align-self-center">
              <div class="mini-stat-icon avatar-sm rounded-circle bg-<?php echo $cpu_color; ?>">
                <span class="avatar-title">
                  <i class="bx bx-chip font-size-20"></i>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-3">
      <div class="card">
        <div class="card-body">
          <div class="d-flex">
            <div class="flex-grow-1">
              <p class="text-muted fw-medium">Memory Usage</p>
              <h4 class="mb-2">
                <span class="text-<?php echo $ram_color; ?>"><?php echo $ram_percent; ?>%</span>
              </h4>
              <div class="progress" style="height: 6px;">
                <div class="progress-bar bg-<?php echo $ram_color; ?>" 
                     style="width: <?php echo $ram_percent; ?>%"></div>
              </div>
              <p class="text-muted mb-0 mt-2">
                <small><?php echo $used_mem_gb; ?>GB / <?php echo $total_mem_gb; ?>GB</small>
              </p>
            </div>
            <div class="flex-shrink-0 align-self-center">
              <div class="mini-stat-icon avatar-sm rounded-circle bg-<?php echo $ram_color; ?>">
                <span class="avatar-title">
                  <i class="bx bx-memory-card font-size-20"></i>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-3">
      <div class="card">
        <div class="card-body">
          <div class="d-flex">
            <div class="flex-grow-1">
              <p class="text-muted fw-medium">Disk Usage</p>
              <h4 class="mb-2">
                <span class="text-<?php echo $disk_color; ?>"><?php echo $disk_percent; ?>%</span>
              </h4>
              <div class="progress" style="height: 6px;">
                <div class="progress-bar bg-<?php echo $disk_color; ?>" 
                     style="width: <?php echo $disk_percent; ?>%"></div>
              </div>
              <p class="text-muted mb-0 mt-2">
                <small><?php echo formatBytes($disk_used); ?> / <?php echo formatBytes($disk_total); ?></small>
              </p>
            </div>
            <div class="flex-shrink-0 align-self-center">
              <div class="mini-stat-icon avatar-sm rounded-circle bg-<?php echo $disk_color; ?>">
                <span class="avatar-title">
                  <i class="bx bx-hdd font-size-20"></i>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-3">
      <div class="card">
        <div class="card-body">
          <div class="d-flex">
            <div class="flex-grow-1">
              <p class="text-muted fw-medium">Database</p>
              <h4 class="mb-2">
                <span class="text-info"><?php echo $db_connections; ?></span>
              </h4>
              <p class="text-muted mb-0">
                <small>Active connections</small>
              </p>
              <p class="text-muted mb-0">
                <small><?php echo $db_queries_per_second; ?> queries/sec</small>
              </p>
            </div>
            <div class="flex-shrink-0 align-self-center">
              <div class="mini-stat-icon avatar-sm rounded-circle bg-info">
                <span class="avatar-title">
                  <i class="bx bx-data font-size-20"></i>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- end row -->


</div>

<div class="col-xl-6">
  <div class="card shadow-sm">
    <div class="card-header bg-primary text-white">
      <h5 class="mb-0">License Status</h5>
    </div>
    <div class="card-body p-2">
      <canvas id="licenseChart" style="height: 200px; width: 200px;"></canvas>
    </div>
  </div>
</div>

<div class="col-xl-6">
  <div class="card shadow-sm">
    <div class="card-header bg-primary text-white">
      <h5 class="mb-0">OS INFO</h5>
    </div>
    <div class="card-body p-2">
      <table class="table table-sm table-borderless mb-0">
        <tbody>
          <tr>
            <td><strong>OS:</strong></td>
            <td><?php echo PHP_OS_FAMILY; ?></td>
          </tr>
          <tr>
            <td><strong>OS Version:</strong></td>
            <td><?php echo php_uname('v'); ?></td>
          </tr>
          <tr>
            <td><strong>PHP Version:</strong></td>
            <td><?php echo phpversion(); ?></td>
          </tr>
          <tr>
            <td><strong>Server Name:</strong></td>
            <td><?php echo $_SERVER['SERVER_NAME']; ?></td>
          </tr>
          <tr>
            <td><strong>Server Software:</strong></td>
            <td><?php echo $_SERVER['SERVER_SOFTWARE']; ?></td>
          </tr>
          <tr>
            <td><strong>Hostname:</strong></td>
            <td><?php echo gethostname(); ?></td>
          </tr>
          <tr>
            <td><strong>Timezone:</strong></td>
            <td><?php echo date_default_timezone_get(); ?></td>
          </tr>
          <tr>
            <td><strong>CPU Architecture:</strong></td>
            <td><?php echo php_uname('m'); ?></td>
          </tr>
          <tr>
            <td><strong>Total Disk Space:</strong></td>
            <td><?php echo round(disk_total_space("/") / 1073741824, 2) . ' GB'; ?></td>
          </tr>
          <tr>
            <td><strong>Free Disk Space:</strong></td>
            <td><?php echo round(disk_free_space("/") / 1073741824, 2) . ' GB'; ?></td>
          </tr>
          <tr>
            <td><strong>Used Disk Space:</strong></td>
            <td><?php echo round((disk_total_space("/") - disk_free_space("/")) / 1073741824, 2) . ' GB'; ?></td>
          </tr>
          <tr>
            <td><strong>Server Time:</strong></td>
            <td><?php echo date('Y-m-d H:i:s a'); ?></td>
          </tr>
          <tr>
            <td><strong>Uptime:</strong></td>
            <td>
              <?php
              $uptime = shell_exec("uptime -p");
              echo $uptime ? $uptime : "N/A";
              ?>
            </td>
          </tr>
          <tr>
            <td><strong>Current User:</strong></td>
            <td><?php echo get_current_user(); ?></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <!-- Detailed Monitoring Section -->
  <div class="row mt-4">
    <!-- System Information -->
    <div class="col-lg-6">
      <div class="card">
        <div class="card-header bg-primary text-white">
          <h5 class="card-title mb-0">
            <i class="mdi mdi-server"></i> System Information
          </h5>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-sm mb-0">
              <tbody>
                <tr>
                  <td class="fw-medium">PHP Version</td>
                  <td><?php echo $php_version; ?></td>
                </tr>
                <tr>
                  <td class="fw-medium">Memory Limit</td>
                  <td><?php echo $php_memory_limit; ?></td>
                </tr>
                <tr>
                  <td class="fw-medium">Max Execution Time</td>
                  <td><?php echo $php_max_execution_time; ?>s</td>
                </tr>
                <tr>
                  <td class="fw-medium">Upload Max Size</td>
                  <td><?php echo $php_upload_max_filesize; ?></td>
                </tr>
                <tr>
                  <td class="fw-medium">CPU Cores</td>
                  <td><?php echo $core_count; ?> cores</td>
                </tr>
                <tr>
                  <td class="fw-medium">Load Average</td>
                  <td><?php echo implode(', ', array_map(function($l) { return round($l, 2); }, $load)); ?></td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- Database Performance -->
    <div class="col-lg-6">
      <div class="card">
        <div class="card-header bg-success text-white">
          <h5 class="card-title mb-0">
            <i class="mdi mdi-database"></i> Database Performance
          </h5>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-sm mb-0">
              <tbody>
                <tr>
                  <td class="fw-medium">Active Connections</td>
                  <td>
                    <span class="badge bg-info"><?php echo $db_connections; ?></span>
                  </td>
                </tr>
                <tr>
                  <td class="fw-medium">Queries/Second</td>
                  <td><?php echo $db_queries_per_second; ?></td>
                </tr>
                <tr>
                  <td class="fw-medium">Slow Queries</td>
                  <td>
                    <span class="badge bg-<?php echo $db_slow_queries > 0 ? 'warning' : 'success'; ?>">
                      <?php echo $db_slow_queries; ?>
                    </span>
                  </td>
                </tr>
                <tr>
                  <td class="fw-medium">Database Status</td>
                  <td>
                    <span class="badge bg-success">
                      <i class="mdi mdi-check"></i> Connected
                    </span>
                  </td>
                </tr>
                <tr>
                  <td class="fw-medium">Connection Health</td>
                  <td>
                    <?php
                    $health_color = $db_connections < 50 ? 'success' : ($db_connections < 100 ? 'warning' : 'danger');
                    $health_text = $db_connections < 50 ? 'Optimal' : ($db_connections < 100 ? 'Moderate' : 'High');
                    ?>
                    <span class="badge bg-<?php echo $health_color; ?>"><?php echo $health_text; ?></span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Network & Security Section -->
  <div class="row mt-4">
    <!-- Network Statistics -->
    <div class="col-lg-4">
      <div class="card">
        <div class="card-header bg-info text-white">
          <h5 class="card-title mb-0">
            <i class="mdi mdi-network"></i> Network Stats
          </h5>
        </div>
        <div class="card-body">
          <div class="d-flex justify-content-between mb-3">
            <span class="text-muted">RX Bytes</span>
            <span class="fw-medium"><?php echo $network_stats['rx_bytes']; ?></span>
          </div>
          <div class="d-flex justify-content-between mb-3">
            <span class="text-muted">TX Bytes</span>
            <span class="fw-medium"><?php echo $network_stats['tx_bytes']; ?></span>
          </div>
          <div class="d-flex justify-content-between mb-3">
            <span class="text-muted">RX Packets</span>
            <span class="fw-medium"><?php echo $network_stats['rx_packets']; ?></span>
          </div>
          <div class="d-flex justify-content-between">
            <span class="text-muted">TX Packets</span>
            <span class="fw-medium"><?php echo $network_stats['tx_packets']; ?></span>
          </div>
        </div>
      </div>
    </div>

    <!-- Recent Activity -->
    <div class="col-lg-4">
      <div class="card">
        <div class="card-header bg-warning text-white">
          <h5 class="card-title mb-0">
            <i class="mdi mdi-clock-time-four"></i> Recent Activity
          </h5>
        </div>
        <div class="card-body">
          <div class="activity-timeline">
            <?php
            // Get recent user activity
            try {
              $sql = "SELECT username, login_time FROM system_user ORDER BY login_time DESC LIMIT 5";
              $stmt = $conn->query($sql);
              $recent_activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
            } catch (Exception $e) {
              $recent_activities = [];
            }
            
            if (!empty($recent_activities)) {
              foreach ($recent_activities as $activity) {
                $time_ago = $activity['login_time'] ? date('M j, H:i', strtotime($activity['login_time'])) : 'Unknown';
                echo "<div class='d-flex mb-2'>";
                echo "<div class='flex-shrink-0'>";
                echo "<div class='avatar-xs'>";
                echo "<div class='avatar-title rounded-circle bg-soft-primary text-primary'>";
                echo "<i class='mdi mdi-account'></i>";
                echo "</div></div></div>";
                echo "<div class='flex-grow-1 ms-2'>";
                echo "<p class='mb-0 text-muted'><strong>{$activity['username']}</strong> logged in</p>";
                echo "<p class='mb-0 text-muted font-size-12'>{$time_ago}</p>";
                echo "</div></div>";
              }
            } else {
              echo "<p class='text-muted text-center'>No recent activity</p>";
            }
            ?>
          </div>
        </div>
      </div>
    </div>

    <!-- System Health -->
    <div class="col-lg-4">
      <div class="card">
        <div class="card-header bg-danger text-white">
          <h5 class="card-title mb-0">
            <i class="mdi mdi-heart-pulse"></i> System Health
          </h5>
        </div>
        <div class="card-body">
          <div class="health-metrics">
            <div class="d-flex justify-content-between align-items-center mb-3">
              <span class="text-muted">CPU Health</span>
              <span class="badge bg-<?php echo $cpu_color; ?> font-size-12">
                <?php echo $cpu_percent <= 50 ? 'Good' : ($cpu_percent <= 80 ? 'Warning' : 'Critical'); ?>
              </span>
            </div>
            
            <div class="d-flex justify-content-between align-items-center mb-3">
              <span class="text-muted">Memory Health</span>
              <span class="badge bg-<?php echo $ram_color; ?> font-size-12">
                <?php echo $ram_percent <= 50 ? 'Good' : ($ram_percent <= 80 ? 'Warning' : 'Critical'); ?>
              </span>
            </div>
            
            <div class="d-flex justify-content-between align-items-center mb-3">
              <span class="text-muted">Disk Health</span>
              <span class="badge bg-<?php echo $disk_color; ?> font-size-12">
                <?php echo $disk_percent <= 50 ? 'Good' : ($disk_percent <= 80 ? 'Warning' : 'Critical'); ?>
              </span>
            </div>
            
            <div class="d-flex justify-content-between align-items-center mb-3">
              <span class="text-muted">Database Health</span>
              <span class="badge bg-<?php echo $db_connections < 50 ? 'success' : 'warning'; ?> font-size-12">
                <?php echo $db_connections < 50 ? 'Good' : 'Moderate'; ?>
              </span>
            </div>
            
            <div class="d-flex justify-content-between align-items-center">
              <span class="text-muted">Overall Status</span>
              <?php
              $overall_health = 'success';
              if ($cpu_percent > 80 || $ram_percent > 80 || $disk_percent > 80 || $db_connections > 100) {
                $overall_health = 'danger';
              } elseif ($cpu_percent > 50 || $ram_percent > 50 || $disk_percent > 50 || $db_connections > 50) {
                $overall_health = 'warning';
              }
              ?>
              <span class="badge bg-<?php echo $overall_health; ?> font-size-12">
                <i class="mdi mdi-<?php echo $overall_health == 'success' ? 'check' : ($overall_health == 'warning' ? 'alert' : 'close'); ?>"></i>
                <?php echo $overall_health == 'success' ? 'Healthy' : ($overall_health == 'warning' ? 'Warning' : 'Critical'); ?>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>




<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  var ctx = document.getElementById('licenseChart').getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['Active', 'Inactive'],
      datasets: [{
        data: [<?php echo $total_active; ?>, <?php echo $all_licenses - $total_active; ?>],
        backgroundColor: ['#28a745', '#dc3545']
      }]
    }
  });
</script>

<?php
include realpath(dirname(__DIR__) . '/include/footer.php');
?>