<?php
require_once '../includes/config.php';
requireAdmin();
require_once 'includes/header.php';

$totalUsers = $pdo->query("SELECT COUNT(*) FROM users WHERE is_verified=1")->fetchColumn();
$totalStudySessions = $pdo->query("SELECT COUNT(*) FROM study_sessions")->fetchColumn();
$totalMarks = $pdo->query("SELECT COUNT(*) FROM marks")->fetchColumn();
$totalTasks = $pdo->query("SELECT COUNT(*) FROM tasks")->fetchColumn();
$newToday = $pdo->query("SELECT COUNT(*) FROM users WHERE DATE(created_at)=CURDATE()")->fetchColumn();

// Real-time active users (sessions in last 30 mins)
$activeNow = $pdo->query("SELECT COUNT(DISTINCT user_id) FROM study_sessions WHERE created_at >= NOW() - INTERVAL 30 MINUTE")->fetchColumn();

// At-risk users: not logged in for 7+ days
$atRiskUsers = $pdo->query("SELECT id, name, email, last_login FROM users WHERE is_verified=1 AND (is_disabled IS NULL OR is_disabled=0) AND (last_login IS NULL OR last_login < NOW() - INTERVAL 7 DAY) ORDER BY last_login DESC LIMIT 8")->fetchAll();

// Subject popularity
$subjectStats = $pdo->query("SELECT sub.name, COUNT(ss.id) as session_count FROM study_sessions ss JOIN subjects sub ON ss.subject_id=sub.id GROUP BY ss.subject_id ORDER BY session_count DESC LIMIT 8")->fetchAll();

// Top active users
$topUsersQ = $pdo->query("SELECT u.name, u.email, COUNT(ss.id) as sessions, COALESCE(SUM(ss.duration_minutes),0) as total_mins FROM users u LEFT JOIN study_sessions ss ON u.id=ss.user_id WHERE u.is_verified=1 GROUP BY u.id ORDER BY total_mins DESC LIMIT 10");
$topUsers = $topUsersQ->fetchAll();

// Activity last 30 days
$activityData = [];
for ($i=29; $i>=0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $q = $pdo->prepare("SELECT COUNT(DISTINCT user_id) FROM study_sessions WHERE date=?");
    $q->execute([$d]); $activityData[] = ['date'=>date('M j',strtotime($d)), 'users'=>(int)$q->fetchColumn()];
}

// User growth last 30 days
$growthData = [];
for ($i=29; $i>=0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $q = $pdo->prepare("SELECT COUNT(*) FROM users WHERE DATE(created_at)=?");
    $q->execute([$d]); $growthData[] = ['date'=>date('M j',strtotime($d)), 'count'=>(int)$q->fetchColumn()];
}

// Heatmap data: study sessions by day-of-week and hour
$heatmapRaw = $pdo->query("SELECT DAYOFWEEK(created_at)-1 as dow, HOUR(created_at) as hr, COUNT(*) as cnt FROM study_sessions WHERE created_at >= NOW() - INTERVAL 90 DAY GROUP BY dow, hr")->fetchAll();
$heatmap = [];
foreach ($heatmapRaw as $r) $heatmap[$r['dow']][$r['hr']] = (int)$r['cnt'];

$exam = $pdo->query("SELECT * FROM al_exam_dates WHERE is_active=1 ORDER BY exam_date ASC LIMIT 1")->fetch();

renderAdminHeader('Admin Dashboard', 'dashboard');
?>

<?php if ($exam): ?>
<div class="countdown-card" style="margin-bottom:20px">
  <div class="countdown-title">⏳ A/L Exam Countdown</div>
  <div class="countdown-exam"><?= htmlspecialchars($exam['exam_name']) ?> — <?= date('F j, Y',strtotime($exam['exam_date'])) ?></div>
  <div class="countdown-units">
    <div class="countdown-unit"><span class="countdown-num" id="cd-days">00</span><span class="countdown-label">Days</span></div>
    <div class="countdown-unit"><span class="countdown-num" id="cd-hours">00</span><span class="countdown-label">Hours</span></div>
    <div class="countdown-unit"><span class="countdown-num" id="cd-mins">00</span><span class="countdown-label">Minutes</span></div>
    <div class="countdown-unit"><span class="countdown-num" id="cd-secs">00</span><span class="countdown-label">Seconds</span></div>
  </div>
