<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

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

// Get system metrics
function getServerMetrics() {
   return [
       'cpu_usage' => sys_getloadavg()[0],
       'memory_usage' => memory_get_usage(true),
       'disk_free' => disk_free_space("/"),
       'disk_total' => disk_total_space("/")
   ];
}

function getDatabaseMetrics($conn) {
   // Get database size
   $sql = "SELECT table_schema AS db_name, 
           ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size 
           FROM information_schema.tables 
           WHERE table_schema = DATABASE()
           GROUP BY table_schema";
   $result = $conn->query($sql);
   $db_size = $result->fetch_assoc()['size'];

   // Get table counts
   $sql = "SELECT COUNT(*) as table_count 
           FROM information_schema.tables 
           WHERE table_schema = DATABASE()";
   $result = $conn->query($sql);
   $table_count = $result->fetch_assoc()['table_count'];

   return [
       'db_size' => $db_size,
       'table_count' => $table_count
   ];
}

function getApplicationMetrics($conn) {
   // Get user counts
   $sql = "SELECT COUNT(*) as total_users FROM users WHERE verified = 1";
   $result = $conn->query($sql);
   $active_users = $result->fetch_assoc()['total_users'];

   // Get today's activity
   $sql = "SELECT COUNT(*) as today_logs 
           FROM activity_log 
           WHERE DATE(action_date) = CURDATE()";
   $result = $conn->query($sql);
   $today_activity = $result->fetch_assoc()['today_logs'];

   return [
       'active_users' => $active_users,
       'today_activity' => $today_activity
   ];
}

$server_metrics = getServerMetrics();
$db_metrics = getDatabaseMetrics($conn);
$app_metrics = getApplicationMetrics($conn);
?>

<!DOCTYPE html>
<html>
<head>
   <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'System Status')); ?>
   <?php include 'layouts/head-css.php'; ?>
</head>

