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

// ─── Shared AI helper (raw JSON response, no plan wrapper) ───────────────────
function callAIForTool(string $prompt): ?array {
    global $config;
    $url  = "https://generativelanguage.googleapis.com/v1beta/models/{$config['gemini_model']}:generateContent?key={$config['gemini_api_key']}";
    $body = json_encode(['contents' => [['parts' => [['text' => $prompt]]]]]);
    $ch   = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS     => $body,
        CURLOPT_TIMEOUT        => 20,
    ]);
    $raw  = curl_exec($ch);
    $data = json_decode($raw, true);
    $text = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';
    if (preg_match('/\{[\s\S]+\}/m', $text, $m)) {
        return json_decode($m[0], true) ?: null;
    }
    return null;
}

// ─── Free Tools Menu ─────────────────────────────────────────────────────────
function sendToolsMenu($chat_id): void {
    $keyboard = [
        "inline_keyboard" => [
            [["text" => "💧 Water Tracker",    "callback_data" => "tool_water"],
             ["text" => "🔍 Calorie Lookup",   "callback_data" => "tool_cal"]],
            [["text" => "🏋️ 1RM Calculator",   "callback_data" => "tool_1rm"],
             ["text" => "📏 Body Fat %",        "callback_data" => "tool_bfat"]],
            [["text" => "🏠 Main Menu",         "callback_data" => "main_menu"]],
        ]
    ];
    sendMessage($chat_id,
        "🛠️ <b>Free Tools</b>\n\n" .
        "All tools below are <b>completely free</b> — no credits, no subscription needed.\n\n" .
        "Choose a tool:",
        $keyboard
    );
}

// ─── Water Tracker ───────────────────────────────────────────────────────────
function promptWaterInput($chat_id): void {
    sendMessage($chat_id,
        "💧 <b>Water Tracker</b>\n\n" .
        "How many litres did you drink today?\n" .
        "Example: <code>2.5</code>\n\n" .
        "<i>Free — no credits needed</i>"
    );
}

function handleWaterLog($chat_id, $litresInput): void {
    global $pdo;
    $litres = (float)$litresInput;

    if ($litres <= 0 || $litres > 20) {
        sendMessage($chat_id, "⚠️ Enter a valid amount (0.1–20 litres). Example: <code>2.5</code>");
        return;
    }

    $pdo->prepare("INSERT INTO water_log (chat_id, litres) VALUES (?, ?)")->execute([$chat_id, $litres]);

    $totalStmt = $pdo->prepare("SELECT COALESCE(SUM(litres),0) FROM water_log WHERE chat_id = ? AND DATE(logged_at) = CURDATE()");
    $totalStmt->execute([$chat_id]);
    $total = round((float)$totalStmt->fetchColumn(), 2);
    $goal  = 2.5;
    $pct   = min(100, (int)round($total / $goal * 100));
    $filled = (int)round($pct / 10);
    $bar   = str_repeat('🟦', $filled) . str_repeat('⬜', 10 - $filled);

    $msg  = "💧 <b>+{$litres}L logged!</b>\n\n";
    $msg .= "Today: <b>{$total}L</b> / {$goal}L goal\n";
    $msg .= "{$bar} {$pct}%";
    if ($total >= $goal) $msg .= "\n\n✅ <b>Daily water goal reached!</b> 🎉";

    sendMessage($chat_id, $msg, ["inline_keyboard" => [
        [["text" => "💧 Log More",  "callback_data" => "tool_water"],
         ["text" => "🛠️ Tools",     "callback_data" => "tools_menu"]],
        [["text" => "🏠 Main Menu", "callback_data" => "main_menu"]],
    ]]);
}

// ─── Calorie Lookup ──────────────────────────────────────────────────────────
function promptCalInput($chat_id): void {
    sendMessage($chat_id,
        "🔍 <b>Calorie Lookup</b>\n\n" .
        "What food do you want to look up?\n" .
        "Examples:\n• <code>chicken breast 150g</code>\n• <code>2 boiled eggs</code>\n• <code>1 cup oats</code>\n\n" .
        "<i>Free — no credits needed</i>"
    );
}

