<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];
$period = $_GET['period'] ?? 'month';

// Study data by day
$days = match($period) { 'week'=>7, 'year'=>365, default=>30 };
$studyData = [];
for ($i=$days-1; $i>=0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=? AND date=?");
    $q->execute([$uid,$d]);
    $studyData[] = ['date'=>$d,'label'=>$days<=7?date('D M j',strtotime($d)):date('M j',strtotime($d)),'minutes'=>(int)$q->fetchColumn()];
}

// Summary stats
$totalMins  = array_sum(array_column($studyData, 'minutes'));
$studyDays  = count(array_filter($studyData, fn($d) => $d['minutes'] > 0));
$avgMins    = $studyDays > 0 ? round($totalMins / $studyDays) : 0;
$maxDay     = $studyData ? max(array_column($studyData, 'minutes')) : 0;

// Marks trend
$marksQ = $pdo->prepare("SELECT m.*, s.name as sname, s.color FROM marks m JOIN subjects s ON m.subject_id=s.id WHERE m.user_id=? AND m.exam_date >= DATE_SUB(CURDATE(),INTERVAL ? DAY) ORDER BY m.exam_date ASC");
$marksQ->execute([$uid,$days]); $marksTrend = $marksQ->fetchAll();

// Subject distribution
$subDistQ = $pdo->prepare("SELECT s.name, s.color, COALESCE(SUM(ss.duration_minutes),0) as total FROM subjects s LEFT JOIN study_sessions ss ON s.id=ss.subject_id AND ss.date >= DATE_SUB(CURDATE(),INTERVAL ? DAY) WHERE s.user_id=? GROUP BY s.id HAVING total>0 ORDER BY total DESC");
$subDistQ->execute([$days,$uid]); $subDist = $subDistQ->fetchAll();

// Heatmap data (last 84 days)
$heatQ = $pdo->prepare("SELECT date, SUM(duration_minutes) as mins FROM study_sessions WHERE user_id=? AND date >= DATE_SUB(CURDATE(),INTERVAL 84 DAY) GROUP BY date");
$heatQ->execute([$uid]); $heatRaw = $heatQ->fetchAll();
$heatMap = [];
foreach ($heatRaw as $h) {
    $level = $h['mins'] >= 180 ? 4 : ($h['mins'] >= 120 ? 3 : ($h['mins'] >= 60 ? 2 : 1));
    $heatMap[$h['date']] = $level;
}

// Class Hours Analysis
$classAttQ = $pdo->prepare("SELECT COUNT(*) as total, SUM(attended) as attended, COALESCE(SUM(duration_minutes),0) as total_mins, COALESCE(SUM(CASE WHEN attended=1 THEN duration_minutes ELSE 0 END),0) as attended_mins FROM class_hours WHERE user_id=? AND class_date >= DATE_SUB(CURDATE(), INTERVAL ? DAY)");
$classAttQ->execute([$uid, $days]);
$classAtt = $classAttQ->fetch();
$classTotal    = (int)($classAtt['total'] ?? 0);
$classAttended = (int)($classAtt['attended'] ?? 0);
$classMissed   = $classTotal - $classAttended;
$classAttRate  = $classTotal > 0 ? round(($classAttended / $classTotal) * 100) : 0;
$classTotalMins = (int)($classAtt['total_mins'] ?? 0);
$classAttMins   = (int)($classAtt['attended_mins'] ?? 0);

$classSubQ = $pdo->prepare("SELECT s.name, s.color, COUNT(ch.id) as total_classes, SUM(ch.attended) as attended_classes, COALESCE(SUM(CASE WHEN ch.attended=1 THEN ch.duration_minutes ELSE 0 END),0) as attended_mins FROM subjects s LEFT JOIN class_hours ch ON s.id=ch.subject_id AND ch.user_id=? AND ch.class_date >= DATE_SUB(CURDATE(), INTERVAL ? DAY) WHERE s.user_id=? GROUP BY s.id HAVING total_classes > 0 ORDER BY total_classes DESC");
$classSubQ->execute([$uid, $days, $uid]);
$classBySub = $classSubQ->fetchAll();