</div>
<script>startCountdown('<?= $exam['exam_date'] ?> 08:00:00','countdown');</script>
<?php endif; ?>

<div class="stats-grid">
  <div class="stat-card"><div class="stat-icon" style="background:rgba(99,102,241,0.15)">👥</div><div class="stat-value"><?= $totalUsers ?></div><div class="stat-label">Registered Students</div><div class="stat-change up">+<?= $newToday ?> today</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(6,182,212,0.15)">⏱️</div><div class="stat-value"><?= number_format($totalStudySessions) ?></div><div class="stat-label">Study Sessions</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(16,185,129,0.15)">📝</div><div class="stat-value"><?= $totalMarks ?></div><div class="stat-label">Exam Results Logged</div></div>
  <div class="stat-card"><div class="stat-icon" style="background:rgba(245,158,11,0.15)">✅</div><div class="stat-value"><?= $totalTasks ?></div><div class="stat-label">Tasks Created</div></div>
</div>

<!-- Real-time Active Users -->
<div class="card" style="margin-bottom:20px;border-left:3px solid #10b981">
  <div class="card-header" style="align-items:center">
    <div class="card-title">🟢 Active Right Now</div>
    <span style="font-size:12px;color:var(--text-muted)" id="lastRefreshed">Auto-refreshes every 60s</span>
  </div>
  <div style="display:flex;align-items:center;gap:16px;padding:8px 0">
    <div style="font-size:48px;font-weight:700;color:#10b981" id="activeNowCount"><?= $activeNow ?></div>
    <div style="color:var(--text-muted);font-size:14px">students studying<br>in the last 30 minutes</div>
    <div style="margin-left:auto"><span id="activePulse" style="display:inline-block;width:10px;height:10px;background:#10b981;border-radius:50%;animation:pulse 2s infinite"></span></div>
  </div>
</div>

<!-- Charts Row -->
<div class="grid-2" style="margin-bottom:20px">
  <div class="card">
    <div class="card-header">
      <div class="card-title">📊 Platform Activity</div>
      <div style="display:flex;gap:4px">
        <button class="btn btn-secondary btn-sm chart-toggle active" data-chart="activity" data-period="30">30d</button>
        <button class="btn btn-secondary btn-sm chart-toggle" data-chart="activity" data-period="7">7d</button>
      </div>
    </div>
    <div class="chart-container" style="height:220px"><canvas id="activityChart"></canvas></div>
  </div>
  <div class="card">
    <div class="card-header">
      <div class="card-title">📈 New Registrations</div>
      <div style="display:flex;gap:4px">
        <button class="btn btn-secondary btn-sm chart-toggle active" data-chart="growth" data-period="30">30d</button>
        <button class="btn btn-secondary btn-sm chart-toggle" data-chart="growth" data-period="7">7d</button>
      </div>
    </div>
    <div class="chart-container" style="height:220px"><canvas id="growthChart"></canvas></div>
  </div>
</div>

