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

/**
 * Build the weekly progress report text for a user.
 */
function buildWeeklyReport($chat_id): string {
    global $pdo;

    $weekStart = date('Y-m-d', strtotime('last Monday'));
    $weekEnd   = date('Y-m-d', strtotime('next Sunday'));

    // User profile
    $user = $pdo->prepare("SELECT first_name, weight, goal, credits FROM users WHERE chat_id = ?");
    $user->execute([$chat_id]);
    $user = $user->fetch(PDO::FETCH_ASSOC);
    if (!$user) return '';

    $name = $user['first_name'] ?? "User";
    $goal = ucwords(str_replace('_', ' ', $user['goal'] ?? 'Not set'));

    // Weight logs this week
    $wStmt = $pdo->prepare("SELECT weight, logged_at FROM progress WHERE chat_id = ? AND DATE(logged_at) BETWEEN ? AND ? ORDER BY logged_at ASC");
    $wStmt->execute([$chat_id, $weekStart, $weekEnd]);
    $weightLogs = $wStmt->fetchAll(PDO::FETCH_ASSOC);

    // Diet plans generated this week
    $dStmt = $pdo->prepare("SELECT COUNT(*) FROM diet_plans WHERE chat_id = ? AND DATE(created_at) BETWEEN ? AND ?");
    $dStmt->execute([$chat_id, $weekStart, $weekEnd]);
    $dietCount = (int)$dStmt->fetchColumn();

    // Workout plans generated this week
    $wkStmt = $pdo->prepare("SELECT COUNT(*) FROM workout_plans WHERE chat_id = ? AND DATE(created_at) BETWEEN ? AND ?");
    $wkStmt->execute([$chat_id, $weekStart, $weekEnd]);
    $workoutCount = (int)$wkStmt->fetchColumn();

    // Exercises logged this week
    $exStmt = $pdo->prepare("SELECT COUNT(*) FROM workout_log WHERE chat_id = ? AND DATE(logged_at) BETWEEN ? AND ?");
    $exStmt->execute([$chat_id, $weekStart, $weekEnd]);
    $exerciseCount = (int)$exStmt->fetchColumn();

    // Water logs this week
    $h2oStmt = $pdo->prepare("SELECT COALESCE(SUM(litres), 0) FROM water_log WHERE chat_id = ? AND DATE(logged_at) BETWEEN ? AND ?");
    $h2oStmt->execute([$chat_id, $weekStart, $weekEnd]);
    $totalWater = round((float)$h2oStmt->fetchColumn(), 1);

    // Streak
    include_once __DIR__ . '/streak.php';
    $streak = getStreak($chat_id);

    // Credits spent this week
    $crStmt = $pdo->prepare("SELECT COALESCE(ABS(SUM(amount)), 0) FROM credit_transactions WHERE chat_id = ? AND amount < 0 AND DATE(created_at) BETWEEN ? AND ?");
    $crStmt->execute([$chat_id, $weekStart, $weekEnd]);
    $creditsSpent = (int)$crStmt->fetchColumn();

    // Build report text
    $from = date('d M', strtotime($weekStart));
    $to   = date('d M Y', strtotime($weekEnd));

    $msg  = "📊 <b>Weekly Progress Report</b>\n";
    $msg .= "👤 {$name} | 🎯 {$goal}\n";
    $msg .= "📅 {$from} – {$to}\n\n";

    // Weight section
    if (!empty($weightLogs)) {
        $firstW = (float)$weightLogs[0]['weight'];
        $lastW  = (float)end($weightLogs)['weight'];
        $diff   = round($lastW - $firstW, 1);
        $arrow  = $diff < 0 ? '⬇️' : ($diff > 0 ? '⬆️' : '➡️');
        $sign   = $diff > 0 ? '+' : '';
        $msg   .= "⚖️ <b>Weight</b>\n";
        $msg   .= "  Start: {$firstW}kg → End: {$lastW}kg {$arrow} {$sign}{$diff}kg\n";
        $msg   .= "  Logged: <b>" . count($weightLogs) . " days</b>\n\n";
    } else {
        $msg .= "⚖️ <b>Weight:</b> No logs this week\n\n";
    }

    // Activity section
    $msg .= "🏃 <b>Activity</b>\n";
    $msg .= "  🍽️ Diet plans:      <b>{$dietCount}</b>\n";
    $msg .= "  💪 Workout plans:   <b>{$workoutCount}</b>\n";
    $msg .= "  📝 Exercises done:  <b>{$exerciseCount}</b>\n";
    if ($totalWater > 0) {
        $msg .= "  💧 Water tracked:   <b>{$totalWater}L</b>\n";
    }
    $msg .= "\n";

    // Streak section
    $msg .= "🔥 <b>Streak</b>\n";
    $msg .= "  Current: <b>{$streak['current']} days</b>";
    if ($streak['current'] > 0) $msg .= " " . streakEmoji($streak['current']);
    $msg .= "\n  Best: <b>{$streak['longest']} days</b>\n\n";

    // Credits
    if ($creditsSpent > 0) {
        $msg .= "💳 Credits used this week: <b>{$creditsSpent}</b>\n\n";
    }

    $msg .= "Keep it up! 💪 See you next week.";
    return $msg;
}

