<?php
session_start();
require_once __DIR__ . '/includes/auth_check.php';
require_once __DIR__ . '/includes/db_connect.php';

// Get basic counts
$pendingCount = (int)$pdo->query("SELECT COUNT(*) FROM recordings WHERE status='pending'")->fetchColumn();
$usersCount = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$approvedCount = (int)$pdo->query("SELECT COUNT(*) FROM recordings WHERE status='approved'")->fetchColumn();
$totalRecordings = $pendingCount + $approvedCount;

// Get active users (active today)
$activeUsers = (int)$pdo->query(
    "SELECT COUNT(DISTINCT user_id) FROM recordings WHERE DATE(created_at) = CURDATE()"
)->fetchColumn();

// Get average recording duration
$avgDuration = $pdo->query(
    "SELECT ROUND(AVG(duration), 1) FROM recordings WHERE duration > 0"
)->fetchColumn() ?: 0;

// Get daily completion rate
try {
    $todayCompleted = (int)$pdo->query(
        "SELECT COUNT(DISTINCT user_id) FROM recordings WHERE DATE(created_at) = CURDATE()"
    )->fetchColumn();
    
    // Use created_at as fallback if last_login doesn't exist
    $activeToday = (int)$pdo->query(
        "SELECT COUNT(*) FROM users WHERE created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)"
    )->fetchColumn();
    
    $completionRate = $activeToday > 0 ? round(($todayCompleted / $activeToday) * 100) : 0;
} catch (PDOException $e) {
    // If there's an error (like missing columns), set default values
    $todayCompleted = 0;
    $activeToday = 0;
    $completionRate = 0;
    error_log("Dashboard stats error: " . $e->getMessage());
}

// Get recent recordings
$recentRecordings = $pdo->query(
    "SELECT r.*, u.full_name, u.phone, t.title as task_title 
     FROM recordings r 
     LEFT JOIN users u ON r.user_id = u.id 
     LEFT JOIN tasks t ON r.task_id = t.id 
     ORDER BY r.created_at DESC LIMIT 5"
)->fetchAll(PDO::FETCH_ASSOC);

// Get recordings by day (last 7 days)
$recordingsByDay = $pdo->query(
    "SELECT 
        DATE(created_at) as day, 
        COUNT(*) as count,
        ROUND(AVG(duration), 1) as avg_duration
     FROM recordings 
     WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
     GROUP BY DATE(created_at)
     ORDER BY day ASC"
)->fetchAll(PDO::FETCH_ASSOC);

// Prepare data for chart
$chartLabels = [];
$chartData = [];
$chartAvgDuration = [];