<!-- Activity Heatmap -->
<div class="card" style="margin-bottom:20px">
  <div class="card-header"><div class="card-title">🔥 Study Activity Heatmap (Last 90 Days)</div></div>
  <div style="overflow-x:auto;padding:8px 0">
  <table style="border-collapse:collapse;font-size:11px;width:100%">
    <thead><tr>
      <th style="width:50px;text-align:right;padding-right:8px;color:var(--text-muted)"></th>
      <?php for($h=0;$h<24;$h++): ?>
      <th style="text-align:center;color:var(--text-muted);padding:2px 3px;font-weight:400"><?= $h ?></th>
      <?php endfor; ?>
    </tr></thead>
    <tbody>
    <?php
    $days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
    $maxVal = 1;
    foreach($heatmap as $row) foreach($row as $v) if($v > $maxVal) $maxVal = $v;
    foreach($days as $di => $dname):
    ?>
    <tr>
      <td style="text-align:right;padding-right:8px;color:var(--text-muted);font-weight:500"><?= $dname ?></td>
      <?php for($h=0;$h<24;$h++):
        $v = $heatmap[$di][$h] ?? 0;
        $intensity = $maxVal > 0 ? $v / $maxVal : 0;
        $alpha = round($intensity * 0.9 + ($v > 0 ? 0.05 : 0), 2);
        $bg = $v > 0 ? "rgba(168,85,247,$alpha)" : "rgba(42,42,61,0.3)";
      ?>
      <td title="<?= $dname ?> <?= $h ?>:00 — <?= $v ?> sessions" style="width:3.5%;padding:3px;text-align:center">
        <div style="width:100%;aspect-ratio:1;background:<?= $bg ?>;border-radius:3px;min-width:14px"></div>
      </td>
      <?php endfor; ?>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  <div style="display:flex;align-items:center;gap:6px;margin-top:8px;font-size:11px;color:var(--text-muted)">
    <span>Less</span>
    <?php for($i=0;$i<=4;$i++): $a = $i*0.225; ?>
    <div style="width:14px;height:14px;background:rgba(168,85,247,<?= $a ?>);border-radius:3px;border:1px solid rgba(168,85,247,0.2)"></div>
    <?php endfor; ?>
    <span>More</span>
  </div>
  </div>
</div>

<!-- Subject Popularity + Top Students -->
<div class="grid-2" style="margin-bottom:20px">
  <div class="card">
    <div class="card-header"><div class="card-title">📚 Subject Popularity</div></div>
    <?php if($subjectStats): ?>
    <?php $maxSessions = max(array_column($subjectStats,'session_count')); ?>
    <div style="display:flex;flex-direction:column;gap:10px;padding:4px 0">
    <?php foreach($subjectStats as $s):
      $pct = $maxSessions > 0 ? round($s['session_count']/$maxSessions*100) : 0;
    ?>
    <div>
      <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:4px">
        <span style="color:var(--text-primary)"><?= htmlspecialchars($s['name']) ?></span>
        <span style="color:var(--text-muted)"><?= $s['session_count'] ?> sessions</span>
      </div>
      <div style="background:var(--border);border-radius:4px;height:6px">
        <div style="background:var(--accent);border-radius:4px;height:6px;width:<?= $pct ?>%"></div>
      </div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php else: ?><p style="color:var(--text-muted)">No data yet.</p><?php endif; ?>
  </div>

  <div class="card">
    <div class="card-header"><div class="card-title">🏆 Top Students by Study Time</div></div>
    <?php if ($topUsers): ?>
    <div class="table-wrapper"><table>
      <thead><tr><th>#</th><th>Student</th><th>Sessions</th><th>Total Time</th></tr></thead>
      <tbody>
      <?php foreach ($topUsers as $i=>$u): ?>
      <tr>
        <td style="font-weight:700;color:var(--accent)"><?= $i+1 ?></td>
        <td><div style="font-weight:500;color:var(--text-primary)"><?= htmlspecialchars($u['name']) ?></div><div style="font-size:12px;color:var(--text-muted)"><?= htmlspecialchars($u['email']) ?></div></td>
        <td><?= $u['sessions'] ?></td>
        <td><?= floor($u['total_mins']/60) ?>h <?= $u['total_mins']%60 ?>m</td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table></div>
    <?php endif; ?>
  </div>
</div>