$weeklyClassData = [];
for ($i=6; $i>=0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM class_hours WHERE user_id=? AND class_date=? AND attended=1");
    $q->execute([$uid,$d]);
    $weeklyClassData[] = ['label'=>date('D',strtotime($d)), 'minutes'=>(int)$q->fetchColumn()];
}

require_once 'includes/header.php';
renderHeader('Analysis', 'analysis');
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;700;800;900&display=swap');

/* ── Hero ───────────────────────────────────────────────── */
.an-hero {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}
.an-title {
  font-size: 22px;
  font-weight: 800;
  font-family: 'Outfit', sans-serif;
  background: var(--gradient);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  line-height: 1.2;
  display: flex;
  align-items: center;
  gap: 10px;
}
.an-title-icon { -webkit-text-fill-color: initial; }
.an-subtitle { font-size: 13px; color: var(--text-muted); margin-top: 3px; }
.period-selector {
  display: flex;
  gap: 4px;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 4px;
}

/* ── Summary stat cards ─────────────────────────────────── */
.an-stats {
  display: grid;
  grid-template-columns: repeat(4,1fr);
  gap: 14px;
  margin-bottom: 22px;
}
.an-stat {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 16px;
  padding: 18px 20px;
  position: relative;
  overflow: hidden;
  transition: all .22s;
}
.an-stat::before {
  content: '';
  position: absolute;
  top:0; left:0; right:0;
  height: 2px;
  border-radius: 2px 2px 0 0;
}
.an-stat:nth-child(1)::before { background: var(--gradient); }
.an-stat:nth-child(2)::before { background: linear-gradient(90deg,var(--accent-3),var(--accent)); }
.an-stat:nth-child(3)::before { background: linear-gradient(90deg,var(--success),var(--accent-3)); }
.an-stat:nth-child(4)::before { background: linear-gradient(90deg,var(--warning),var(--danger)); }
.an-stat:hover { transform: translateY(-2px); border-color: var(--border-light); }
.an-stat:nth-child(1):hover { box-shadow: 0 4px 24px rgba(99,102,241,.14); }
.an-stat:nth-child(2):hover { box-shadow: 0 4px 24px rgba(6,182,212,.12); }
.an-stat:nth-child(3):hover { box-shadow: 0 4px 24px rgba(16,185,129,.12); }
.an-stat:nth-child(4):hover { box-shadow: 0 4px 24px rgba(245,158,11,.12); }
.an-stat-icon { width:38px; height:38px; border-radius:11px; display:flex; align-items:center; justify-content:center; font-size:17px; margin-bottom:12px; }
.an-stat-val { font-size:28px; font-weight:900; font-family:'Outfit',sans-serif; color:var(--text-primary); line-height:1; letter-spacing:-.5px; }
.an-stat-unit { font-size:15px; font-weight:600; color:var(--text-muted); }
.an-stat-lbl { font-size:12px; color:var(--text-muted); margin-top:5px; font-weight:500; }
.an-stat-sub { font-size:11px; color:var(--text-muted); margin-top:2px; opacity:.7; }

/* ── Generic Card ───────────────────────────────────────── */
.an-card {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--radius-lg);
  padding: 22px;
  transition: border-color .2s;
}
.an-card:hover { border-color: var(--border-light); }
.an-card-hd {
  display:flex; align-items:center; justify-content:space-between;
  margin-bottom: 20px; gap:12px; flex-wrap:wrap;
}
.an-card-title {
  font-size:14px; font-weight:700; color:var(--text-primary);
  display:flex; align-items:center; gap:8px;
  font-family:'Outfit',sans-serif;
}
.an-card-badge {
  font-size:11px; font-weight:600;
  padding:3px 10px; border-radius:20px;
  background:rgba(99,102,241,.12); color:var(--accent);
  border:1px solid rgba(99,102,241,.2);
}

/* ── 2-col grid ─────────────────────────────────────────── */
.an-row-2   { display:grid; grid-template-columns:1fr 1fr; gap:18px; margin-bottom:20px; }
.an-row-3-2 { display:grid; grid-template-columns:1.5fr 1fr; gap:18px; margin-bottom:20px; }

