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

// Total study hours per day (last 30 days)
$studyHoursData = [];
for ($i=29;$i>=0;$i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0)/60 FROM study_sessions WHERE date=?");
    $q->execute([$d]);
    $studyHoursData[] = ['date'=>date('M j',strtotime($d)), 'hours'=>round((float)$q->fetchColumn(),1)];
}

// Average session length
$avgSession = $pdo->query("SELECT ROUND(AVG(duration_minutes),1) FROM study_sessions WHERE duration_minutes > 0")->fetchColumn();

// Peak study hour
$peakHour = $pdo->query("SELECT HOUR(created_at) as hr, COUNT(*) as cnt FROM study_sessions GROUP BY hr ORDER BY cnt DESC LIMIT 1")->fetch();

// Subject distribution
$subjectDist = $pdo->query("SELECT sub.name, COUNT(ss.id) as cnt FROM study_sessions ss JOIN subjects sub ON ss.subject_id=sub.id GROUP BY ss.subject_id ORDER BY cnt DESC")->fetchAll();
$totalSubSess = array_sum(array_column($subjectDist,'cnt'));

// User growth per week (last 12 weeks)
$weeklyGrowth = [];
for ($i=11;$i>=0;$i--) {
    $start = date('Y-m-d', strtotime("-".($i+1)." weeks +1 day", strtotime('last monday')));
    $end   = date('Y-m-d', strtotime("-$i weeks", strtotime('last monday')));
    $q = $pdo->prepare("SELECT COUNT(*) FROM users WHERE created_at >= ? AND created_at < ?");
    $q->execute([$start,$end]);
    $weeklyGrowth[] = ['week'=>date('M j',strtotime($start)), 'count'=>(int)$q->fetchColumn()];
}

// Retention: % of users who studied within last 7 days out of those who registered 7+ days ago
$eligible = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE is_verified=1 AND created_at <= NOW() - INTERVAL 7 DAY")->fetchColumn();
$retained7 = $eligible > 0 ? (int)$pdo->query("SELECT COUNT(DISTINCT user_id) FROM study_sessions WHERE created_at >= NOW() - INTERVAL 7 DAY")->fetchColumn() : 0;
$retention7 = $eligible > 0 ? round($retained7/$eligible*100,1) : 0;

$retained30 = $eligible > 0 ? (int)$pdo->query("SELECT COUNT(DISTINCT user_id) FROM study_sessions WHERE created_at >= NOW() - INTERVAL 30 DAY")->fetchColumn() : 0;
$retention30 = $eligible > 0 ? round($retained30/$eligible*100,1) : 0;

$churn30 = $eligible > 0 ? round((1 - $retained30/$eligible)*100, 1) : 0;

// Top XP earners (achievements system)
$topXP = $pdo->query("SELECT u.name, u.email, COALESCE(SUM(a.xp_reward),0) as total_xp FROM users u LEFT JOIN user_achievements ua ON u.id=ua.user_id LEFT JOIN achievement_defs a ON ua.achievement_id=a.id WHERE u.is_verified=1 GROUP BY u.id ORDER BY total_xp DESC LIMIT 10")->fetchAll();

// Device/auth stats
$totalUsers  = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE is_verified=1")->fetchColumn();
try {
    $googleUsers = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE auth_provider='google' OR google_id IS NOT NULL")->fetchColumn();
    $fbUsers     = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE auth_provider='facebook' OR facebook_id IS NOT NULL")->fetchColumn();
} catch (PDOException $e) {
    // auth_provider/google_id/facebook_id columns not present on this DB yet
    $googleUsers = 0;
    $fbUsers     = 0;
}
$emailUsers  = max(0, $totalUsers - $googleUsers - $fbUsers);

renderAdminHeader('Analytics & Reports', 'analytics');
?>
<style>
.metric-row { display:grid; grid-template-columns:repeat(auto-fit,minmax(160px,1fr)); gap:16px; margin-bottom:20px; }
.metric-card { background:var(--surface); border-radius:12px; padding:20px 16px; text-align:center; border:1px solid var(--border); }
.metric-val { font-size:32px; font-weight:700; color:var(--accent); }
.metric-label { font-size:12px; color:var(--text-muted); margin-top:4px; }
.export-btn { float:right }
</style>

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px">
  <h2 style="margin:0;color:var(--text-primary)">Platform Analytics</h2>
  <a href="<?= SITE_URL ?>/admin/export-report.php" class="btn btn-secondary">⬇️ Export CSV Report</a>
</div>

<!-- Key Metrics -->
<div class="metric-row">
  <div class="metric-card"><div class="metric-val"><?= $avgSession ?>m</div><div class="metric-label">Avg Session Length</div></div>
  <div class="metric-card"><div class="metric-val"><?= $peakHour ? $peakHour['hr'].':00' : '—' ?></div><div class="metric-label">Peak Study Hour</div></div>
  <div class="metric-card"><div class="metric-val"><?= $retention7 ?>%</div><div class="metric-label">7-Day Retention</div></div>
  <div class="metric-card"><div class="metric-val"><?= $retention30 ?>%</div><div class="metric-label">30-Day Retention</div></div>
  <div class="metric-card" style="border-color:rgba(239,68,68,0.3)"><div class="metric-val" style="color:#ef4444"><?= $churn30 ?>%</div><div class="metric-label">30-Day Churn</div></div>