<!-- At-Risk Users Widget -->
<?php if($atRiskUsers): ?>
<div class="card" style="margin-bottom:20px;border-left:3px solid #ef4444">
  <div class="card-header">
    <div class="card-title">⚠️ At-Risk Users <span style="font-size:12px;font-weight:400;color:var(--text-muted)">(Not logged in for 7+ days)</span></div>
    <a href="<?= SITE_URL ?>/admin/users.php?filter=inactive" class="btn btn-secondary btn-sm">View All</a>
  </div>
  <div class="table-wrapper"><table>
    <thead><tr><th>Student</th><th>Last Login</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach($atRiskUsers as $u): ?>
    <tr>
      <td><div style="font-weight:500;color:var(--text-primary)"><?= htmlspecialchars($u['name']) ?></div><div style="font-size:12px;color:var(--text-muted)"><?= htmlspecialchars($u['email']) ?></div></td>
      <td style="color:var(--text-muted);font-size:13px"><?= $u['last_login'] ? date('M j, Y', strtotime($u['last_login'])) : 'Never' ?></td>
      <td>
        <a href="<?= SITE_URL ?>/admin/notifications.php?prefill_user=<?= $u['id'] ?>" class="btn btn-secondary btn-sm" title="Send notification">🔔 Notify</a>
        <a href="<?= SITE_URL ?>/admin/user-details.php?id=<?= $u['id'] ?>" class="btn btn-secondary btn-sm" title="View profile">👤 View</a>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table></div>
</div>
<?php endif; ?>

<style>
@keyframes pulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:.5;transform:scale(1.4)} }
.chart-toggle.active { background:var(--accent)!important;color:#fff!important;border-color:var(--accent)!important }
</style>

<script>
const activityLabels = <?= json_encode(array_column($activityData,'date')) ?>;
const activityValues = <?= json_encode(array_column($activityData,'users')) ?>;
const growthLabels   = <?= json_encode(array_column($growthData,'date')) ?>;
const growthValues   = <?= json_encode(array_column($growthData,'count')) ?>;

function makeChart(id, labels, data, color) {
  return new Chart(document.getElementById(id), {
    type:'line',
    data:{labels,datasets:[{label:'',data,borderColor:color,backgroundColor:color.replace(')',',0.1)').replace('rgb','rgba'),tension:0.4,fill:true,pointBackgroundColor:color,pointRadius:3}]},
    options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{x:{grid:{display:false},ticks:{color:'#64748b'},border:{display:false}},y:{grid:{color:'rgba(42,42,61,0.5)'},ticks:{color:'#64748b'},border:{display:false}}}}
  });
}

let actChart = makeChart('activityChart', activityLabels, activityValues, 'rgb(168,85,247)');
let grwChart = makeChart('growthChart', growthLabels, growthValues, 'rgb(6,182,212)');

document.querySelectorAll('.chart-toggle').forEach(btn => {
  btn.addEventListener('click', function() {
    const chart = this.dataset.chart;
    const period = parseInt(this.dataset.period);
    document.querySelectorAll(`.chart-toggle[data-chart="${chart}"]`).forEach(b=>b.classList.remove('active'));
    this.classList.add('active');
    if(chart === 'activity') {
      actChart.data.labels = activityLabels.slice(-period);
      actChart.data.datasets[0].data = activityValues.slice(-period);
      actChart.update();
    } else {
      grwChart.data.labels = growthLabels.slice(-period);
      grwChart.data.datasets[0].data = growthValues.slice(-period);
      grwChart.update();
    }
  });
});

// Auto refresh active users count
setInterval(() => {
  fetch('<?= SITE_URL ?>/admin/ajax/active-users.php')
    .then(r=>r.json()).then(d=>{
      document.getElementById('activeNowCount').textContent = d.count ?? '—';
      document.getElementById('lastRefreshed').textContent = 'Updated '+new Date().toLocaleTimeString();
    }).catch(()=>{});
}, 60000);
</script>
<?php require_once 'includes/footer.php'; renderAdminFooter(); ?>