function handleCalorieLookup($chat_id, $query): void {
    $query = trim($query);
    if (empty($query)) {
        promptCalInput($chat_id);
        return;
    }

    sendMessage($chat_id, "🔍 Looking up <code>" . htmlspecialchars($query) . "</code>...");

    $prompt = "Give exact nutritional info for: \"{$query}\"\nRespond ONLY with valid JSON (no markdown):\n{\"food\":\"full name\",\"serving\":\"amount description\",\"calories\":number,\"protein_g\":number,\"carbs_g\":number,\"fat_g\":number,\"fiber_g\":number}\nAll macros must be numbers in grams. Be precise.";

    $result = callAIForTool($prompt);

    if (!$result || !isset($result['calories'])) {
        sendMessage($chat_id,
            "⚠️ Couldn't find info for that. Try being more specific.\n" .
            "Example: <code>grilled chicken breast 100g</code>",
            ["inline_keyboard" => [[["text" => "🔍 Try Again", "callback_data" => "tool_cal"], ["text" => "🏠 Menu", "callback_data" => "main_menu"]]]]
        );
        return;
    }

    $msg  = "🍽️ <b>" . htmlspecialchars($result['food'] ?? $query) . "</b>";
    if (!empty($result['serving'])) $msg .= " <i>(" . htmlspecialchars($result['serving']) . ")</i>";
    $msg .= "\n\n";
    $msg .= "🔥 Calories: <b>{$result['calories']} kcal</b>\n";
    $msg .= "🥩 Protein:  <b>{$result['protein_g']}g</b>\n";
    $msg .= "🍚 Carbs:    <b>{$result['carbs_g']}g</b>\n";
    $msg .= "🥑 Fat:      <b>{$result['fat_g']}g</b>\n";
    if (!empty($result['fiber_g'])) $msg .= "🌿 Fiber:    <b>{$result['fiber_g']}g</b>\n";
    $msg .= "\n<i>Free tool ✅</i>";

    sendMessage($chat_id, $msg, ["inline_keyboard" => [
        [["text" => "🔍 Look Up Another", "callback_data" => "tool_cal"],
         ["text" => "🛠️ Tools",           "callback_data" => "tools_menu"]],
        [["text" => "🏠 Main Menu",        "callback_data" => "main_menu"]],
    ]]);
}

// ─── 1RM Calculator ──────────────────────────────────────────────────────────
function prompt1RMInput($chat_id): void {
    sendMessage($chat_id,
        "🏋️ <b>1-Rep Max Calculator</b>\n\n" .
        "Enter weight (kg) and reps done:\n" .
        "Format: <code>weight reps</code>\n" .
        "Example: <code>80 5</code>\n\n" .
        "<i>Free — no credits needed</i>"
    );
}

function handleOneRM($chat_id, $input): void {
    $parts  = preg_split('/\s+/', trim($input));
    $weight = isset($parts[0]) ? (float)$parts[0] : 0;
    $reps   = isset($parts[1]) ? (int)$parts[1]   : 0;

    if ($weight <= 0 || $reps <= 0 || $reps > 30) {
        sendMessage($chat_id, "⚠️ Invalid input. Format: <code>weight reps</code>\nExample: <code>80 5</code>");
        return;
    }

    $epley   = round($weight * (1 + $reps / 30), 1);
    $brzycki = $reps < 37 ? round($weight / (1.0278 - 0.0278 * $reps), 1) : $epley;
    $avg     = round(($epley + $brzycki) / 2, 1);

    $msg  = "🏋️ <b>Estimated 1-Rep Max</b>\n\n";
    $msg .= "Input: <b>{$weight}kg × {$reps} reps</b>\n\n";
    $msg .= "Epley formula:   <b>{$epley} kg</b>\n";
    $msg .= "Brzycki formula: <b>{$brzycki} kg</b>\n";
    $msg .= "Average:         <b>{$avg} kg</b>\n\n";
    $msg .= "📊 <b>Training Zones</b>\n";
    foreach ([100 => 1, 95 => 2, 90 => 4, 85 => 6, 80 => 8, 75 => 10, 70 => 12] as $pct => $approxReps) {
        $kg   = round($avg * $pct / 100, 1);
        $msg .= "  {$pct}% → <b>{$kg}kg</b> (~{$approxReps} reps)\n";
    }
    $msg .= "\n<i>Free tool ✅</i>";

    sendMessage($chat_id, $msg, ["inline_keyboard" => [
        [["text" => "🏋️ Calculate Again", "callback_data" => "tool_1rm"],
         ["text" => "🛠️ Tools",           "callback_data" => "tools_menu"]],
        [["text" => "🏠 Main Menu",        "callback_data" => "main_menu"]],
    ]]);
}

// ─── Body Fat Estimator ──────────────────────────────────────────────────────
function startBodyFat($chat_id): void {
    global $sessions, $sessionFile;
    $sessions[$chat_id]['bfat_step']   = 'gender';
    $sessions[$chat_id]['bfat_inputs'] = [];
    saveSessions($sessions, $sessionFile);
    sendMessage($chat_id,
        "📏 <b>Body Fat Estimator</b> (Navy Formula)\n\n" .
        "Gender? Reply <code>male</code> or <code>female</code>\n\n" .
        "<i>Free — no credits needed</i>"
    );
}