/**
 * Generate, send, and record the weekly report for a user.
 * Returns true if sent successfully.
 */
function sendWeeklyReport($chat_id): bool {
    global $pdo;

    $report = buildWeeklyReport($chat_id);
    if (empty($report)) return false;

    $keyboard = ["inline_keyboard" => [
        [["text" => "📈 My Status",  "callback_data" => "view_status"],
         ["text" => "🏠 Main Menu",  "callback_data" => "main_menu"]],
    ]];
    sendMessage($chat_id, $report, $keyboard);

    // Record it so we don't send twice
    $weekStart = date('Y-m-d', strtotime('last Monday'));
    $pdo->prepare("INSERT IGNORE INTO weekly_reports (chat_id, week_start) VALUES (?, ?)")
        ->execute([$chat_id, $weekStart]);

    return true;
}

/**
 * Send a "report ready" notification to a credit user with a generate button.
 */
function sendWeeklyReportNotification($chat_id): void {
    $credits    = getUserCredits($chat_id);
    $reportCost = getSettingInt('report_cost', 20);

    $msg  = "📊 <b>Your Weekly Report is Ready!</b>\n\n";
    $msg .= "Get your fitness summary for this week.\n\n";
    if ($credits >= $reportCost) {
        $msg .= "💳 Cost: <b>{$reportCost} credits</b> (you have {$credits})\n\n";
    } else {
        $msg .= "⚠️ You need <b>{$reportCost} credits</b> (you have <b>{$credits}</b>).\n\n";
    }
    $msg .= "Or upgrade to ⭐ <b>Premium</b> for free auto-reports every week!";

    $keyboard = ["inline_keyboard" => [
        [["text" => "📊 Generate Report (−{$reportCost} cr)", "callback_data" => "generate_report"]],
        [["text" => "⭐ Go Premium",  "callback_data" => "show_subscription"],
         ["text" => "🏠 Main Menu",   "callback_data" => "main_menu"]],
    ]];
    sendMessage($chat_id, $msg, $keyboard);
}

/**
 * Handle the "Generate Report" callback for credit users — deducts credits and sends report.
 */
function handleGenerateReport($chat_id): void {
    $reportCost = getSettingInt('report_cost', 20);
    $credits    = getUserCredits($chat_id);

    if ($credits < $reportCost) {
        sendInsufficientCreditsMessage($chat_id, $reportCost, $credits);
        return;
    }

    deductCredits($chat_id, $reportCost, 'Weekly Report');
    $remaining = getUserCredits($chat_id);

    sendWeeklyReport($chat_id);
    sendCreditDeductedNotice($chat_id, $reportCost, $remaining);
}
