<?php 
session_start();
include "../dbc.php";

if (!isset($_SESSION["login"])) {
  header("Location:login.php");
  exit();
}

// Set timezone
mysqli_query($conn, "SET time_zone = '+08:00'");

// Get user metrics
$user_sql = "SELECT 
    SUM(CASE WHEN expiry_at = '2025-12-31 23:59:00' THEN 1 ELSE 0 END) as subscribed,
    SUM(CASE WHEN expiry_at = DATE_FORMAT(LAST_DAY(NOW()), '%Y-%m-%d 23:59:59') THEN 1 ELSE 0 END) as pending,
    SUM(CASE 
        WHEN expiry_at != '2025-12-31 23:59:00' 
        AND expiry_at != DATE_FORMAT(LAST_DAY(NOW()), '%Y-%m-%d 23:59:59') 
        THEN 1 ELSE 0 END) as unsubscribed
    FROM multi_page_user";
$user_result = mysqli_query($conn, $user_sql);
$user_metrics = mysqli_fetch_assoc($user_result);

// Get active sessions (24h)
$session_sql = "SELECT COUNT(*) as total FROM user_sessions 
               WHERE access_time >= DATE_SUB(NOW(), INTERVAL 24 HOUR)";
$session_result = mysqli_query($conn, $session_sql);
$active_sessions = mysqli_fetch_assoc($session_result)['total'];

// Get channel status
$channel_sql = "SELECT COUNT(*) as total, 
                SUM(CASE 
                    WHEN status = 1 AND updated_at >= DATE_SUB(NOW(), INTERVAL 10 HOUR) THEN 1 
                    ELSE 0 END) as active,
                SUM(CASE 
                    WHEN status = 1 AND updated_at < DATE_SUB(NOW(), INTERVAL 10 HOUR) AND updated_at >= DATE_SUB(NOW(), INTERVAL 12 HOUR) THEN 1
                    ELSE 0 END) as warning,
                SUM(CASE 
                    WHEN status = 0 OR updated_at < DATE_SUB(NOW(), INTERVAL 12 HOUR) THEN 1
                    ELSE 0 END) as inactive
                FROM tk_page";
$channel_result = mysqli_query($conn, $channel_sql);
$channel_metrics = mysqli_fetch_assoc($channel_result);

// Get latest session details
$sessions_sql = "SELECT us.*, mpu.remark, mpu.username 
               FROM user_sessions us
               LEFT JOIN multi_page_user mpu ON us.user_agent = mpu.uagent
               WHERE us.access_time >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
               ORDER BY us.access_time DESC
               LIMIT 10";
$sessions_result = mysqli_query($conn, $sessions_sql);

// Get channel details
$channel_details_sql = "SELECT filename, status, updated_at, remark 
                       FROM tk_page 
                       ORDER BY updated_at DESC";
$channel_details_result = mysqli_query($conn, $channel_details_sql);
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <?php include "inc-dashboard-header.php"; ?>
  <style>
    .card {
      background-color: transparent;
      border: none;
    }
    .card-header {
      background-color: #1e2635;
      border-color: #2d3748;
      color: #b58900;
      padding: 0.75rem;
    }
    .card-body {
      background-color: #1e2635;
      padding: 0;
    }
    .breadcrumb {
      background-color: #1e2635;
      border: none;
      padding: 0.75rem;
      margin-bottom: 1rem;
    }
    .table {
      color: #ffffff;
      margin-bottom: 0;
    }
    .table th {
      background-color: #1a1a1a;
      border-color: #2d3748;
      color: #b58900;
      font-weight: normal;
      text-transform: uppercase;
      padding: 0.75rem;
    }
    .table td {
      border-color: #2d3748;
      padding: 0.75rem;
    }
    .table-striped tbody tr:nth-of-type(odd) {
      background-color: #1e2635;
    }
    .table-striped tbody tr:nth-of-type(even) {
      background-color: #252d3b;
    }
    .table-striped tbody tr:hover {
      background-color: #2d3748;
    }
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
      gap: 1rem;
      margin-bottom: 1rem;
    }
    .stat-card {
      background-color: #1e2635;
      padding: 1rem;
      border-radius: 0.25rem;
    }
    .stat-title {
      color: #b58900;
      font-size: 0.875rem;
      margin-bottom: 0.5rem;
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }
    .stat-value {
      font-size: 1.5rem;
      font-weight: bold;
      margin-bottom: 1rem;
      color: #ffffff;
    }
    .stat-detail {
      display: flex;
      justify-content: space-between;
      margin-bottom: 0.5rem;
    }
    .text-success {
      color: #28a745 !important;
    }
    .text-danger {
      color: #dc3545 !important;
    }
    .text-warning {
      color: #ffc107 !important;
    }
  </style>
</head>