function handleBodyFatStep($chat_id, $text): bool {
    global $sessions, $sessionFile;
    $step = $sessions[$chat_id]['bfat_step'] ?? null;
    if (!$step) return false;

    $inputs = &$sessions[$chat_id]['bfat_inputs'];

    switch ($step) {
        case 'gender':
            $val = strtolower(trim($text));
            if (!in_array($val, ['male', 'female'])) {
                sendMessage($chat_id, "Please reply <code>male</code> or <code>female</code>.");
                return true;
            }
            $inputs['gender'] = $val;
            $sessions[$chat_id]['bfat_step'] = 'height';
            saveSessions($sessions, $sessionFile);
            sendMessage($chat_id, "📏 Your <b>Height</b> in cm (e.g. <code>175</code>):");
            return true;

        case 'height':
            if (!is_numeric($text) || $text < 50 || $text > 250) {
                sendMessage($chat_id, "⚠️ Enter height in cm (50–250)."); return true;
            }
            $inputs['height'] = (float)$text;
            $sessions[$chat_id]['bfat_step'] = 'waist';
            saveSessions($sessions, $sessionFile);
            sendMessage($chat_id, "📏 <b>Waist</b> circumference in cm (measured at navel):");
            return true;

        case 'waist':
            if (!is_numeric($text) || $text < 40 || $text > 250) {
                sendMessage($chat_id, "⚠️ Enter waist in cm."); return true;
            }
            $inputs['waist'] = (float)$text;
            if ($inputs['gender'] === 'female') {
                $sessions[$chat_id]['bfat_step'] = 'hip';
                saveSessions($sessions, $sessionFile);
                sendMessage($chat_id, "📏 <b>Hip</b> circumference in cm (widest point):");
            } else {
                $sessions[$chat_id]['bfat_step'] = 'neck';
                saveSessions($sessions, $sessionFile);
                sendMessage($chat_id, "📏 <b>Neck</b> circumference in cm:");
            }
            return true;

        case 'hip':
            if (!is_numeric($text) || $text < 40 || $text > 250) {
                sendMessage($chat_id, "⚠️ Enter hip in cm."); return true;
            }
            $inputs['hip'] = (float)$text;
            $sessions[$chat_id]['bfat_step'] = 'neck';
            saveSessions($sessions, $sessionFile);
            sendMessage($chat_id, "📏 <b>Neck</b> circumference in cm:");
            return true;

        case 'neck':
            if (!is_numeric($text) || $text < 20 || $text > 80) {
                sendMessage($chat_id, "⚠️ Enter neck in cm."); return true;
            }
            $inputs['neck'] = (float)$text;
            $h = $inputs['height']; $w = $inputs['waist']; $n = $inputs['neck'];

            if ($inputs['gender'] === 'male') {
                $bf = 495 / (1.0324 - 0.19077 * log10($w - $n) + 0.15456 * log10($h)) - 450;
            } else {
                $hip = $inputs['hip'] ?? ($w * 1.05);
                $bf  = 495 / (1.29579 - 0.35004 * log10($w + $hip - $n) + 0.22100 * log10($h)) - 450;
            }
            $bf = max(1, round($bf, 1));

            $cats = $inputs['gender'] === 'male'
                ? [[6,'Essential Fat'],[14,'Athlete 🏅'],[18,'Fitness 💪'],[25,'Average'],[PHP_INT_MAX,'Obese ⚠️']]
                : [[14,'Essential Fat'],[21,'Athlete 🏅'],[25,'Fitness 💪'],[32,'Average'],[PHP_INT_MAX,'Obese ⚠️']];
            $cat = 'Unknown';
            foreach ($cats as [$limit, $label]) { if ($bf < $limit) { $cat = $label; break; } }

            $msg  = "📊 <b>Body Fat Estimate</b>\n\n";
            $msg .= "Body Fat: <b>{$bf}%</b> — {$cat}\n\n";
            $msg .= "<i>Navy formula. Estimate only. Free tool ✅</i>";

            unset($sessions[$chat_id]['bfat_step'], $sessions[$chat_id]['bfat_inputs']);
            saveSessions($sessions, $sessionFile);
            sendMessage($chat_id, $msg, ["inline_keyboard" => [
                [["text" => "📏 Recalculate",  "callback_data" => "tool_bfat"],
                 ["text" => "🛠️ Tools",         "callback_data" => "tools_menu"]],
                [["text" => "🏠 Main Menu",      "callback_data" => "main_menu"]],
            ]]);
            return true;
    }
    return false;
}
