<?php
global $config;
include_once __DIR__ . "/../db.php";
include_once __DIR__ . "/../prompts.php";
include_once __DIR__ . "/../gemini.php";
include_once __DIR__ . "/../chatgpt.php";

/**
 * Handle full Diet Plan flow
 */
function handleDietFlow($chat_id, $text = null) {
    global $pdo, $sessions, $sessionFile;

    if (!isset($sessions[$chat_id])) {
        $sessions[$chat_id] = ["step" => null, "inputs" => [], "lastPlan" => null];
    }

    $step = $sessions[$chat_id]["step"] ?? null;

    // === START FLOW ===
    if ($text === "start" || !$step) {
        $sessions[$chat_id]["step"] = "ask_for_whom";
        saveSessions($sessions, $sessionFile);
        sendMessage($chat_id, "Is this diet for you?\nOptions: <code>yes</code> / <code>no</code>");
        return;
    }

    // === STEP 1: ASK FOR WHOM ===
    if ($step === "ask_for_whom") {
        $response = strtolower(trim($text));

        if (in_array($response, ["yes", "y"])) {
            $sessions[$chat_id]["inputs"]["save_to_db"] = true;
            $sessions[$chat_id]["step"] = "name";
            saveSessions($sessions, $sessionFile);
            sendMessage($chat_id, "✅ Great! What’s your <b>First Name</b>?");
            return;

        } elseif (in_array($response, ["no", "n"])) {
            $sessions[$chat_id]["inputs"]["save_to_db"] = false;
            $sessions[$chat_id]["step"] = "name";
            saveSessions($sessions, $sessionFile);
            sendMessage($chat_id, "Alright! Let’s make a quick plan (it won’t be saved).\nWhat’s your <b>First Name</b>?");
            return;

        } else {
            sendMessage($chat_id, "Please reply with <code>yes</code> or <code>no</code>.");
            return;
        }
    }

    // === MULTI-STEP QUESTION FLOW ===
    switch ($step) {
        case "name":
            $sessions[$chat_id]["inputs"]["name"] = trim($text);
            $sessions[$chat_id]["step"] = "weight";
            sendMessage($chat_id, "Enter your <b>Weight (kg)</b>:\nExample: <code>70</code>");
            break;

        case "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;
            }
            $sessions[$chat_id]["inputs"]["weight"] = $val;
            $sessions[$chat_id]["step"] = "height";
            sendMessage($chat_id, "Enter your <b>Height (cm)</b>:\nExample: <code>175</code>");
            break;

        case "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;
            }
            $sessions[$chat_id]["inputs"]["height"] = $val;
            $sessions[$chat_id]["step"] = "age";
            sendMessage($chat_id, "Enter your <b>Age (years)</b>:\nExample: <code>24</code>");
            break;

        case "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;
            }
            $sessions[$chat_id]["inputs"]["age"] = $val;
            $sessions[$chat_id]["step"] = "gender";
            sendMessage($chat_id, "Enter your <b>Gender</b>:\nOptions: <code>male</code>, <code>female</code>");
            break;

        case "gender":
            $sessions[$chat_id]["inputs"]["gender"] = strtolower(trim($text));
            $sessions[$chat_id]["step"] = "goal";
            sendMessage($chat_id, "Enter your <b>Goal</b>:\nOptions: <code>muscle</code>, <code>weight_loss</code>, <code>fat_loss</code>, <code>weight_fat_loss</code>");
            break;

        case "goal":
            $sessions[$chat_id]["inputs"]["goal"] = strtolower(trim($text));
            $sessions[$chat_id]["step"] = "diet";
            sendMessage($chat_id, "Enter your <b>Diet Preference</b>:\nOptions: <code>veg</code>, <code>nonveg</code>, <code>vegan</code>, <code>eggetarian</code>");
            break;

        case "diet":
            $sessions[$chat_id]["inputs"]["diet"] = strtolower(trim($text));
            $sessions[$chat_id]["step"] = "budget";
            sendMessage($chat_id, "Enter your <b>Monthly Budget (₹)</b>:\nExample: <code>2500</code>");
            break;

        case "budget":
            $val = trim($text);
            if (!is_numeric($val) || $val < 500 || $val > 100000) {
                sendMessage($chat_id, "⚠️ Please enter a valid monthly budget between ₹500 and ₹1,00,000.\nExample: <code>2500</code>");
                return;
            }
            $sessions[$chat_id]["inputs"]["budget"] = $val;
            $sessions[$chat_id]["step"] = "wake";
            sendMessage($chat_id, "Enter your <b>Morning Wake-up Time</b>:\nExample: <code>6:30 AM</code>");
            break;

        case "wake":
            $sessions[$chat_id]["inputs"]["wake"] = trim($text);
            $sessions[$chat_id]["step"] = "bed";
            sendMessage($chat_id, "Enter your <b>Bedtime</b>:\nExample: <code>11:00 PM</code>");
            break;

        case "bed":
            $sessions[$chat_id]["inputs"]["bed"] = trim($text);
            $sessions[$chat_id]["step"] = "workout";
            sendMessage($chat_id, "When do you <b>Workout</b>?\nOptions: <code>morning</code>, <code>evening</code>, <code>none</code>");
            break;

        case "workout":
            $sessions[$chat_id]["inputs"]["workout"] = strtolower(trim($text));
            $sessions[$chat_id]["step"] = "notes";
            sendMessage($chat_id, "Any <b>Notes</b> (allergies/dislikes)?\nExample: <code>no peanuts</code>\n(If none, type <code>none</code>)");
            break;

        // === FINAL STEP — AUTO GENERATE PLAN ===
        case "notes":
            $sessions[$chat_id]["inputs"]["notes"] = trim($text);
            $sessions[$chat_id]["step"] = "generate";
            saveSessions($sessions, $sessionFile);

            $estimatedCost = getSettingInt('diet_plan_cost', 10);
            sendMessage($chat_id, "⚡ Generating your custom diet plan... Please wait ~60 seconds.\n💳 Estimated cost: <b>~{$estimatedCost} credits</b> (final cost may vary by plan complexity).");

            // trigger immediate generation
            handleDietFlow($chat_id, "__auto_generate__");
            return;

        case "generate":
            if ($text !== "__auto_generate__") return;

            $isSub = hasActiveSubscription($chat_id);

            // Credit check only for non-subscribers
            if (!$isSub) {
                $cost    = getSettingInt('diet_plan_cost', 10);
                $credits = getUserCredits($chat_id);
                if ($credits < $cost) {
                    sendInsufficientCreditsMessage($chat_id, $cost, $credits);
                    unset($sessions[$chat_id]["step"], $sessions[$chat_id]["inputs"]);
                    saveSessions($sessions, $sessionFile);
                    return;
                }
            }

            $i = $sessions[$chat_id]["inputs"];

            // build AI prompt
            $prompt = userPrompt(
                $i["weight"], $i["height"], $i["age"], $i["gender"], $i["goal"],
                $i["diet"], $i["budget"], $i["wake"], $i["bed"],
                $i["workout"], $i["notes"]
            );

            // show typing
            file_get_contents("https://api.telegram.org/bot{$GLOBALS['config']['telegram_token']}/sendChatAction?chat_id={$chat_id}&action=typing");

            $plan = null;
            try {
                $plan = askGemini($prompt);
            } catch (Throwable $e) {
                error_log("Gemini Error: " . $e->getMessage());
            }

            // fallback
            if (!is_array($plan) || empty($plan["json"])) {
                sendMessage($chat_id, "⚙️ Gemini returned empty. Trying ChatGPT...");
                try {
                    $plan = askChatGPT($prompt);
                } catch (Throwable $e) {
                    error_log("ChatGPT Error: " . $e->getMessage());
                    $plan = null;
                }
            }

            if (empty($plan) || !isset($plan["json"])) {
                sendMessage($chat_id, "❌ Unable to generate your diet plan right now. Please try again later.");
                unset($sessions[$chat_id]["step"], $sessions[$chat_id]["inputs"]);
                saveSessions($sessions, $sessionFile);
                return;
            }

            // === SAVE & DISPLAY PLAN ===
            $sessions[$chat_id]["lastPlan"] = $plan["json"];
            $detailedText = formatDietPlanText($plan["json"]);

            $keyboard = [
                "inline_keyboard" => [
                    [["text" => "🔄 New Diet Plan",  "callback_data" => "restart_diet"],
                     ["text" => "📄 Download PDF",   "callback_data" => "download_pdf"]],
                    [["text" => "💪 Workout Plan",   "callback_data" => "start_workout"],
                     ["text" => "⚖️ Log Weight",     "callback_data" => "log_weight_prompt"]],
                    [["text" => "📊 My Status",      "callback_data" => "view_status"],
                     ["text" => "🏠 Main Menu",      "callback_data" => "main_menu"]],
                ]
            ];

            // Deduct credits only for non-subscribers, actual cost based on plan complexity
            if (!$isSub) {
                $cost = calculateDietPlanCredits($plan["json"]);
                deductCredits($chat_id, $cost, 'Diet Plan');
            }
            $remaining = getUserCredits($chat_id);

            if (!empty($i["save_to_db"])) {
                saveUserDietDataToDB($chat_id, $i);
                saveDietPlanToDB($chat_id, json_encode($plan["json"], JSON_UNESCAPED_UNICODE));
                sendMessage($chat_id, "✅ Your personalized diet plan has been saved!");
            }

            sendLongMessage($chat_id, $detailedText, $keyboard);
            if ($isSub) {
                sendMessage($chat_id, "⭐ Generated free with your Premium subscription!");
            } else {
                sendCreditDeductedNotice($chat_id, $cost, $remaining);
            }

            include_once __DIR__ . "/../functions/bmi.php";
            calculateUserStats($chat_id);

            unset($sessions[$chat_id]["step"], $sessions[$chat_id]["inputs"]);
            saveSessions($sessions, $sessionFile);
            break;
    }

    saveSessions($sessions, $sessionFile);
}