/* ── Heatmap legend ─────────────────────────────────────── */
.hm-legend { display:flex; align-items:center; gap:6px; font-size:11px; color:var(--text-muted); font-weight:500; }
.hm-legend-cells { display:flex; gap:3px; }
.hm-cell { width:12px; height:12px; border-radius:3px; }

/* ── Sub dist bar ───────────────────────────────────────── */
.sb-row { margin-bottom:12px; }
.sb-row:last-child { margin-bottom:0; }
.sb-top { display:flex; align-items:center; justify-content:space-between; margin-bottom:6px; }
.sb-name { display:flex; align-items:center; gap:8px; font-size:13px; font-weight:600; color:var(--text-primary); }
.sb-pct  { font-size:12px; font-weight:700; font-family:'Outfit',sans-serif; }
.sb-track { height:6px; background:var(--bg-secondary); border-radius:99px; overflow:hidden; border:1px solid var(--border); }
.sb-fill  { height:100%; border-radius:99px; transition:width 1s cubic-bezier(.4,0,.2,1); }

/* ── Class mini stats ───────────────────────────────────── */
.cls-stats { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; margin-bottom:22px; }
.cls-stat { background:var(--bg-secondary); border:1px solid var(--border); border-radius:14px; padding:14px 16px; text-align:center; transition:all .2s; }
.cls-stat:hover { border-color:var(--border-light); }
.cls-num { font-size:26px; font-weight:900; font-family:'Outfit',sans-serif; line-height:1; margin-bottom:4px; }
.cls-lbl { font-size:10px; font-weight:700; color:var(--text-muted); text-transform:uppercase; letter-spacing:.8px; }
.cls-sub { font-size:11px; color:var(--text-muted); margin-top:3px; }

/* ── Attendance ring ────────────────────────────────────── */
.ring-wrap { position:relative; width:140px; height:140px; flex-shrink:0; }
.ring-center { position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; pointer-events:none; }
.ring-pct { font-size:28px; font-weight:900; font-family:'Outfit',sans-serif; color:var(--text-primary); line-height:1; }
.ring-lbl { font-size:10px; color:var(--text-muted); font-weight:600; text-transform:uppercase; letter-spacing:.8px; margin-top:3px; }

