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

$year = (int)($_GET['year'] ?? date('Y'));
$year = max(2020, min(date('Y') + 1, $year));

// Get all study sessions for the year
$sessionsQ = $pdo->prepare("
    SELECT date as study_date,
           SUM(duration_minutes) as total_minutes,
           COUNT(*) as session_count
    FROM study_sessions
    WHERE user_id = ?
      AND YEAR(date) = ?
      AND duration_minutes > 0
    GROUP BY date
    ORDER BY date
");
$sessionsQ->execute([$uid, $year]);
$dayData = [];
foreach ($sessionsQ->fetchAll() as $row) {
    $dayData[$row['study_date']] = [
        'minutes'  => (int)$row['total_minutes'],
        'sessions' => (int)$row['session_count'],
    ];
}

// Stats for the year
$totalMinutes = array_sum(array_column($dayData, 'minutes'));
$totalDays = count($dayData);
$maxMinutes = $totalDays > 0 ? max(array_column($dayData, 'minutes')) : 0;
$avgMinutes = $totalDays > 0 ? round($totalMinutes / $totalDays) : 0;

// Current streak - calculated from study_sessions date column
$streakDates = array_keys($dayData);

// Monthly breakdown
$monthlyQ = $pdo->prepare("
    SELECT MONTH(date) as m, SUM(duration_minutes) as total
    FROM study_sessions WHERE user_id=? AND YEAR(date)=? AND duration_minutes>0
    GROUP BY MONTH(date)
");
$monthlyQ->execute([$uid, $year]);
$monthly = [];
foreach ($monthlyQ->fetchAll() as $row) {
    $monthly[(int)$row['m']] = (int)$row['total'];
}

// Best month
$bestMonth = count($monthly) > 0 ? array_search(max($monthly), $monthly) : null;
$months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

require_once 'includes/header.php';
renderHeader('Study Heatmap', 'heatmap');
?>

<style>
.heatmap-page-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}
.hm-stat { 
    background: var(--bg-card); border: 1px solid var(--border);
    border-radius: 14px; padding: 18px 20px;
    display: flex; align-items: center; gap: 14px;
}
.hm-stat-icon {
    width: 44px; height: 44px; border-radius: 12px;
    display: flex; align-items: center; justify-content: center;
    font-size: 20px; flex-shrink: 0;
}
.heatmap-container {
    background: var(--bg-card); border: 1px solid var(--border);
    border-radius: 16px; padding: 24px;
    overflow-x: auto;
}
.hm-grid {
    display: grid;
    grid-template-rows: repeat(7, 14px);
    grid-auto-flow: column;
    gap: 3px;
    width: max-content;
}
.hm-cell {
    width: 14px; height: 14px; border-radius: 3px;
    cursor: pointer; position: relative;
    transition: transform 0.1s;
}
.hm-cell:hover { transform: scale(1.5); z-index: 10; }
.hm-cell[data-level="0"] { background: var(--bg-secondary); border: 1px solid var(--border); }
.hm-cell[data-level="1"] { background: rgba(99,102,241,0.25); }
.hm-cell[data-level="2"] { background: rgba(99,102,241,0.50); }
.hm-cell[data-level="3"] { background: rgba(99,102,241,0.75); }
.hm-cell[data-level="4"] { background: #6366f1; }
.hm-cell[data-level="5"] { background: #4f46e5; box-shadow: 0 0 8px rgba(99,102,241,0.5); }
.hm-month-labels {
    display: flex; gap: 3px; margin-bottom: 6px;
    font-size: 10px; color: var(--text-muted);
    width: max-content;
}
.hm-day-labels {
    display: grid; grid-template-rows: repeat(7,14px); gap:3px;
    font-size: 10px; color: var(--text-muted);
    margin-right: 6px; flex-shrink: 0;
    align-items: center;
}
.hm-tooltip {
    position: fixed; z-index: 9999;
    background: var(--bg-card); border: 1px solid var(--border);
    border-radius: 10px; padding: 8px 12px;
    font-size: 12px; color: var(--text-primary);
    box-shadow: 0 4px 20px rgba(0,0,0,0.3);
    pointer-events: none; display: none;
    white-space: nowrap;
}
.month-bar-wrap { display: flex; gap: 4px; align-items: flex-end; height: 80px; margin-top: 8px; }
.month-bar { flex: 1; border-radius: 4px 4px 0 0; background: var(--gradient); transition: all 0.3s; cursor: pointer; position: relative; min-height: 4px; }
.month-bar:hover { filter: brightness(1.2); }

/* ── Back ── */
.bm-back {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  color: var(--text-muted);
  font-size: 13px;
  font-weight: 600;
  text-decoration: none;
  margin-bottom: 26px;
  transition: color .18s;
}
.bm-back:hover { color: var(--text-primary); }
</style>
  <!-- Back -->
  <a href="javascript:history.back()" class="bm-back">
    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
      <path d="M19 12H5M12 5l-7 7 7 7"/>
    </svg>
    Back
  </a>

<!-- Stats Row -->
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px;margin-bottom:20px">
    <div class="hm-stat">
        <div class="hm-stat-icon" style="background:rgba(99,102,241,0.12)">📅</div>
        <div>
            <div style="font-size:22px;font-weight:800;color:var(--text-primary)"><?= $totalDays ?></div>
            <div style="font-size:12px;color:var(--text-muted)">Study Days in <?= $year ?></div>
        </div>
    </div>
    <div class="hm-stat">
        <div class="hm-stat-icon" style="background:rgba(16,185,129,0.12)">⏱️</div>
        <div>
            <div style="font-size:22px;font-weight:800;color:var(--text-primary)">
                <?= $totalMinutes >= 60 ? floor($totalMinutes/60).'h '.($totalMinutes%60).'m' : $totalMinutes.'m' ?>
            </div>
            <div style="font-size:12px;color:var(--text-muted)">Total Study Time</div>
        </div>
    </div>
    <div class="hm-stat">
        <div class="hm-stat-icon" style="background:rgba(245,158,11,0.12)">⚡</div>
        <div>
            <div style="font-size:22px;font-weight:800;color:var(--text-primary)">
                <?= $avgMinutes >= 60 ? floor($avgMinutes/60).'h '.($avgMinutes%60).'m' : $avgMinutes.'m' ?>
            </div>
            <div style="font-size:12px;color:var(--text-muted)">Daily Average</div>
        </div>
    </div>
    <div class="hm-stat">
        <div class="hm-stat-icon" style="background:rgba(168,85,247,0.12)">🏆</div>
        <div>
            <div style="font-size:22px;font-weight:800;color:var(--text-primary)">
                <?= $maxMinutes >= 60 ? floor($maxMinutes/60).'h '.($maxMinutes%60).'m' : $maxMinutes.'m' ?>
            </div>
            <div style="font-size:12px;color:var(--text-muted)">Best Single Day</div>
        </div>
    </div>
</div>

<!-- Year Nav -->
<div class="heatmap-container">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;flex-wrap:wrap;gap:10px">
        <div style="font-size:16px;font-weight:700;color:var(--text-primary)">
            📅 Study Activity — <?= $year ?>
        </div>
        <div style="display:flex;align-items:center;gap:8px">
            <a href="?year=<?= $year-1 ?>" style="display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:8px;background:var(--bg-secondary);border:1px solid var(--border);color:var(--text-primary);text-decoration:none;font-weight:700">‹</a>
            <span style="font-size:15px;font-weight:700;color:var(--text-primary);min-width:50px;text-align:center"><?= $year ?></span>
            <?php if ($year < date('Y')): ?>
            <a href="?year=<?= $year+1 ?>" style="display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:8px;background:var(--bg-secondary);border:1px solid var(--border);color:var(--text-primary);text-decoration:none;font-weight:700">›</a>
            <?php else: ?>
            <div style="width:32px;height:32px;border-radius:8px;background:var(--bg-secondary);border:1px solid var(--border);opacity:0.3;display:flex;align-items:center;justify-content:center;color:var(--text-muted)">›</div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Heatmap -->
    <div style="display:flex;overflow-x:auto;padding-bottom:8px">
        <div class="hm-day-labels">
            <div></div><div>Mon</div><div></div><div>Wed</div><div></div><div>Fri</div><div></div>
        </div>
        <div>
            <div class="hm-month-labels" id="monthLabels"></div>
            <div class="hm-grid" id="heatmapGrid"></div>
        </div>
    </div>

    <!-- Legend -->
    <div style="display:flex;align-items:center;gap:6px;margin-top:14px;font-size:11px;color:var(--text-muted)">
        <span>Less</span>
        <?php foreach(range(0,5) as $l): ?>
        <div style="width:14px;height:14px;border-radius:3px;<?= $l==0?'background:var(--bg-secondary);border:1px solid var(--border)':'background:rgba(99,102,241,'.($l*0.2).')' ?>"></div>
        <?php endforeach; ?>
        <span>More</span>
    </div>
</div>
<br>
<!-- Monthly Breakdown -->
<div class="card">
    <div class="card-header">
        <div class="card-title">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>
            Monthly Breakdown
        </div>
        <?php if ($bestMonth): ?>
        <div style="font-size:12px;color:var(--text-muted)">Best: <span style="color:var(--accent);font-weight:600"><?= $months[$bestMonth-1] ?></span></div>
        <?php endif; ?>
    </div>
    <?php 
    $maxMonthly = count($monthly) > 0 ? max($monthly) : 1;
    ?>
    <div style="display:grid;grid-template-columns:repeat(12,1fr);gap:6px;align-items:flex-end">
        <?php for ($m = 1; $m <= 12; $m++): 
            $mins = $monthly[$m] ?? 0;
            $heightPct = $maxMonthly > 0 ? ($mins / $maxMonthly * 100) : 0;
            $hrs = $mins >= 60 ? floor($mins/60).'h '.($mins%60).'m' : $mins.'m';
        ?>
        <div style="display:flex;flex-direction:column;align-items:center;gap:4px">
            <?php if ($mins > 0): ?>
            <div style="font-size:9px;color:var(--accent);font-weight:700"><?= $hrs ?></div>
            <?php else: ?>
            <div style="font-size:9px;color:transparent">-</div>
            <?php endif; ?>
            <div style="width:100%;border-radius:4px 4px 0 0;height:<?= max(4, $heightPct * 0.8) ?>px;background:<?= $m==$bestMonth?'var(--gradient)':'rgba(99,102,241,0.3)' ?>;min-height:4px;transition:all .3s"></div>
            <div style="font-size:10px;color:var(--text-muted)"><?= $months[$m-1] ?></div>
        </div>
        <?php endfor; ?>
    </div>
</div>

<div class="hm-tooltip" id="hmTooltip"></div>

<script>
const dayData = <?= json_encode($dayData) ?>;
const year = <?= $year ?>;

// Build full year grid
function buildHeatmap() {
    const grid = document.getElementById('heatmapGrid');
    const monthLabels = document.getElementById('monthLabels');
    grid.innerHTML = '';
    monthLabels.innerHTML = '';

    const startDate = new Date(year, 0, 1);
    const endDate = new Date(year, 11, 31);
    
    // Find first Monday on or before Jan 1
    const startDow = startDate.getDay(); // 0=Sun
    const offset = startDow === 0 ? 6 : startDow - 1;
    const gridStart = new Date(startDate);
    gridStart.setDate(gridStart.getDate() - offset);

    const cells = [];
    let d = new Date(gridStart);
    let weekCol = 0;
    let monthLabelPositions = {};

    while (d <= endDate || d.getDay() !== 1) {
        if (d > endDate && d.getDay() === 1) break;

        const dateStr = d.toISOString().split('T')[0];
        const isCurrentYear = d.getFullYear() === year;
        const data = dayData[dateStr];
        const mins = data ? data.minutes : 0;
        const sessions = data ? data.sessions : 0;
        
        let level = 0;
        if (isCurrentYear && mins > 0) {
            if (mins >= 240) level = 5;
            else if (mins >= 180) level = 4;
            else if (mins >= 120) level = 3;
            else if (mins >= 60)  level = 2;
            else                  level = 1;
        }

        const cell = document.createElement('div');
        cell.className = 'hm-cell';
        cell.setAttribute('data-level', isCurrentYear ? level : '0');
        cell.setAttribute('data-date', dateStr);
        cell.setAttribute('data-mins', mins);
        cell.setAttribute('data-sessions', sessions);
        cell.style.opacity = isCurrentYear ? '1' : '0.2';
        
        // Month label tracking
        if (isCurrentYear && d.getDate() === 1) {
            const col = Math.floor(cells.length / 7);
            monthLabelPositions[col] = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];
        }

        cell.addEventListener('mousemove', showTooltip);
        cell.addEventListener('mouseleave', hideTooltip);
        
        grid.appendChild(cell);
        cells.push(cell);
        d.setDate(d.getDate() + 1);
    }

    // Build month labels
    const totalCols = Math.ceil(cells.length / 7);
    let lastLabel = '';
    for (let col = 0; col < totalCols; col++) {
        const label = monthLabelPositions[col] || '';
        const div = document.createElement('div');
        div.style.cssText = 'width:17px;text-align:left;font-size:10px;color:var(--text-muted);';
        div.textContent = label && label !== lastLabel ? label : '';
        if (label) lastLabel = label;
        monthLabels.appendChild(div);
    }
}

function showTooltip(e) {
    const cell = e.currentTarget;
    const date = cell.getAttribute('data-date');
    const mins = parseInt(cell.getAttribute('data-mins')) || 0;
    const sessions = parseInt(cell.getAttribute('data-sessions')) || 0;
    const tooltip = document.getElementById('hmTooltip');
    
    const d = new Date(date + 'T12:00:00');
    const formatted = d.toLocaleDateString('en-US', {weekday:'short', month:'short', day:'numeric', year:'numeric'});
    
    let content = `<strong>${formatted}</strong><br>`;
    if (mins > 0) {
        const h = Math.floor(mins/60), m = mins%60;
        content += `⏱️ ${h > 0 ? h+'h ' : ''}${m}m studied<br>`;
        content += `📚 ${sessions} session${sessions!==1?'s':''}`;
    } else {
        content += `<span style="color:var(--text-muted)">No study recorded</span>`;
    }
    
    tooltip.innerHTML = content;
    tooltip.style.display = 'block';
    tooltip.style.left = (e.clientX + 12) + 'px';
    tooltip.style.top = (e.clientY - 40) + 'px';
}

function hideTooltip() {
    document.getElementById('hmTooltip').style.display = 'none';
}

buildHeatmap();
</script>

<?php require_once 'includes/footer.php'; ?>