<?php
// AJAX endpoint: returns chart data for dashboard
require_once 'includes/config.php';
requireLogin();

$uid    = $_SESSION['user_id'];
$period = $_GET['period'] ?? 'week';

if ($period === 'month') {
    // Last 30 days — group by day
    $data = [];
    for ($i = 29; $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]);
        // Show every 5th label to avoid crowding
        $label = ($i % 5 === 0 || $i === 0) ? date('M j', strtotime($d)) : '';
        $data[] = ['date' => $label, 'minutes' => (int)$q->fetchColumn()];
    }
} else {
    // Last 7 days
    $data = [];
    for ($i = 6; $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]);
        $data[] = ['date' => date('D', strtotime($d)), 'minutes' => (int)$q->fetchColumn()];
    }
}

jsonResponse(['success' => true, 'data' => $data, 'period' => $period]);
