<?php
file_put_contents(__DIR__ . "/../bot_debug.log", "[" . date("H:i:s") . "] bmi.php loaded\n", FILE_APPEND);

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

/**
 * Handle /bmi command or button clicks
 */
function handleBMICommand($chat_id, $text = null) {
    file_put_contents(__DIR__ . "/../bot_debug.log", "[" . date("H:i:s") . "] handleBMICommand started for $chat_id\n", FILE_APPEND);
    global $pdo, $sessions, $sessionFile;

    // ✅ Ensure session is initialized
    if (!isset($sessions[$chat_id])) {
        $sessions[$chat_id] = ["bmi_step" => null, "bmi_inputs" => []];
    }

    if (!isset($sessions[$chat_id]["bmi_inputs"])) {
        $sessions[$chat_id]["bmi_inputs"] = [];
    }

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

    // ✅ Detect if user clicked "Recalculate BMI"
    $isRecalc = ($text === "recalc");

    // ✅ Show stored BMI only if NOT recalculating
    if (
        !$isRecalc &&
        $user &&
        $user['weight'] &&
        $user['height'] &&
        $user['age'] &&
        empty($sessions[$chat_id]['bmi_step'])
    ) {
        sendBMIMessage($chat_id);
        file_put_contents(__DIR__ . "/../bot_debug.log", "[" . date("H:i:s") . "] Sent BMI message step X\n", FILE_APPEND);
        return;
    }

    // ✅ If no user found or we’re recalculating → start guided flow
    $step = $sessions[$chat_id]["bmi_step"] ?? null;
    $inputs = &$sessions[$chat_id]["bmi_inputs"];

    // Step 1: No step set yet → ask for weight
    if (!$step) {
        $sessions[$chat_id]["bmi_step"] = "weight";
        saveSessions($sessions, $sessionFile);
        sendMessage($chat_id, "Let's calculate your BMI and calories! 🧮\n\nEnter your <b>Weight (kg)</b>:\nExample: <code>70</code>");
        return;
    }

    // Step 2: Weight
    if ($step === "weight") {
        $val = trim($text);
        if (!is_numeric($val) || $val < 20 || $val > 300) {
            sendMessage($chat_id, "⚠️ Please enter a valid weight between 20 and 300 kg.\nExample: <code>70</code>");
            return;
        }
        $inputs["weight"] = $val;
        $sessions[$chat_id]["bmi_step"] = "height";
        saveSessions($sessions, $sessionFile);
        sendMessage($chat_id, "Enter your <b>Height (cm)</b>:\nExample: <code>175</code>");
        return;
    }

    // Step 3: Height
    if ($step === "height") {
        $val = trim($text);
        if (!is_numeric($val) || $val < 50 || $val > 250) {
            sendMessage($chat_id, "⚠️ Please enter a valid height between 50 and 250 cm.\nExample: <code>175</code>");
            return;
        }
        $inputs["height"] = $val;
        $sessions[$chat_id]["bmi_step"] = "age";
        saveSessions($sessions, $sessionFile);
        sendMessage($chat_id, "Enter your <b>Age (years)</b>:\nExample: <code>24</code>");
        return;
    }

    // Step 4: Age
    if ($step === "age") {
        $val = trim($text);
        if (!is_numeric($val) || $val < 10 || $val > 100) {
            sendMessage($chat_id, "⚠️ Please enter a valid age between 10 and 100.\nExample: <code>24</code>");
            return;
        }
        $inputs["age"] = $val;
        $sessions[$chat_id]["bmi_step"] = "goal";
        saveSessions($sessions, $sessionFile);
        sendMessage($chat_id, "What’s your <b>Goal</b>?\nOptions: <code>muscle</code>, <code>weight_loss</code>, <code>fat_loss</code>, <code>weight_fat_loss</code>");
        return;
    }

    // Step 5: Goal → Save all, calculate BMI
    if ($step === "goal") {
        $inputs["goal"] = strtolower(trim($text));

        $stmt = $pdo->prepare("
            INSERT INTO users (chat_id, weight, height, age, goal)
            VALUES (:chat_id, :weight, :height, :age, :goal)
            ON DUPLICATE KEY UPDATE
            weight=:weight, height=:height, age=:age, goal=:goal
        ");
        $stmt->execute([
            ':chat_id' => $chat_id,
            ':weight'  => $inputs["weight"],
            ':height'  => $inputs["height"],
            ':age'     => $inputs["age"],
            ':goal'    => $inputs["goal"],
        ]);

        // ✅ Clear BMI session
        unset($sessions[$chat_id]["bmi_step"]);
        unset($sessions[$chat_id]["bmi_inputs"]);
        saveSessions($sessions, $sessionFile);

        // ✅ Calculate and display new BMI
        calculateUserStats($chat_id);
        return;
    }
}

/**
 * Calculate BMI, BMR, and TDEE
 */
function calculateUserStats($chat_id) {
    global $pdo;

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

    if (!$user || !$user['weight'] || !$user['height'] || !$user['age']) {
        sendMessage($chat_id, "⚠️ Not enough data found to calculate BMI.\nPlease start again using /bmi");
        return;
    }

    $weight = floatval($user['weight']);
    $height = floatval($user['height']);
    $age    = intval($user['age']);
    $goal   = strtolower(trim($user['goal']));
    $gender = strtolower(trim($user['gender'] ?? 'male'));

    // Mifflin-St Jeor: male +5, female -161
    $height_m    = $height / 100;
    $bmi         = round($weight / ($height_m * $height_m), 2);
    $genderConst = ($gender === 'female') ? -161 : 5;
    $bmr         = round((10 * $weight) + (6.25 * $height) - (5 * $age) + $genderConst);
    $tdee        = round($bmr * 1.55);

    if ($goal === "muscle") $tdee += 300;
    if (in_array($goal, ["weight_loss", "fat_loss", "weight_fat_loss"])) $tdee -= 300;

    // ✅ Update user table (for quick reference)
    $stmt = $pdo->prepare("UPDATE users SET bmi=?, bmr=?, maintenance_calories=? WHERE chat_id=?");
    $stmt->execute([$bmi, $bmr, $tdee, $chat_id]);

    // ✅ Check last BMI entry to enforce weekly limit
    $stmt = $pdo->prepare("
        SELECT created_at FROM bmi_history 
        WHERE chat_id = ? 
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    $stmt->execute([$chat_id]);
    $last = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($last) {
        $lastDate = new DateTime($last['created_at']);
        $now = new DateTime();
        $days = $now->diff($lastDate)->days;
        if ($days < 7) {
            $wait = 7 - $days;
            sendMessage($chat_id, "⏳ You’ve already calculated your BMI recently.\nPlease wait <b>{$wait} more day(s)</b> before recalculating again.");
            return;
        }
    }

    // ✅ Save new BMI record to history
    $stmt = $pdo->prepare("
        INSERT INTO bmi_history (chat_id, weight, height, bmi, bmr, tdee, goal)
        VALUES (:chat_id, :weight, :height, :bmi, :bmr, :tdee, :goal)
    ");
    $stmt->execute([
        ':chat_id' => $chat_id,
        ':weight'  => $weight,
        ':height'  => $height,
        ':bmi'     => $bmi,
        ':bmr'     => $bmr,
        ':tdee'    => $tdee,
        ':goal'    => $goal
    ]);

    // ✅ Send summary message
    sendBMIMessage($chat_id, $weight, $height, $bmi, $bmr, $tdee, $goal);
}


/**
 * Send BMI Summary
 */
function sendBMIMessage($chat_id, $weight = null, $height = null, $bmi = null, $bmr = null, $tdee = null, $goal = null) {
    file_put_contents(__DIR__ . "/../bot_debug.log", "[" . date("H:i:s") . "] Sent BMI message step X\n", FILE_APPEND);

    global $pdo;

    // ✅ Fetch data if not passed
    if (!$bmi) {
        $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 user data found. Please enter /bmi to start.");
            return;
        }
        $weight = $user['weight'];
        $height = $user['height'];
        $bmi    = $user['bmi'];
        $bmr    = $user['bmr'];
        $tdee   = $user['maintenance_calories'];
        $goal   = $user['goal'];
    }

    // ✅ Determine BMI status
    $bmi_status = ($bmi < 18.5) ? "Underweight 😕" :
                  (($bmi < 24.9) ? "Normal ✅" :
                  (($bmi < 29.9) ? "Overweight ⚠️" : "Obese ❌"));

    // ✅ Build summary message
    $msg = "📊 <b>Your Fitness Summary</b>\n\n";
    $msg .= "🏋️‍♂️ Weight: <b>{$weight} kg</b>\n";
    $msg .= "📏 Height: <b>{$height} cm</b>\n";
    $msg .= "🧮 BMI: <b>{$bmi}</b> ({$bmi_status})\n";
    $msg .= "🔥 BMR: <b>{$bmr} kcal/day</b>\n";
    $msg .= "⚡ Maintenance (TDEE): <b>{$tdee} kcal/day</b>\n";
    $msg .= "🎯 Goal: <b>" . ucfirst($goal) . "</b>";

    $keyboard = [
        "inline_keyboard" => [
            [["text" => "♻️ Recalculate BMI", "callback_data" => "re_bmi"]],
            [["text" => "🍽️ Diet Plan",       "callback_data" => "start_diet"],
             ["text" => "💪 Workout Plan",    "callback_data" => "start_workout"]],
            [["text" => "📈 My Status",       "callback_data" => "view_status"],
             ["text" => "🏠 Main Menu",       "callback_data" => "main_menu"]],
        ]
    ];

    sendMessage($chat_id, $msg, $keyboard);
    file_put_contents(__DIR__ . "/../bot_debug.log", "[" . date("H:i:s") . "] Sent BMI message step X\n", FILE_APPEND);

}
?>