<?php
include_once __DIR__ . "/../db.php";

function updateStreak($chat_id): array {
    global $pdo;
    $today     = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime('-1 day'));

    $stmt = $pdo->prepare("SELECT current_streak, longest_streak, last_log_date FROM streaks WHERE chat_id = ?");
    $stmt->execute([$chat_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        $pdo->prepare("INSERT INTO streaks (chat_id, current_streak, longest_streak, last_log_date) VALUES (?, 1, 1, ?)")
            ->execute([$chat_id, $today]);
        return ['current' => 1, 'longest' => 1, 'is_new' => true, 'milestone' => false];
    }

    if ($row['last_log_date'] === $today) {
        return ['current' => (int)$row['current_streak'], 'longest' => (int)$row['longest_streak'], 'is_new' => false, 'milestone' => false];
    }

    if ($row['last_log_date'] === $yesterday) {
        $newCurrent = (int)$row['current_streak'] + 1;
        $newLongest = max($newCurrent, (int)$row['longest_streak']);
    } else {
        $newCurrent = 1;
        $newLongest = (int)$row['longest_streak'];
    }

    $pdo->prepare("UPDATE streaks SET current_streak = ?, longest_streak = ?, last_log_date = ? WHERE chat_id = ?")
        ->execute([$newCurrent, $newLongest, $today, $chat_id]);

    $milestone = in_array($newCurrent, [3, 7, 14, 21, 30, 60, 100]);
    return ['current' => $newCurrent, 'longest' => $newLongest, 'is_new' => true, 'milestone' => $milestone];
}

function getStreak($chat_id): array {
    global $pdo;
    $stmt = $pdo->prepare("SELECT current_streak, longest_streak, last_log_date FROM streaks WHERE chat_id = ?");
    $stmt->execute([$chat_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) return ['current' => 0, 'longest' => 0];

    $today     = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime('-1 day'));

    // If last log was not today or yesterday, streak is broken
    if ($row['last_log_date'] !== $today && $row['last_log_date'] !== $yesterday) {
        return ['current' => 0, 'longest' => (int)$row['longest_streak']];
    }

    return ['current' => (int)$row['current_streak'], 'longest' => (int)$row['longest_streak']];
}

function streakEmoji(int $streak): string {
    if ($streak >= 100) return '🏆';
    if ($streak >= 30)  return '🔥';
    if ($streak >= 14)  return '⚡';
    if ($streak >= 7)   return '💪';
    if ($streak >= 3)   return '✨';
    return '🌱';
}