<body id="page-top">
  <?php include "inc-dashboard-topbar.php"; ?>

  <div id="wrapper">
    <div id="content-wrapper">
      <div class="container-fluid">
        <ol class="breadcrumb">
          <li class="breadcrumb-item">
            <b>DASHBOARD</b>
          </li>
        </ol>

        <!-- Stats Grid -->
        <div class="stats-grid">
          <!-- Total Users -->
          <div class="stat-card">
            <div class="stat-title">
              <i class="fas fa-users"></i> Total Users
            </div>
            <div class="stat-value">
              <?= $user_metrics['subscribed'] + $user_metrics['unsubscribed'] + $user_metrics['pending'] ?>
            </div>
            <div class="stat-details">
              <div class="stat-detail">
                <span class="text-success">Subscribed</span>
                <span><?= $user_metrics['subscribed'] ?></span>
              </div>
              <div class="stat-detail">
                <span class="text-danger">Unsubscribed</span>
                <span><?= $user_metrics['unsubscribed'] ?></span>
              </div>
              <div class="stat-detail">
                <span class="text-warning">Pending</span>
                <span><?= $user_metrics['pending'] ?></span>
              </div>
            </div>
          </div>

          <!-- Active Sessions -->
          <div class="stat-card">
            <div class="stat-title">
              <i class="fas fa-clock"></i> Active Sessions (24h)
            </div>
            <div class="stat-value">
              <?= $active_sessions ?>
            </div>
          </div>

          <!-- Channel Status -->
          <div class="stat-card">
            <div class="stat-title">
              <i class="fas fa-broadcast-tower"></i> Channel Status
            </div>
            <div class="stat-value">
              <?= $channel_metrics['total'] ?>
            </div>
            <div class="stat-details">
              <div class="stat-detail">
                <span class="text-success">Active</span>
                <span><?= $channel_metrics['active'] ?></span>
              </div>
              <div class="stat-detail">
                <span class="text-danger">Inactive</span>
                <span><?= $channel_metrics['inactive'] ?></span>
              </div>
              <div class="stat-detail">
                <span class="text-warning">Warning</span>
                <span><?= $channel_metrics['warning'] ?></span>
              </div>
            </div>
          </div>

          <!-- Total Channels -->
          <div class="stat-card">
            <div class="stat-title">
              <i class="fas fa-tv"></i> Total Channels
            </div>
            <div class="stat-value">
              <?= $channel_metrics['total'] ?>
            </div>
          </div>
        </div>

        <!-- Channel Status Table -->
        <div class="card mb-3">
          <div class="card-header">
            <i class="fas fa-table"></i>
            Channel Status Overview
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-striped" id="channelTable" width="100%" cellspacing="0">
                <thead class="bg-info">
                  <tr>
                    <th>CHANNEL NAME</th>
                    <th>STATUS</th>
                    <th>LAST UPDATE</th>
                    <th>REMARK</th>
                  </tr>
                </thead>
                <tbody>
                  <?php while ($row = mysqli_fetch_assoc($channel_details_result)) { 
                    $updated_at = strtotime($row["updated_at"]);
                    $current_time = time();
                    $time_diff = $current_time - $updated_at;
                    $status_class = 'text-success';
                    $status_text = 'Active';
                    
                    if ($time_diff > 36000 && $time_diff <= 43200) {
                      $status_class = 'text-warning';
                      $status_text = 'Warning';
                    } elseif ($time_diff > 43200 || $row["status"] == 0) {
                      $status_class = 'text-danger';
                      $status_text = 'Inactive';
                    }
                  ?>
                    <tr>
                      <td><?= htmlspecialchars($row["filename"]) ?></td>
                      <td><span class="<?= $status_class ?>"><?= $status_text ?></span></td>
                      <td><?= date("d/m/Y h:i A", strtotime($row["updated_at"])) ?></td>
                      <td><?= htmlspecialchars($row["remark"]) ?></td>
                    </tr>
                  <?php } ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- Active Sessions Table -->
        <div class="card mb-3">
          <div class="card-header">
            <i class="fas fa-users"></i>
            Active Sessions (Last 24 Hours)
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-striped" id="sessionTable" width="100%" cellspacing="0">
                <thead class="bg-info">
                  <tr>
                    <th>#</th>
                    <th>USERNAME</th>
                    <th>USER AGENT</th>
                    <th>IP ADDRESS</th>
                    <th>LAST ACTIVITY</th>
                    <th>DEVICE FINGERPRINT</th>
                    <th>REMARK</th>
                  </tr>
                </thead>
                <tbody>
                  <?php 
                  $count = 0;
                  while ($row = mysqli_fetch_assoc($sessions_result)) {
                    $count++;
                  ?>
                    <tr>
                      <td><?= $count ?></td>
                      <td><?= htmlspecialchars($row["username"] ?? 'N/A') ?></td>
                      <td><?= htmlspecialchars($row["user_agent"]) ?></td>
                      <td><?= htmlspecialchars($row["ip_address"]) ?></td>
                      <td><?= date("d/m/Y h:i A", strtotime($row["access_time"])) ?></td>
                      <td><?= htmlspecialchars($row["device_fingerprint"]) ?></td>
                      <td><?= htmlspecialchars($row["remark"] ?? 'N/A') ?></td>
                    </tr>
                  <?php } ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>

      <?php include "inc-dashboard-footer.php"; ?>
    </div>
  </div>

  <?php include "inc-dashboard-bottom.php"; ?>

  <script type="text/javascript">
    $(document).ready(function() {
      $('#channelTable, #sessionTable').DataTable({
        "pageLength": 25,
        "order": [[2, "desc"]]
      });
    });
  </script>
</body>
</html>