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

/**
 * Handle /log <weight> command
 */
function handleLogCommand($chat_id, $text) {
    global $pdo;

    // Parse weight from "/log 72.5" or bare "72.5"
    $parts  = explode(' ', trim($text), 2);
    $weight = isset($parts[1]) ? trim($parts[1]) : trim($parts[0]);

    if (!is_numeric($weight) || $weight < 20 || $weight > 300) {
        sendMessage($chat_id, "⚠️ Usage: <code>/log 72.5</code>\nEnter your weight in kg (20–300).");
        return;
    }
    $weight = round((float)$weight, 1);

    // Enforce one log per day
    $stmt = $pdo->prepare("SELECT weight, logged_at FROM progress WHERE chat_id = ? ORDER BY logged_at DESC LIMIT 1");
    $stmt->execute([$chat_id]);
    $last = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($last && date('Y-m-d', strtotime($last['logged_at'])) === date('Y-m-d')) {
        sendMessage($chat_id, "⏳ You've already logged your weight today (<b>{$last['weight']} kg</b>).\nCome back tomorrow!");
        return;
    }

    // Insert log
    $pdo->prepare("INSERT INTO progress (chat_id, weight) VALUES (?, ?)")->execute([$chat_id, $weight]);

    // Also update users table for BMI accuracy
    $pdo->prepare("UPDATE users SET weight = ? WHERE chat_id = ?")->execute([$weight, $chat_id]);

    // Update streak
    include_once __DIR__ . '/streak.php';
    $streak = updateStreak($chat_id);

    // Build response
    $msg = "✅ <b>Weight logged:</b> {$weight} kg (" . date('d M Y') . ")";
    if ($last) {
        $diff  = round($weight - $last['weight'], 1);
        $arrow = $diff < 0 ? "⬇️" : ($diff > 0 ? "⬆️" : "➡️");
        $sign  = $diff > 0 ? "+" : "";
        $msg  .= "\n{$arrow} Change since last entry: <b>{$sign}{$diff} kg</b>";
    }

    // Streak line
    if ($streak['is_new'] && $streak['current'] > 0) {
        $emoji = streakEmoji($streak['current']);
        $msg  .= "\n{$emoji} Streak: <b>{$streak['current']} day" . ($streak['current'] > 1 ? 's' : '') . "</b>!";
        if ($streak['milestone']) {
            $msg .= " 🎉 Milestone reached!";
        }
    }

    $keyboard = [
        "inline_keyboard" => [
            [["text" => "📊 My Status",    "callback_data" => "view_status"],
             ["text" => "🍽️ Diet Plan",   "callback_data" => "start_diet"]],
            [["text" => "🏠 Main Menu",   "callback_data" => "main_menu"]],
        ]
    ];
    sendMessage($chat_id, $msg, $keyboard);
}

/**
 * Handle /status command — full fitness dashboard
 */
function handleStatusCommand($chat_id) {
    global $pdo;

    $stmt = $pdo->prepare("SELECT * FROM users WHERE chat_id = ?");
    $stmt->execute([$chat_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        sendMessage($chat_id, "⚠️ No profile found. Use /diet to create your profile first.");
        return;
    }

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

    $msg  = "📊 <b>Your Fitness Dashboard</b>\n";
    $msg .= "👤 <b>{$name}</b> | 🎯 Goal: <b>{$goal}</b>\n";
    $msg .= "💳 Credits: <b>{$credits}</b>";
    $msg .= ($credits === 0 ? " — ⚠️ Top up to generate plans" : "") . "\n\n";

    // Body stats
    if ($user['bmi']) {
        $bmi_status = ($user['bmi'] < 18.5) ? "Underweight 😕" :
                      (($user['bmi'] < 24.9) ? "Normal ✅" :
                      (($user['bmi'] < 29.9) ? "Overweight ⚠️" : "Obese ❌"));
        $msg .= "📏 <b>Body Stats</b>\n";
        $msg .= "  BMI: <b>{$user['bmi']}</b> ({$bmi_status})\n";
        $msg .= "  Weight: <b>{$user['weight']} kg</b> | Height: <b>{$user['height']} cm</b>\n";
        $msg .= "  BMR: <b>{$user['bmr']} kcal/day</b>\n";
        $msg .= "  TDEE: <b>{$user['maintenance_calories']} kcal/day</b>\n\n";
    }

    // Progress trend (last 5 entries)
    $stmt = $pdo->prepare("SELECT weight, logged_at FROM progress WHERE chat_id = ? ORDER BY logged_at DESC LIMIT 5");
    $stmt->execute([$chat_id]);
    $entries = array_reverse($stmt->fetchAll(PDO::FETCH_ASSOC));

    if (!empty($entries)) {
        $msg .= "📈 <b>Progress (last " . count($entries) . " entries)</b>\n";
        $first = (float)$entries[0]['weight'];
        foreach ($entries as $idx => $row) {
            $w    = (float)$row['weight'];
            $date = date('d M', strtotime($row['logged_at']));
            if ($idx === 0) {
                $msg .= "  {$date} — <b>{$w} kg</b> (start)\n";
            } else {
                $diff  = round($w - $first, 1);
                $sign  = $diff > 0 ? "+" : "";
                $arrow = $diff < 0 ? "⬇️" : ($diff > 0 ? "⬆️" : "➡️");
                $msg  .= "  {$date} — <b>{$w} kg</b> {$arrow} {$sign}{$diff} kg total\n";
            }
        }
        $msg .= "\n";
    } else {
        $msg .= "📈 No weight logs yet. Use <code>/log 72.5</code> to start tracking.\n\n";
    }

    // Latest diet plan date
    $stmt = $pdo->prepare("SELECT created_at FROM diet_plans WHERE chat_id = ? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$chat_id]);
    $diet = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($diet) {
        $msg .= "🍽️ Last diet plan: <b>" . date('d M Y', strtotime($diet['created_at'])) . "</b>\n";
    }

    // Latest workout plan date
    $stmt = $pdo->prepare("SELECT created_at FROM workout_plans WHERE chat_id = ? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$chat_id]);
    $wkout = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($wkout) {
        $msg .= "💪 Last workout plan: <b>" . date('d M Y', strtotime($wkout['created_at'])) . "</b>\n";
    }

    $rows = [
        [["text" => "🗂️ My Diet",      "callback_data" => "view_diet"],
         ["text" => "🏋️ My Workout",   "callback_data" => "view_workout"]],
        [["text" => "⚖️ Log Weight",   "callback_data" => "log_weight_prompt"],
         ["text" => "📊 Check BMI",   "callback_data" => "bmi_start"]],
        [["text" => "🏠 Main Menu",   "callback_data" => "main_menu"]],
    ];

    // Show top-up button when credits are low
    if ($credits < 5) {
        global $config;
        $support = ltrim($config['support_username'] ?? '', '@');
        array_splice($rows, 2, 0, [[
            ["text" => "💳 Get More Credits", "url" => "https://t.me/{$support}"]
        ]]);
    }

    sendMessage($chat_id, $msg, ["inline_keyboard" => $rows]);
}
