<?php
/**
 * Study Points — simple earning system: 1 hour studied = 1 point.
 *
 * Points are added to the existing `users.xp_points` column (already used
 * by Achievements / Leaderboard), so everything you earn here also shows
 * up there automatically.
 *
 * How it avoids double-counting / farming:
 * We don't award points per-session directly (a user could log lots of
 * tiny sessions, or delete-and-re-add a session, to farm points). Instead
 * we track total lifetime minutes studied vs. how many points have
 * already been paid out (`users.study_points_awarded`), and only ever
 * top up the difference:
 *
 *   points_due = floor(total_minutes_ever_studied / 60) - already_awarded
 *
 * If points_due > 0, we add that many points to xp_points and bump
 * study_points_awarded to match. Deleting a session lowers the lifetime
 * total but never claws back points already paid out — it just means
 * fewer new points are due until real study time "catches back up".
 */

// ── Self-migrating column (safe to call on every request) ──
function ensureStudyPointsColumn($pdo) {
    try {
        $col = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'study_points_awarded'");
        if ($col && !$col->fetch()) {
            $pdo->exec("ALTER TABLE `users` ADD COLUMN `study_points_awarded` INT NOT NULL DEFAULT 0");
        }
    } catch (Exception $e) {
        // non-fatal — points feature just won't run until this succeeds
    }
}

/**
 * Call after a study session is saved. Awards 1 point per full hour of
 * *lifetime* study time not yet paid out. Returns the number of points
 * newly awarded (0 if not a full hour yet).
 */
function awardStudyPoints($pdo, $uid) {
    try {
        $sumStmt = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=?");
        $sumStmt->execute([$uid]);
        $totalMinutes = (int)$sumStmt->fetchColumn();
        $totalPointsEarned = intdiv($totalMinutes, 60);

        $userStmt = $pdo->prepare("SELECT COALESCE(study_points_awarded,0) FROM users WHERE id=?");
        $userStmt->execute([$uid]);
        $alreadyAwarded = (int)$userStmt->fetchColumn();

        $newPoints = $totalPointsEarned - $alreadyAwarded;
        if ($newPoints > 0) {
            $pdo->prepare("UPDATE users SET xp_points = COALESCE(xp_points,0) + ?, study_points_awarded = ? WHERE id=?")
                ->execute([$newPoints, $totalPointsEarned, $uid]);
        }
        return max(0, $newPoints);
    } catch (Exception $e) {
        return 0;
    }
}

/** Current point balance (used to display on Study Log / Dashboard). */
function getStudyPointsBalance($pdo, $uid) {
    try {
        $stmt = $pdo->prepare("SELECT COALESCE(xp_points,0) FROM users WHERE id=?");
        $stmt->execute([$uid]);
        return (int)$stmt->fetchColumn();
    } catch (Exception $e) {
        return 0;
    }
}

/** Minutes still needed until the next point (for a "x mins to next point" hint). */
function minutesToNextStudyPoint($pdo, $uid) {
    try {
        $sumStmt = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=?");
        $sumStmt->execute([$uid]);
        $totalMinutes = (int)$sumStmt->fetchColumn();
        $rem = $totalMinutes % 60;
        return $rem === 0 ? 0 : (60 - $rem);
    } catch (Exception $e) {
        return 0;
    }
}