/* ── Score pills ────────────────────────────────────────── */
.sc-pill { display:inline-flex; align-items:center; padding:4px 10px; border-radius:20px; font-size:12px; font-weight:700; font-family:'Outfit',sans-serif; }
.sc-pill.g { background:rgba(16,185,129,.12); color:#34d399; border:1px solid rgba(16,185,129,.2); }
.sc-pill.y { background:rgba(245,158,11,.12);  color:#fbbf24; border:1px solid rgba(245,158,11,.2); }
.sc-pill.r { background:rgba(239,68,68,.12);   color:#f87171; border:1px solid rgba(239,68,68,.2); }

/* ── Section label ──────────────────────────────────────── */
.sec-lbl {
  font-size:11px; font-weight:700; text-transform:uppercase;
  letter-spacing:1px; color:var(--text-muted);
  margin-bottom:14px; padding-left:2px;
  display:flex; align-items:center; gap:8px;
}
.sec-lbl::after { content:''; flex:1; height:1px; background:var(--border); }

/* ── Responsive ─────────────────────────────────────────── */
@media(max-width:900px){
  .an-stats,.cls-stats { grid-template-columns:repeat(2,1fr); }
  .an-row-2,.an-row-3-2 { grid-template-columns:1fr; }
}
@media(max-width:540px){
  .an-stats { grid-template-columns:repeat(2,1fr); }
  .an-stat-val { font-size:22px; }
}
/* ── Animations ── */
@keyframes ch-rise { from{opacity:0;transform:translateY(18px)} to{opacity:1;transform:translateY(0)} }


</style>


<!-- Hero -->


<div class="an-hero">
    
  <div>
    <div class="an-title"><span class="an-title-icon">📈</span> Performance Analysis</div>
    <div class="an-subtitle">Study habits, marks & attendance insights</div>
  </div>
  <div class="period-selector">
    <a href="?period=week"  class="period-btn <?= $period==='week'  ?'active':'' ?>">Week</a>
    <a href="?period=month" class="period-btn <?= $period==='month' ?'active':'' ?>">Month</a>
    <a href="?period=year"  class="period-btn <?= $period==='year'  ?'active':'' ?>">Year</a>
  </div>
</div>

<!-- Summary Stats -->
<div class="an-stats">
  <div class="an-stat">
    <div class="an-stat-icon" style="background:rgba(99,102,241,.12)">⏱️</div>
    <div class="an-stat-val"><?= floor($totalMins/60) ?><span class="an-stat-unit">h <?= $totalMins%60 ?>m</span></div>
    <div class="an-stat-lbl">Total Study Time</div>
    <div class="an-stat-sub">Last <?= $days ?> days</div>
  </div>
  <div class="an-stat">
    <div class="an-stat-icon" style="background:rgba(6,182,212,.12)">📅</div>
    <div class="an-stat-val"><?= $studyDays ?></div>
    <div class="an-stat-lbl">Active Study Days</div>
    <div class="an-stat-sub"><?= $days>0?round($studyDays/$days*100):0 ?>% consistency</div>
  </div>
  <div class="an-stat">
    <div class="an-stat-icon" style="background:rgba(16,185,129,.12)">⚡</div>
    <div class="an-stat-val"><?= floor($avgMins/60) ?><span class="an-stat-unit">h <?= $avgMins%60 ?>m</span></div>
    <div class="an-stat-lbl">Daily Average</div>
    <div class="an-stat-sub">On active days</div>
  </div>
  <div class="an-stat">
    <div class="an-stat-icon" style="background:rgba(245,158,11,.12)">🏆</div>
    <div class="an-stat-val"><?= floor($maxDay/60) ?><span class="an-stat-unit">h <?= $maxDay%60 ?>m</span></div>
    <div class="an-stat-lbl">Best Day</div>
    <div class="an-stat-sub">Peak session</div>
  </div>
</div>

<!-- Study Hours Chart -->
<div class="an-card" style="margin-bottom:20px">
  <div class="an-card-hd">
    <div class="an-card-title">⏱️ Daily Study Hours</div>
    <span class="an-card-badge"><?= ucfirst($period) ?> view</span>
  </div>
  <div style="height:260px;position:relative"><canvas id="studyChart"></canvas></div>
</div>

<!-- Marks Trend + Subject Distribution -->
<div class="an-row-3-2">
  <div class="an-card">
    <div class="an-card-hd">
      <div class="an-card-title">📊 Marks Trend</div>
      <?php if(count($marksTrend)>0): ?>
        <span class="an-card-badge"><?= count($marksTrend) ?> exam<?= count($marksTrend)>1?'s':'' ?></span>
      <?php endif; ?>
    </div>
    <?php if(count($marksTrend)>0): ?>
      <div style="height:230px;position:relative"><canvas id="marksChart"></canvas></div>
    <?php else: ?>
      <div class="empty-state" style="padding:30px 20px">
        <div class="empty-icon">📊</div><p>No exam data for this period</p>
      </div>
    <?php endif; ?>
  </div>

  <div class="an-card">
    <div class="an-card-hd">
      <div class="an-card-title">🥧 Study Split</div>
    </div>
    <?php if(!empty($subDist)): ?>
      <div style="display:flex;flex-direction:column;align-items:center;gap:16px">
        <div style="width:150px;height:150px"><canvas id="pieChart"></canvas></div>
        <div style="width:100%">
          <?php foreach($subDist as $s):
            $pct=$subDist?round($s['total']/array_sum(array_column($subDist,'total'))*100):0; ?>
          <div class="sb-row">
            <div class="sb-top">
              <span class="sb-name">
                <span style="width:9px;height:9px;border-radius:50%;background:<?=htmlspecialchars($s['color'])?>;display:inline-block;flex-shrink:0"></span>
                <?=htmlspecialchars($s['name'])?>
              </span>
              <span class="sb-pct" style="color:<?=htmlspecialchars($s['color'])?>"><?=$pct?>%</span>
            </div>
            <div class="sb-track"><div class="sb-fill" style="width:<?=$pct?>%;background:<?=htmlspecialchars($s['color'])?>"></div></div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    <?php else: ?>
      <div class="empty-state" style="padding:30px 20px">
        <div class="empty-icon">🥧</div><p>No study sessions logged yet</p>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- Heatmap -->
<div class="an-card" style="margin-bottom:20px">
  <div class="an-card-hd">
    <div class="an-card-title">🗓️ Study Heatmap <span style="font-size:12px;color:var(--text-muted);font-weight:400;font-family:'Inter',sans-serif">Last 12 Weeks</span></div>
    <div class="hm-legend">
      Less
      <div class="hm-legend-cells">
        <div class="hm-cell" style="background:var(--bg-secondary);border:1px solid var(--border)"></div>
        <div class="hm-cell" style="background:rgba(99,102,241,.3)"></div>
        <div class="hm-cell" style="background:rgba(99,102,241,.55)"></div>
        <div class="hm-cell" style="background:rgba(99,102,241,.8)"></div>
        <div class="hm-cell" style="background:#6366f1"></div>
      </div>
      More
    </div>
  </div>
  <div class="heatmap-wrapper">
    <div class="heatmap">
      <?php
      $heatStart = strtotime('-83 days');
      $heatLabels = ['No study','< 1 hour','1–2 hours','2–3 hours','3 + hours'];
      for($i=0;$i<84;$i++){
          $d=date('Y-m-d',$heatStart+$i*86400);
          $level=$heatMap[$d]??0;
          echo "<div class='heatmap-cell' data-level='$level' title='$d: {$heatLabels[$level]}'></div>";
      }
      ?>
    </div>
  </div>
</div>

<!-- Class Hours -->
<?php if($classTotal>0): ?>
<div class="sec-lbl" style="margin-bottom:16px">🏫 Class Hours Analysis</div>
<div class="an-card" style="margin-bottom:20px">
  <div class="an-card-hd">
    <div class="an-card-title">🏫 Attendance Overview</div>
    <a href="<?=defined('SITE_URL')?SITE_URL:''?>/class-hours" class="btn btn-sm btn-secondary">View All</a>
  </div>

  <div class="cls-stats">
    <div class="cls-stat">
      <div class="cls-num" style="color:var(--text-primary)"><?=$classTotal?></div>
      <div class="cls-lbl">Total</div>
      <div class="cls-sub">Classes</div>
    </div>
    <div class="cls-stat" style="border-color:rgba(16,185,129,.2)">
      <div class="cls-num" style="color:#10b981"><?=$classAttended?></div>
      <div class="cls-lbl">Attended</div>
      <div class="cls-sub"><?=floor($classAttMins/60)?>h <?=$classAttMins%60?>m</div>
    </div>
    <div class="cls-stat" style="border-color:rgba(239,68,68,.2)">
      <div class="cls-num" style="color:#ef4444"><?=$classMissed?></div>
      <div class="cls-lbl">Missed</div>
      <div class="cls-sub"><?=floor(($classTotalMins-$classAttMins)/60)?>h <?=($classTotalMins-$classAttMins)%60?>m</div>
    </div>
    <div class="cls-stat" style="border-color:rgba(<?=$classAttRate>=75?'16,185,129':($classAttRate>=50?'245,158,11':'239,68,68')?>, .2)">
      <div class="cls-num" style="color:<?=$classAttRate>=75?'#10b981':($classAttRate>=50?'#f59e0b':'#ef4444')?>"><?=$classAttRate?>%</div>
      <div class="cls-lbl">Rate</div>
      <div class="cls-sub">Attendance</div>
    </div>
  </div>

  <div class="an-row-2" style="margin-bottom:0">
    <div>
      <div style="font-size:13px;font-weight:700;color:var(--text-secondary);margin-bottom:12px;font-family:'Outfit',sans-serif">📊 Weekly Class Hours</div>
      <div style="height:190px;position:relative"><canvas id="classWeekChart"></canvas></div>
    </div>
    <div>
      <div style="font-size:13px;font-weight:700;color:var(--text-secondary);margin-bottom:12px;font-family:'Outfit',sans-serif">🎯 Attendance Split</div>
      <div style="display:flex;align-items:center;gap:20px;flex-wrap:wrap">
        <div class="ring-wrap">
          <canvas id="classAttChart" width="140" height="140"></canvas>
          <div class="ring-center">
            <div class="ring-pct"><?=$classAttRate?>%</div>
            <div class="ring-lbl">Attendance</div>
          </div>
        </div>
        <div style="flex:1;min-width:120px;display:flex;flex-direction:column;gap:10px">
          <div style="display:flex;align-items:center;justify-content:space-between;background:rgba(16,185,129,.08);border:1px solid rgba(16,185,129,.2);border-radius:12px;padding:10px 14px">
            <div style="display:flex;align-items:center;gap:8px">
              <span style="width:10px;height:10px;border-radius:3px;background:#10b981;display:inline-block"></span>
              <span style="font-size:13px;color:var(--text-secondary);font-weight:500">Attended</span>
            </div>
            <span style="font-size:16px;font-weight:900;color:#10b981;font-family:'Outfit',sans-serif"><?=$classAttended?></span>
          </div>
          <div style="display:flex;align-items:center;justify-content:space-between;background:rgba(239,68,68,.08);border:1px solid rgba(239,68,68,.2);border-radius:12px;padding:10px 14px">
            <div style="display:flex;align-items:center;gap:8px">
              <span style="width:10px;height:10px;border-radius:3px;background:#ef4444;display:inline-block"></span>
              <span style="font-size:13px;color:var(--text-secondary);font-weight:500">Missed</span>
            </div>
            <span style="font-size:16px;font-weight:900;color:#ef4444;font-family:'Outfit',sans-serif"><?=$classMissed?></span>
          </div>
          <div style="display:flex;align-items:center;justify-content:space-between;background:var(--bg-secondary);border:1px solid var(--border);border-radius:12px;padding:10px 14px">
            <div style="display:flex;align-items:center;gap:8px">
              <span style="width:10px;height:10px;border-radius:3px;background:#6366f1;display:inline-block"></span>
              <span style="font-size:13px;color:var(--text-secondary);font-weight:500">Total</span>
            </div>
            <span style="font-size:16px;font-weight:900;color:var(--text-primary);font-family:'Outfit',sans-serif"><?=$classTotal?></span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <?php if(!empty($classBySub)): ?>
  <div style="margin-top:22px;border-top:1px solid var(--border);padding-top:20px">
    <div style="font-size:13px;font-weight:700;color:var(--text-secondary);margin-bottom:14px;font-family:'Outfit',sans-serif">Per Subject Attendance</div>
    <?php foreach($classBySub as $cs):
      $csPct=$cs['total_classes']>0?round(($cs['attended_classes']/$cs['total_classes'])*100):0;
      $csColor=$csPct>=75?'#10b981':($csPct>=50?'#f59e0b':'#ef4444');
    ?>
    <div class="sb-row">
      <div class="sb-top">
        <span class="sb-name">
          <span style="width:9px;height:9px;border-radius:50%;background:<?=htmlspecialchars($cs['color'])?>;display:inline-block;flex-shrink:0"></span>
          <?=htmlspecialchars($cs['name'])?>
        </span>
        <span style="font-size:12px;font-weight:700;color:<?=$csColor?>;font-family:'Outfit',sans-serif">
          <?=$csPct?>% <span style="color:var(--text-muted);font-weight:400"><?=$cs['attended_classes']?>/<?=$cs['total_classes']?></span>
        </span>
      </div>
      <div class="sb-track"><div class="sb-fill" style="width:<?=$csPct?>%;background:<?=$csColor?>"></div></div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>
</div>
<?php endif; ?>

<!-- Per Subject Table -->
<div class="sec-lbl" style="margin-bottom:16px">📖 Subject Performance</div>
<div class="an-card">
  <div class="an-card-hd">
    <div class="an-card-title">📖 Per Subject Performance</div>
  </div>
  <?php
  $subPerfQ = $pdo->prepare("SELECT s.*, COALESCE(SUM(ss.duration_minutes),0) as total_mins, COUNT(DISTINCT ss.date) as study_days, COUNT(m.id) as exam_count, COALESCE(AVG((m.marks_obtained/m.total_marks)*100),0) as avg_score, COALESCE(MAX((m.marks_obtained/m.total_marks)*100),0) as best_score FROM subjects s LEFT JOIN study_sessions ss ON s.id=ss.subject_id LEFT JOIN marks m ON s.id=m.subject_id WHERE s.user_id=? GROUP BY s.id ORDER BY avg_score DESC");
  $subPerfQ->execute([$uid]); $subPerf=$subPerfQ->fetchAll();
  ?>
  <?php if($subPerf): ?>
  <div class="table-wrapper">
    <table>
      <thead><tr>
        <th>Subject</th><th>Study Time</th><th>Days</th><th>Exams</th>
        <th>Avg Score</th><th>Best</th><th style="min-width:110px">Progress</th>
      </tr></thead>
      <tbody>
      <?php foreach($subPerf as $s): $pct=round($s['avg_score'],1); ?>
      <tr>
        <td><span class="subject-dot" style="background:<?=htmlspecialchars($s['color'])?>"></span><strong style="color:var(--text-primary)"><?=htmlspecialchars($s['name'])?></strong></td>
        <td style="font-family:'Outfit',sans-serif;font-weight:600;color:var(--accent)"><?=floor($s['total_mins']/60)?>h <?=$s['total_mins']%60?>m</td>
        <td><?=$s['study_days']?></td>
        <td><?=$s['exam_count']?></td>
        <td><span class="sc-pill <?=$pct>=75?'g':($pct>=55?'y':'r')?>"><?=$pct?>%</span></td>
        <td><span class="sc-pill <?=round($s['best_score'])>=75?'g':(round($s['best_score'])>=55?'y':'r')?>"><?=round($s['best_score'],1)?>%</span></td>
        <td><div class="sb-track" style="height:5px"><div class="sb-fill" style="width:<?=min($pct,100)?>%;background:<?=$pct>=75?'#10b981':($pct>=55?'#f59e0b':'#ef4444')?>"></div></div></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php else: ?>
  <div class="empty-state">
    <div class="empty-icon">📊</div>
    <p>Add subjects and study sessions to see your analysis</p>
  </div>
  <?php endif; ?>
</div>

<script>
const isDark   = document.documentElement.getAttribute('data-theme') !== 'light';
const gridClr  = isDark ? 'rgba(42,42,61,0.6)'  : 'rgba(203,213,225,0.6)';
const tickClr  = isDark ? '#64748b' : '#94a3b8';
const tipBg    = isDark ? 'rgba(16,16,24,0.96)' : 'rgba(255,255,255,0.96)';
const tipTxt   = isDark ? '#f1f5f9' : '#0f172a';
const tipBdr   = isDark ? '#2a2a3d' : '#e2e8f0';

const tipBase = { backgroundColor:tipBg, titleColor:tipTxt, bodyColor:tickClr, borderColor:tipBdr, borderWidth:1, cornerRadius:10, padding:10 };

/* Study Hours */
new Chart(document.getElementById('studyChart'),{
  type:'line',
  data:{
    labels:<?=json_encode(array_column($studyData,'label'))?>,
    datasets:[{
      label:'Minutes',
      data:<?=json_encode(array_column($studyData,'minutes'))?>,
      borderColor:'#6366f1',
      backgroundColor:isDark?'rgba(99,102,241,0.08)':'rgba(99,102,241,0.05)',
      tension:0.4, fill:true,
      pointBackgroundColor:'#6366f1',
      pointBorderColor:isDark?'#16161f':'#fff',
      pointBorderWidth:2, pointRadius:4, pointHoverRadius:6
    }]
  },
  options:{
    responsive:true, maintainAspectRatio:false,
    plugins:{legend:{display:false}, tooltip:{...tipBase, callbacks:{label:ctx=>'  '+Math.floor(ctx.raw/60)+'h '+(ctx.raw%60)+'m'}}},
    scales:{
      x:{grid:{display:false},ticks:{color:tickClr,font:{size:11}},border:{display:false}},
      y:{grid:{color:gridClr},ticks:{color:tickClr,font:{size:11},callback:v=>Math.floor(v/60)+'h'},border:{display:false}}
    }
  }
});

/* Marks Scatter */
const marksData=<?=json_encode(array_map(fn($m)=>['label'=>date('M j',strtotime($m['exam_date'])),'score'=>round(($m['marks_obtained']/$m['total_marks'])*100,1),'subject'=>$m['sname'],'color'=>$m['color']],$marksTrend))?>;
const marksEl=document.getElementById('marksChart');
if(marksEl&&marksData.length>0){
  new Chart(marksEl,{
    type:'scatter',
    data:{datasets:[{
      label:'Score %',
      data:marksData.map(m=>({x:m.label,y:m.score})),
      backgroundColor:marksData.map(m=>m.color||'#6366f1'),
      pointRadius:8, pointHoverRadius:11,
      pointBorderColor:isDark?'#16161f':'#fff', pointBorderWidth:2
    }]},
    options:{
      responsive:true, maintainAspectRatio:false,
      plugins:{legend:{display:false}, tooltip:{...tipBase, callbacks:{label:ctx=>' '+marksData[ctx.dataIndex]?.subject+': '+ctx.parsed.y+'%'}}},
      scales:{
        x:{type:'category',grid:{display:false},ticks:{color:tickClr,font:{size:11}},border:{display:false}},
        y:{min:0,max:100,grid:{color:gridClr},ticks:{color:tickClr,font:{size:11},callback:v=>v+'%'},border:{display:false}}
      }
    }
  });
}

/* Doughnut */
const subMins=<?=json_encode(array_column($subDist,'total'))?>;
if(subMins.length>0){
  new Chart(document.getElementById('pieChart'),{
    type:'doughnut',
    data:{
      labels:<?=json_encode(array_column($subDist,'name'))?>,
      datasets:[{data:subMins,backgroundColor:<?=json_encode(array_column($subDist,'color'))?>,borderWidth:3,borderColor:isDark?'#16161f':'#fff',hoverOffset:6}]
    },
    options:{
      responsive:true, maintainAspectRatio:false, cutout:'68%',
      plugins:{legend:{display:false}, tooltip:{...tipBase, callbacks:{label:ctx=>' '+ctx.label+': '+Math.floor(ctx.raw/60)+'h '+ctx.raw%60+'m'}}}
    }
  });
}

/* Class Charts */
<?php if($classTotal>0): ?>
const cwEl=document.getElementById('classWeekChart');
if(cwEl){
  new Chart(cwEl,{
    type:'bar',
    data:{
      labels:<?=json_encode(array_column($weeklyClassData,'label'))?>,
      datasets:[{label:'Class Hours',data:<?=json_encode(array_map(fn($d)=>$d['minutes'],$weeklyClassData))?>,backgroundColor:'rgba(16,185,129,.55)',hoverBackgroundColor:'#34d399',borderRadius:8,borderSkipped:false,borderWidth:0}]
    },
    options:{
      responsive:true, maintainAspectRatio:false,
      plugins:{legend:{display:false}, tooltip:{...tipBase, callbacks:{label:ctx=>'  '+Math.floor(ctx.raw/60)+'h '+(ctx.raw%60)+'m'}}},
      scales:{
        y:{beginAtZero:true,grid:{color:gridClr},ticks:{color:tickClr,callback:v=>Math.floor(v/60)+'h'},border:{display:false}},
        x:{grid:{display:false},ticks:{color:tickClr},border:{display:false}}
      },
      animation:{duration:700,easing:'easeInOutCubic'}
    }
  });
}
const caEl=document.getElementById('classAttChart');
if(caEl){
  new Chart(caEl,{
    type:'doughnut',
    data:{labels:['Attended','Missed'],datasets:[{data:[<?=$classAttended?>,<?=max(1,$classMissed)?>],backgroundColor:['rgba(16,185,129,.85)','rgba(239,68,68,.65)'],borderColor:'transparent',borderWidth:0,hoverOffset:5}]},
    options:{responsive:false,maintainAspectRatio:false,cutout:'72%',plugins:{legend:{display:false},tooltip:{...tipBase,callbacks:{label:ctx=>' '+ctx.label+': '+ctx.raw}}}}
  });
}
<?php endif; ?>
</script>

<?php require_once 'includes/footer.php'; renderFooter(); ?>