foreach ($recordingsByDay as $day) {
    $chartLabels[] = date('D', strtotime($day['day']));
    $chartData[] = $day['count'];
    $chartAvgDuration[] = (float)$day['avg_duration'];
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Admin Dashboard</title>
  <link rel="stylesheet" href="assets/theme.css">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    body {
      color: var(--text);
      background: var(--bg);
      margin: 0;
      padding: 0;
      display: flex;
      min-height: 100vh;
    }
    .content {
      background: var(--bg);
      flex-grow: 1;
      padding: 1.5rem;
      margin-left: 250px;
    }
    .sidebar {
      width: 250px;
      background: var(--surface);
      height: 100vh;
      position: fixed;
      left: 0;
      top: 0;
      display: flex;
      flex-direction: column;
      box-shadow: 2px 0 10px rgba(0,0,0,0.1);
    }
    .sidebar-brand {
      padding: 1.5rem;
      font-size: 1.2rem;
      font-weight: 600;
      color: var(--accent-orange);
      border-bottom: 1px solid rgba(255,255,255,0.05);
    }
    .nav {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 1rem 0;
    }
    .nav-item {
      display: flex;
      align-items: center;
      padding: 0.75rem 1.5rem;
      color: var(--muted);
      text-decoration: none;
      transition: all 0.2s;
    }
    .nav-item:hover {
      background: rgba(255,255,255,0.03);
      color: var(--text);
    }
    .nav-item.active {
      background: rgba(255,154,60,0.1);
      color: var(--accent-orange);
      border-left: 3px solid var(--accent-orange);
    }
    .nav-item svg {
      margin-right: 12px;
      flex-shrink: 0;
    }
    .badge {
      margin-left: auto;
      background: var(--accent-orange);
      color: white;
      font-size: 0.7rem;
      padding: 0.2rem 0.5rem;
      border-radius: 10px;
      font-weight: 600;
    }
    h1, h2, h3, h4 {
      color: var(--text);
    }
    .cards {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
      gap: 1.2rem;
      margin-bottom: 2rem;
    }
    .card {
      background: var(--surface);
      border-radius: var(--radius);
      padding: 1.5rem;
      box-shadow: var(--card-shadow);
      border-left: 4px solid var(--accent-orange);
      transition: transform 0.2s, box-shadow 0.2s;
    }
    .card:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(0,0,0,0.3);
    }
    .card h3 {
      margin: 0 0 0.5rem;
      font-size: 0.9rem;
      color: var(--muted);
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }
    .card .big {
      font-size: 2rem;
      font-weight: 700;
      margin: 0;
      color: var(--text);
      background: linear-gradient(90deg, #ff9a3c, #ff7b3b);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      line-height: 1.2;
    }
    .card .subtext {
      font-size: 0.8rem;
      color: var(--muted);
      margin: 0.5rem 0 0;
      line-height: 1.4;
    }
    .card.primary { border-left-color: var(--accent-orange); }
    .card.success { border-left-color: var(--success); }
    .card.warning { border-left-color: #ff9a3c; }
    .card.danger { border-left-color: var(--danger); }
    
    .recent-activity {
      background: var(--surface);
      border-radius: var(--radius);
      padding: 1.5rem;
      margin-top: 2rem;
      box-shadow: var(--card-shadow);
    }
    .recent-activity h3 {
      margin-top: 0;
      color: var(--text);
      padding-bottom: 1rem;
      border-bottom: 1px solid rgba(255,255,255,0.03);
    }
    .activity-item {
      padding: 1rem 0;
      border-bottom: 1px solid rgba(255,255,255,0.03);
      display: flex;
      align-items: center;
      transition: background 0.2s;
    }
    .activity-item:hover {
      background: rgba(255,255,255,0.02);
    }
    .activity-item:last-child {
      border-bottom: none;
    }
    .activity-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: rgba(255, 154, 60, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 1rem;
      flex-shrink: 0;
      color: var(--accent-orange);
    }
    .activity-details {
      flex-grow: 1;
    }
    .activity-details > div:first-child {
      color: var(--text);
      margin-bottom: 0.25rem;
    }
    .activity-time {
      font-size: 0.75rem;
      color: var(--muted);
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }
    .activity-time:before {
      content: '•';
      color: rgba(255,255,255,0.1);
    }
    .chart-container {
      background: var(--surface);
      border-radius: var(--radius);
      padding: 1.5rem;
      margin-top: 2rem;
      box-shadow: var(--card-shadow);
    }
    .chart-container h3 {
      margin-top: 0;
      margin-bottom: 1.5rem;
      color: var(--text);
    }
    .muted {
      color: var(--muted);
      font-style: italic;
      padding: 1rem 0;
    }
  </style>
</head>
<body class="dashboard-page">
  <?php include 'includes/sidebar.php'; ?>

  <main class="main">
    <header class="topbar">
      <div class="topbar-left">Admin Dashboard</div>
      <div class="topbar-right">Welcome, Admin</div>
    </header>

    <section class="content">
      <h1>Dashboard Overview</h1>
      
      <!-- Key Metrics -->
      <div class="cards">
        <div class="card primary">
          <h3>Total Recordings</h3>
          <p class="big"><?=number_format($totalRecordings)?></p>
          <p class="subtext"><?=number_format($approvedCount)?> approved • <?=number_format($pendingCount)?> pending</p>
        </div>
        
        <div class="card success">
          <h3>Active Users</h3>
          <p class="big"><?=number_format($activeUsers)?></p>
          <p class="subtext"><?=number_format($usersCount)?> total users</p>
        </div>
        
        <div class="card warning">
          <h3>Daily Completion</h3>
          <p class="big"><?=$completionRate?>%</p>
          <p class="subtext"><?=$todayCompleted?> of <?=$activeToday?> active users</p>
        </div>
        
        <div class="card danger">
          <h3>Avg. Duration</h3>
          <p class="big"><?=$avgDuration?>s</p>
          <p class="subtext">per recording</p>
        </div>
      </div>

      <!-- Charts Row -->
      <div class="chart-container">
        <h3>Recordings Overview (Last 7 Days)</h3>
        <canvas id="recordingsChart" height="100"></canvas>
      </div>

      <!-- Recent Activity -->
      <div class="recent-activity">
        <h3>Recent Activity</h3>
        <?php if (count($recentRecordings) > 0): ?>
          <?php foreach ($recentRecordings as $recording): ?>
            <div class="activity-item">
              <div class="activity-icon">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                </svg>
              </div>
              <div class="activity-details">
                <div><strong><?=htmlspecialchars($recording['full_name'] ?? 'User #' . $recording['user_id'])?></strong> submitted a recording</div>
                <div class="activity-time">
                  <?php 
                    $timeAgo = time() - strtotime($recording['created_at']);
                    if ($timeAgo < 60) {
                        echo 'Just now';
                    } elseif ($timeAgo < 3600) {
                        echo floor($timeAgo/60) . ' minutes ago';
                    } elseif ($timeAgo < 86400) {
                        echo floor($timeAgo/3600) . ' hours ago';
                    } else {
                        echo date('M j, Y', strtotime($recording['created_at']));
                    }
                  ?>
                  • <?=round($recording['duration'] ?? 0, 1)?>s
                  <?php if (!empty($recording['task_title'])): ?>
                    • <?=htmlspecialchars($recording['task_title'])?>
                  <?php endif; ?>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        <?php else: ?>
          <p class="muted">No recent activity to display.</p>
        <?php endif; ?>
      </div>
    </section>
  </main>
<script src="assets/dashboard.js"></script>
</body>
</html>
