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

    $url = "https://api.openai.com/v1/chat/completions";

    $postData = [
        "model" => $config["chatgpt_model"], // e.g. gpt-4o-mini
        "messages" => [
            [
                "role" => "system",
                "content" =>
"⚠️ IMPORTANT:
You are a professional Fitness & Nutrition Expert.
Always respond ONLY with a valid single JSON object in this structure:

{
  \"json\": {
    \"meta\": { \"label\": \"70kg — Muscle Building, Veg, ₹2500 budget\" },
    \"meals\": [
      {
        \"name\": \"Breakfast\",
        \"time\": \"8:00 AM\",
        \"items\": [
          { \"food\": \"Oats\", \"qty\": \"60g\", \"protein\": 9, \"carbs\": 36, \"fat\": 4, \"kcal\": 210 },
          { \"food\": \"Milk\", \"qty\": \"200ml\", \"protein\": 7, \"carbs\": 10, \"fat\": 0, \"kcal\": 70 }
        ],
        \"mealTotals\": { \"protein\": 16, \"carbs\": 46, \"fat\": 4, \"kcal\": 280 },
        \"alternatives\": [\"Replace oats with chapati\", \"Milk can be replaced with curd\"]
      }
    ],
    \"totals\": { \"protein\": 120, \"carbs\": 300, \"fat\": 60, \"kcal\": 2200 },
    \"tips\": [\"Stay consistent\", \"Drink 3L water\"],
    \"supplements\": [\"Whey protein (optional)\", \"Multivitamin (optional)\"]
  },
  \"summary\": \"📋 70kg Veg Diet, ₹2500 budget — ~2200 kcal, ~120g protein. Balanced meals with oats, dal, rice, and soya.\"
}

Rules:
- Output JSON only (no markdown, no code fences, no extra text).
- Always include 'json' and 'summary' fields.
- Meals[] must have name, time, items[], mealTotals, alternatives."
            ],
            ["role" => "user", "content" => $prompt]
        ],
        "temperature" => 0.7
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Authorization: " . "Bearer " . $config["openai_api_key"]
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
    curl_setopt($ch, CURLOPT_TIMEOUT, 180);

    $response = curl_exec($ch);
    $error    = curl_error($ch);

    if ($error) {
        error_log("ChatGPT cURL Error: " . $error);
        return null;
    }

    $data = json_decode($response, true);

    if (isset($data["choices"][0]["message"]["content"])) {
        $raw = trim($data["choices"][0]["message"]["content"]);

        // clean accidental code 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;
        }

        error_log("ChatGPT invalid JSON: " . substr($raw, 0, 300));
        return null;
    }

    error_log("ChatGPT no text in response. Raw: " . substr($response, 0, 300));
    return null;
}

function askChatGPTWorkout($prompt) {
    global $config;

    $url      = "https://api.openai.com/v1/chat/completions";
    $postData = [
        "model"       => $config["chatgpt_model"],
        "messages"    => [
            [
                "role"    => "system",
                "content" => "You are a professional fitness coach. Reply ONLY with valid JSON matching the structure requested in the user message. No markdown, no code fences, no extra text."
            ],
            ["role" => "user", "content" => $prompt]
        ],
        "temperature" => 0.7
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Authorization: Bearer " . $config["openai_api_key"]
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
    curl_setopt($ch, CURLOPT_TIMEOUT, 180);

    $response = curl_exec($ch);
    $error    = curl_error($ch);

    if ($error) {
        error_log("ChatGPT Workout cURL Error: " . $error);
        return null;
    }

    $data = json_decode($response, true);
    if (!isset($data["choices"][0]["message"]["content"])) {
        error_log("ChatGPT Workout no text: " . substr($response, 0, 300));
        return null;
    }

    $raw = trim($data["choices"][0]["message"]["content"]);
    $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("ChatGPT Workout invalid JSON: " . substr($raw, 0, 300));
    return null;
}