</div>

<!-- Study Hours Chart -->
<div class="card" style="margin-bottom:20px">
  <div class="card-header"><div class="card-title">⏱️ Platform Study Hours Per Day (Last 30 Days)</div></div>
  <div class="chart-container" style="height:240px"><canvas id="studyHoursChart"></canvas></div>
</div>

<!-- Weekly Growth + Subject Pie -->
<div class="grid-2" style="margin-bottom:20px">
  <div class="card">
    <div class="card-header"><div class="card-title">📈 User Growth (Weekly)</div></div>
    <div class="chart-container" style="height:220px"><canvas id="weeklyGrowthChart"></canvas></div>
  </div>
  <div class="card">
    <div class="card-header"><div class="card-title">📚 Subject Distribution</div></div>
    <div style="position:relative;height:180px;display:flex;justify-content:center">
      <canvas id="subjectPieChart"></canvas>
    </div>
    <div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:8px">
    <?php
    $pieColors = ['#a855f7','#06b6d4','#10b981','#f59e0b','#ef4444','#8b5cf6','#3b82f6','#ec4899'];
    foreach($subjectDist as $si=>$s):
      $pct2 = $totalSubSess > 0 ? round($s['cnt']/$totalSubSess*100) : 0;
    ?>
    <div style="display:flex;align-items:center;gap:4px;font-size:12px">
      <div style="width:10px;height:10px;border-radius:2px;background:<?= $pieColors[$si%8] ?>"></div>
      <span style="color:var(--text-muted)"><?= htmlspecialchars($s['name']) ?> (<?= $pct2 ?>%)</span>
    </div>
    <?php endforeach; ?>
    </div>
  </div>
</div>

<!-- Top XP Earners + Auth Distribution -->
<div class="grid-2" style="margin-bottom:20px">
  <div class="card">
    <div class="card-header"><div class="card-title">🏅 Top XP Earners</div></div>
    <div class="table-wrapper"><table>
      <thead><tr><th>#</th><th>Student</th><th>XP</th></tr></thead>
      <tbody>
      <?php foreach($topXP as $i=>$u): ?>
      <tr>
        <td style="font-weight:700;color:var(--accent)"><?= $i+1 ?></td>
        <td><div style="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:#f59e0b;font-weight:600"><?= number_format($u['total_xp']) ?></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table></div>
  </div>
  <div class="card">
    <div class="card-header"><div class="card-title">🔐 Auth Method Distribution</div></div>
    <div style="display:flex;flex-direction:column;gap:14px;padding:8px 0">
      <?php
      $authData = [['Email / Password',$emailUsers,'#a855f7'],['Google',$googleUsers,'#06b6d4'],['Facebook',$fbUsers,'#3b82f6']];
      $totalAuth = max(1, $totalUsers);
      foreach($authData as [$label,$count,$color]):
        $pctA = round($count/$totalAuth*100);
      ?>
      <div>
        <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:4px">
          <span style="color:var(--text-primary)"><?= $label ?></span>
          <span style="color:var(--text-muted)"><?= $count ?> (<?= $pctA ?>%)</span>
        </div>
        <div style="background:var(--border);border-radius:4px;height:8px">
          <div style="background:<?= $color ?>;border-radius:4px;height:8px;width:<?= $pctA ?>%"></div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<script>
new Chart(document.getElementById('studyHoursChart'), {
  type:'bar',
  data:{labels:<?= json_encode(array_column($studyHoursData,'date')) ?>,datasets:[{label:'Hours',data:<?= json_encode(array_column($studyHoursData,'hours')) ?>,backgroundColor:'rgba(168,85,247,0.6)',borderColor:'#a855f7',borderRadius:4}]},
  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}}}}
});
new Chart(document.getElementById('weeklyGrowthChart'), {
  type:'bar',
  data:{labels:<?= json_encode(array_column($weeklyGrowth,'week')) ?>,datasets:[{label:'New Users',data:<?= json_encode(array_column($weeklyGrowth,'count')) ?>,backgroundColor:'rgba(6,182,212,0.6)',borderColor:'#06b6d4',borderRadius:4}]},
  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}}}}
});
<?php if($subjectDist): ?>
new Chart(document.getElementById('subjectPieChart'), {
  type:'doughnut',
  data:{labels:<?= json_encode(array_column($subjectDist,'name')) ?>,datasets:[{data:<?= json_encode(array_column($subjectDist,'cnt')) ?>,backgroundColor:<?= json_encode(array_slice($pieColors,0,count($subjectDist))) ?>,borderWidth:0}]},
  options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}}}
});
<?php endif; ?>
</script>
<?php require_once 'includes/footer.php'; renderAdminFooter(); ?>
