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

$subjectsQ = $pdo->prepare("SELECT s.*, 
  COALESCE(SUM(ss.duration_minutes),0) as total_mins,
  COUNT(DISTINCT 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,
  COALESCE(MIN((m.marks_obtained/m.total_marks)*100),0) as worst_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");
$subjectsQ->execute([$uid]); $subjects = $subjectsQ->fetchAll();

// Monthly progress
$monthlyQ = $pdo->prepare("SELECT DATE_FORMAT(date,'%Y-%m') as month, SUM(duration_minutes) as mins FROM study_sessions WHERE user_id=? AND date >= DATE_SUB(CURDATE(),INTERVAL 6 MONTH) GROUP BY month ORDER BY month");
$monthlyQ->execute([$uid]); $monthly = $monthlyQ->fetchAll();

// Goal setting
$user = $pdo->prepare("SELECT study_goal_minutes FROM users WHERE id=?")->execute([$uid]);
$userQ = $pdo->prepare("SELECT study_goal_minutes FROM users WHERE id=?"); $userQ->execute([$uid]);
$goal = (int)$userQ->fetchColumn();

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['update_goal'])) {
    $newGoal = (int)($_POST['goal_minutes']??120);
    $pdo->prepare("UPDATE users SET study_goal_minutes=? WHERE id=?")->execute([$newGoal,$uid]);
    header('Location: progress.php'); exit;
}

// Today progress
$todayMins = (int)$pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=? AND date=CURDATE()")->execute([$uid]) ?: 0;
$tdQ = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=? AND date=CURDATE()");
$tdQ->execute([$uid]); $todayMins = (int)$tdQ->fetchColumn();

require_once 'includes/header.php';
renderHeader('Progress', 'progress');
?>

<!-- Daily Goal -->
<div class="card" style="margin-bottom:20px">
  <div class="card-header"><div class="card-title">🎯 Daily Study Goal</div>
    <button class="btn btn-secondary btn-sm" onclick="openModal('goalModal')">Edit Goal</button>
  </div>
  <?php $goalPct = $goal > 0 ? min(round(($todayMins/$goal)*100),100) : 0; ?>
  <div style="display:flex;align-items:center;gap:20px;flex-wrap:wrap">
    <div style="position:relative;width:120px;height:120px;flex-shrink:0">
      <canvas id="goalChart" width="120" height="120"></canvas>
      <div style="position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center">
        <div style="font-size:22px;font-weight:800;color:var(--text-primary)"><?= $goalPct ?>%</div>
        <div style="font-size:11px;color:var(--text-muted)">Today</div>
      </div>
    </div>
    <div style="flex:1">
      <div style="font-size:15px;font-weight:600;color:var(--text-primary);margin-bottom:8px">
        <?= floor($todayMins/60) ?>h <?= $todayMins%60 ?>m / <?= floor($goal/60) ?>h <?= $goal%60 ?>m
      </div>
      <div class="progress-bar" style="height:12px;margin-bottom:12px">
        <div class="progress-fill <?= $goalPct>=100?'green':($goalPct>=60?'yellow':'') ?>" style="width:<?= $goalPct ?>%"></div>
      </div>
      <div style="font-size:13px;color:var(--text-muted)">
        <?php if ($goalPct >= 100): ?>🎉 Goal achieved today! Keep it up!
        <?php else: $rem = $goal - $todayMins; ?>⏳ <?= floor($rem/60) ?>h <?= $rem%60 ?>m more to reach your goal
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- Monthly Study Chart -->
<div class="card" style="margin-bottom:20px">
  <div class="card-header"><div class="card-title">📅 Monthly Study Hours (Last 6 Months)</div></div>
  <div class="chart-container" style="height:240px"><canvas id="monthlyChart"></canvas></div>
</div>

