<?php
function askGemini($prompt) {
    global $config;

    $url = "https://generativelanguage.googleapis.com/v1/models/{$config['gemini_model']}:generateContent?key={$config['gemini_api_key']}";

    $data = [
        "contents" => [[
            "role" => "user",
            "parts" => [[
                "text" =>
                    $prompt . "\n\n" .
                    "⚠️ IMPORTANT RULES:\n" .
                    "- Reply ONLY with valid JSON.\n" .
                    "- Do NOT include markdown, code fences, or explanations.\n" .
                    "- Structure must be:\n" .
                    "{\n" .
                    "  \"json\": {\n" .
                    "    \"meta\": { \"label\": \"70kg — Muscle Building, Veg, ₹2500 budget\" },\n" .
                    "    \"meals\": [\n" .
                    "      {\n" .
                    "        \"name\": \"Breakfast\",\n" .
                    "        \"time\": \"8:00 AM\",\n" .
                    "        \"items\": [\n" .
                    "          { \"food\": \"Oats\", \"qty\": \"60g\", \"protein\": 9, \"carbs\": 36, \"fat\": 4, \"kcal\": 210 },\n" .
                    "          { \"food\": \"Milk\", \"qty\": \"200ml\", \"protein\": 7, \"carbs\": 10, \"fat\": 0, \"kcal\": 70 }\n" .
                    "        ],\n" .
                    "        \"mealTotals\": { \"protein\": 16, \"carbs\": 46, \"fat\": 4, \"kcal\": 280 },\n" .
                    "        \"alternatives\": [\"Replace oats with chapati\", \"Milk can be replaced with curd\"]\n" .
                    "      }\n" .
                    "    ],\n" .
                    "    \"totals\": { \"protein\": 120, \"carbs\": 300, \"fat\": 60, \"kcal\": 2200 },\n" .
                    "    \"tips\": [\"Stay consistent\", \"Drink 3L water\"],\n" .
                    "    \"supplements\": [\"Whey protein (optional)\", \"Multivitamin (optional)\"]\n" .
                    "  },\n" .
                    "  \"summary\": \"📋 70kg Veg Diet, ₹2500 budget — ~2200 kcal, ~120g protein. Balanced meals with oats, dal, rice, and soya.\"\n" .
                    "}\n\n" .
                    "Always include: meals[], totals, tips[], supplements[]."
            ]]
        ]]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_TIMEOUT, 180);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        error_log("Gemini cURL Error: " . curl_error($ch));
        return null;
    }

    $decoded = json_decode($response, true);
    if (isset($decoded["candidates"][0]["content"]["parts"][0]["text"])) {
        $raw = trim($decoded["candidates"][0]["content"]["parts"][0]["text"]);

        // Clean accidental markdown fences
        $raw = preg_replace('/^```json/i', '', $raw);
        $raw = preg_replace('/^```/', '', $raw);
        $raw = preg_replace('/```$/', '', $raw);
        $raw = trim($raw);

        $parsed = json_decode($raw, true);

        if (isset($parsed["json"]) && isset($parsed["summary"])) {
            return $parsed; // ✅ success
        } else {
            error_log("Gemini invalid JSON: " . substr($raw, 0, 300));
            return null; // ✅ null instead of string
        }
    }

    error_log("Gemini Raw Response (no text): " . substr($response, 0, 300));
    return null; // ✅ null instead of string
}
function askGeminiWorkout($prompt) {
    global $config;

    $url = "https://generativelanguage.googleapis.com/v1/models/{$config['gemini_model']}:generateContent?key={$config['gemini_api_key']}";

    $data = [
        "contents" => [[
            "role"  => "user",
            "parts" => [["text" => $prompt]]
        ]]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_TIMEOUT, 180);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        error_log("Gemini Workout cURL Error: " . curl_error($ch));
        return null;
    }

    $decoded = json_decode($response, true);
    if (!isset($decoded["candidates"][0]["content"]["parts"][0]["text"])) {
        error_log("Gemini Workout no text: " . substr($response, 0, 300));
        return null;
    }

    $raw = trim($decoded["candidates"][0]["content"]["parts"][0]["text"]);
    $raw = preg_replace('/^```json/i', '', $raw);
    $raw = preg_replace('/^```/', '', $raw);
    $raw = preg_replace('/```$/', '', $raw);
    $raw = trim($raw);

    $parsed = json_decode($raw, true);
    if (isset($parsed["json"]) && isset($parsed["summary"])) {
        return $parsed;
    }

    error_log("Gemini Workout invalid JSON: " . substr($raw, 0, 300));
    return null;
}
?>