/**
 * Save or insert user data (fixes FK constraint)
 */
function saveUserDietDataToDB($chat_id, $i) {
    global $pdo;

    // check if user exists
    $check = $pdo->prepare("SELECT chat_id FROM users WHERE chat_id = ?");
    $check->execute([$chat_id]);
    $exists = $check->fetchColumn();

    if ($exists) {
        // update existing user
        $stmt = $pdo->prepare("UPDATE users SET 
            first_name=?, weight=?, height=?, age=?, gender=?, goal=?, diet=?, budget=?, 
            wake_time=?, bed_time=?, workout=?, notes=?, updated_at=NOW() 
            WHERE chat_id=?");
        $stmt->execute([
            $i["name"] ?? null,
            $i["weight"] ?? null,
            $i["height"] ?? null,
            $i["age"] ?? null,
            $i["gender"] ?? null,
            $i["goal"] ?? null,
            $i["diet"] ?? null,
            $i["budget"] ?? null,
            $i["wake"] ?? null,
            $i["bed"] ?? null,
            $i["workout"] ?? null,
            $i["notes"] ?? null,
            $chat_id
        ]);
    } else {
        // insert new user (ensures FK consistency)
        $stmt = $pdo->prepare("INSERT INTO users 
            (chat_id, first_name, weight, height, age, gender, goal, diet, budget, wake_time, bed_time, workout, notes)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $chat_id,
            $i["name"] ?? null,
            $i["weight"] ?? null,
            $i["height"] ?? null,
            $i["age"] ?? null,
            $i["gender"] ?? null,
            $i["goal"] ?? null,
            $i["diet"] ?? null,
            $i["budget"] ?? null,
            $i["wake"] ?? null,
            $i["bed"] ?? null,
            $i["workout"] ?? null,
            $i["notes"] ?? null
        ]);
    }
}

/**
 * Save generated diet plan JSON
 */
function saveDietPlanToDB($chat_id, $plan) {
    global $pdo;
    $stmt = $pdo->prepare("INSERT INTO diet_plans (chat_id, plan) VALUES (?, ?)");
    $stmt->execute([$chat_id, $plan]);
}

/**
 * Retrieve saved diet plan
 */
function handleMyDietCommand($chat_id) {
    global $pdo, $sessions;
    $stmt = $pdo->prepare("SELECT plan, created_at FROM diet_plans WHERE chat_id = ? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$chat_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $userName = $sessions[$chat_id]["inputs"]["name"] ?? "User";
        sendMessage($chat_id, "🍱 Your saved diet plan (created on {$row['created_at']}):\n\n" . formatDietPlanText(json_decode($row["plan"], true), $userName));
    } else {
        sendMessage($chat_id, "You don’t have a saved diet plan yet. Type /diet to create one.");
    }
}
?>