<!-- Subject Progress Cards -->
<div class="card-header" style="padding:0;margin-bottom:16px"><div class="card-title">📊 Subject Progress Tracker</div></div>
<?php if ($subjects): ?>
<div style="display:flex;flex-direction:column;gap:16px">
<?php foreach ($subjects as $s): $avg = round($s['avg_score'],1); $target = $s['target_marks']; ?>
<div class="card" style="border-left:4px solid <?= htmlspecialchars($s['color']) ?>">
  <div style="display:flex;flex-wrap:wrap;gap:20px">
    <div style="flex:1;min-width:200px">
      <div style="font-size:17px;font-weight:700;color:var(--text-primary);margin-bottom:4px"><?= htmlspecialchars($s['name']) ?></div>
      <div style="display:flex;gap:8px;align-items:center;margin-bottom:12px">
        <?php if ($avg > 0): ?>
        <span class="badge badge-<?= $avg>=$target?'green':($avg>=55?'yellow':'red') ?>"><?= $avg ?>% avg</span>
        <?php endif; ?>
        <span style="font-size:12px;color:var(--text-muted)">Target: <?= $target ?>%</span>
      </div>
      <div style="margin-bottom:6px;display:flex;justify-content:space-between;font-size:12px;color:var(--text-muted)">
        <span>Progress to Target</span><span><?= $avg ?>% / <?= $target ?>%</span>
      </div>
      <div class="progress-bar">
        <div class="progress-fill <?= $avg>=$target?'green':($avg>=55?'yellow':'red') ?>" style="width:<?= $target>0?min(round(($avg/$target)*100),100):0 ?>%;background:<?= htmlspecialchars($s['color']) ?>"></div>
      </div>
    </div>
    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;min-width:240px">
      <div style="text-align:center;background:var(--bg-secondary);border-radius:10px;padding:12px">
        <div style="font-size:18px;font-weight:700;color:var(--text-primary)"><?= floor($s['total_mins']/60) ?>h</div>
        <div style="font-size:11px;color:var(--text-muted)">Total Study</div>
      </div>
      <div style="text-align:center;background:var(--bg-secondary);border-radius:10px;padding:12px">
        <div style="font-size:18px;font-weight:700;color:var(--text-primary)"><?= $s['exam_count'] ?></div>
        <div style="font-size:11px;color:var(--text-muted)">Exams</div>
      </div>
      <div style="text-align:center;background:var(--bg-secondary);border-radius:10px;padding:12px">
        <div style="font-size:18px;font-weight:700;color:var(--success)"><?= round($s['best_score'],1) ?>%</div>
        <div style="font-size:11px;color:var(--text-muted)">Best</div>
      </div>
    </div>
  </div>
</div>
<?php endforeach; ?>
</div>
<?php else: ?><div class="card"><div class="empty-state"><div class="empty-icon">🎯</div><h3>Add subjects to track progress</h3></div></div><?php endif; ?>

<!-- Goal Modal -->
<div class="modal-overlay" id="goalModal">
<div class="modal">
  <div class="modal-header"><div class="modal-title">🎯 Set Daily Goal</div><button class="modal-close" onclick="closeModal('goalModal')">✕</button></div>
  <form method="POST">
    <div class="form-group"><label class="form-label">Daily Study Goal (minutes)</label>
      <input type="number" name="goal_minutes" class="form-control" value="<?= $goal ?>" min="15" max="720" step="15" required>
      <small style="color:var(--text-muted);font-size:12px;margin-top:4px;display:block">Recommended: 120-240 minutes for A/L students</small>
    </div>
    <input type="hidden" name="update_goal" value="1">
    <button type="submit" class="btn btn-primary btn-full">Save Goal</button>
  </form>
</div></div>

<script>
// Goal circle chart
new Chart(document.getElementById('goalChart'), {
  type: 'doughnut',
  data: { datasets: [{ data: [<?= $goalPct ?>, <?= 100-$goalPct ?>], backgroundColor: ['#6366f1','rgba(42,42,61,0.5)'], borderWidth:0, cutout:'78%' }] },
  options: { responsive:false, plugins:{legend:{display:false},tooltip:{enabled:false}} }
});

// Monthly chart
const months = <?= json_encode(array_column($monthly,'month')) ?>;
const monthMins = <?= json_encode(array_map(fn($m)=>(int)$m['mins'],$monthly)) ?>;
new Chart(document.getElementById('monthlyChart'), {
  type: 'bar',
  data: { labels: months, datasets: [{ label:'Hours',
    data: monthMins.map(m=>Math.round(m/60*10)/10),
    backgroundColor: 'rgba(99,102,241,0.6)', borderColor:'#6366f1', borderWidth:2, borderRadius:8 }] },
  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',callback:v=>v+'h'},border:{display:false}}} }
});
</script>
<?php require_once 'includes/footer.php'; renderFooter(); ?>