<body>
   <div id="layout-wrapper">
       <?php include 'layouts/menu.php'; ?>
       
       <div class="main-content">
           <div class="page-content">
               <div class="container-fluid">
                   <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System', 'title' => 'System Status')); ?>

                   <!-- System Overview -->
                   <div class="row">
                       <div class="col-xl-12">
                           <div class="card">
                               <div class="card-header d-flex align-items-center">
                                   <h4 class="card-title mb-0 flex-grow-1">System Overview</h4>
                                   <div class="flex-shrink-0">
                                       <div id="system-status" class="badge bg-success">System Operational</div>
                                   </div>
                               </div>
                           </div>
                       </div>
                   </div>

                   <!-- Server Metrics -->
                   <div class="row">
                       <div class="col-xl-4">
                           <div class="card">
                               <div class="card-header">
                                   <h4 class="card-title mb-0">Server Metrics</h4>
                               </div>
                               <div class="card-body">
                                   <div class="mb-4">
                                       <h5 class="text-muted mb-3">CPU Usage</h5>
                                       <div class="progress" style="height: 20px;">
                                           <?php $cpu_percent = min(($server_metrics['cpu_usage'] * 100), 100); ?>
                                           <div class="progress-bar <?php echo $cpu_percent > 80 ? 'bg-danger' : ($cpu_percent > 60 ? 'bg-warning' : 'bg-success'); ?>" 
                                                role="progressbar" 
                                                style="width: <?php echo $cpu_percent; ?>%">
                                               <?php echo number_format($cpu_percent, 1); ?>%
                                           </div>
                                       </div>
                                   </div>

                                   <div class="mb-4">
                                       <h5 class="text-muted mb-3">Memory Usage</h5>
                                       <div class="progress" style="height: 20px;">
                                           <?php $memory_percent = ($server_metrics['memory_usage'] / (2 * 1024 * 1024 * 1024)) * 100; ?>
                                           <div class="progress-bar <?php echo $memory_percent > 80 ? 'bg-danger' : ($memory_percent > 60 ? 'bg-warning' : 'bg-success'); ?>" 
                                                role="progressbar" 
                                                style="width: <?php echo $memory_percent; ?>%">
                                               <?php echo number_format($memory_percent, 1); ?>%
                                           </div>
                                       </div>
                                   </div>

                                   <div>
                                       <h5 class="text-muted mb-3">Disk Usage</h5>
                                       <div class="progress" style="height: 20px;">
                                           <?php $disk_percent = (($server_metrics['disk_total'] - $server_metrics['disk_free']) / $server_metrics['disk_total']) * 100; ?>
                                           <div class="progress-bar <?php echo $disk_percent > 80 ? 'bg-danger' : ($disk_percent > 60 ? 'bg-warning' : 'bg-success'); ?>" 
                                                role="progressbar" 
                                                style="width: <?php echo $disk_percent; ?>%">
                                               <?php echo number_format($disk_percent, 1); ?>%
                                           </div>
                                       </div>
                                   </div>
                               </div>
                           </div>
                       </div>

                       <!-- Database Metrics -->
                       <div class="col-xl-4">
                           <div class="card">
                               <div class="card-header">
                                   <h4 class="card-title mb-0">Database Metrics</h4>
                               </div>
                               <div class="card-body">
                                   <div class="d-flex flex-column gap-4">
                                       <div class="text-center">
                                           <h5 class="fs-4 mb-1"><?php echo $db_metrics['db_size']; ?> MB</h5>
                                           <p class="text-muted mb-0">Database Size</p>
                                       </div>

                                       <div class="text-center">
                                           <h5 class="fs-4 mb-1"><?php echo $db_metrics['table_count']; ?></h5>
                                           <p class="text-muted mb-0">Total Tables</p>
                                       </div>

                                       <div class="text-center">
                                           <h5 class="fs-4 mb-1"><?php echo date('Y-m-d H:i', strtotime('-1 hour')); ?></h5>
                                           <p class="text-muted mb-0">Last Backup</p>
                                       </div>
                                   </div>
                               </div>
                           </div>
                       </div>

                       <!-- Application Metrics -->
                       <div class="col-xl-4">
                           <div class="card">
                               <div class="card-header">
                                   <h4 class="card-title mb-0">Application Metrics</h4>
                               </div>
                               <div class="card-body">
                                   <div class="d-flex flex-column gap-4">
                                       <div class="text-center">
                                           <h5 class="fs-4 mb-1"><?php echo $app_metrics['active_users']; ?></h5>
                                           <p class="text-muted mb-0">Active Users</p>
                                       </div>

                                       <div class="text-center">
                                           <h5 class="fs-4 mb-1"><?php echo $app_metrics['today_activity']; ?></h5>
                                           <p class="text-muted mb-0">Today's Activities</p>
                                       </div>

                                       <div class="alert alert-info mb-0">
                                           <div class="d-flex gap-2">
                                               <div class="flex-shrink-0">
                                                   <i class="ri-information-line fs-4"></i>
                                               </div>
                                               <div>
                                                   <h5 class="alert-heading">PHP Version: <?php echo phpversion(); ?></h5>
                                                   <p class="mb-0">Server Time: <?php echo date('Y-m-d H:i:s'); ?></p>
                                               </div>
                                           </div>
                                       </div>
                                   </div>
                               </div>
                           </div>
                       </div>
                   </div>

                   <!-- Recent Errors -->
                   <div class="row">
                       <div class="col-xl-12">
                           <div class="card">
                               <div class="card-header">
                                   <h4 class="card-title mb-0">Recent System Errors</h4>
                               </div>
                               <div class="card-body">
                                   <div class="table-responsive">
                                       <table class="table table-hover">
                                           <thead>
                                               <tr>
                                                   <th>Time</th>
                                                   <th>Type</th>
                                                   <th>Message</th>
                                                   <th>File</th>
                                                   <th>Line</th>
                                               </tr>
                                           </thead>
                                           <tbody>
                                               <?php
                                               $error_log = file_exists('error.log') ? file('error.log') : [];
                                               $errors = array_slice($error_log, -5);
                                               foreach($errors as $error):
                                                   $parts = explode('|', $error);
                                               ?>
                                               <tr>
                                                   <td><?php echo $parts[0] ?? ''; ?></td>
                                                   <td>
                                                       <span class="badge bg-danger">
                                                           <?php echo $parts[1] ?? ''; ?>
                                                       </span>
                                                   </td>
                                                   <td><?php echo $parts[2] ?? ''; ?></td>
                                                   <td><?php echo $parts[3] ?? ''; ?></td>
                                                   <td><?php echo $parts[4] ?? ''; ?></td>
                                               </tr>
                                               <?php endforeach; ?>
                                           </tbody>
                                       </table>
                                   </div>
                               </div>
                           </div>
                       </div>
                   </div>

               </div>
           </div>
           <?php include 'layouts/footer.php'; ?>
       </div>
   </div>

   <?php include 'layouts/vendor-scripts.php'; ?>
   <script src="assets/js/app.js"></script>

   <script>
   // Auto-refresh metrics every 30 seconds
   setInterval(function() {
       location.reload();
   }, 30000);
   </script>
</body>
</html>