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

/**
 * Multi-step workout plan flow
 */
function handleWorkoutFlow($chat_id, $text = null) {
    global $sessions, $sessionFile;

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

    $step   = $sessions[$chat_id]["workout_step"] ?? null;
    $inputs = &$sessions[$chat_id]["workout_inputs"];

    // === START ===
    if ($text === "start" || !$step) {
        $sessions[$chat_id]["workout_step"]   = "fitness_level";
        $sessions[$chat_id]["workout_inputs"] = [];
        saveSessions($sessions, $sessionFile);
        sendMessage($chat_id, "💪 <b>Workout Plan Generator</b>\n\nWhat is your <b>Fitness Level</b>?\nOptions: <code>beginner</code>, <code>intermediate</code>, <code>advanced</code>");
        return;
    }

    switch ($step) {
        case "fitness_level":
            $val = strtolower(trim($text));
            if (!in_array($val, ["beginner", "intermediate", "advanced"])) {
                sendMessage($chat_id, "⚠️ Please choose: <code>beginner</code>, <code>intermediate</code>, or <code>advanced</code>");
                return;
            }
            $inputs["fitness_level"] = $val;
            $sessions[$chat_id]["workout_step"] = "equipment";
            saveSessions($sessions, $sessionFile);
            sendMessage($chat_id, "🏋️ What <b>Equipment</b> do you have?\n<code>none</code> – Bodyweight only\n<code>dumbbells</code> – Home gym\n<code>full_gym</code> – Full gym access");
            break;

        case "equipment":
            $val = strtolower(trim($text));
            if (!in_array($val, ["none", "dumbbells", "full_gym"])) {
                sendMessage($chat_id, "⚠️ Please choose: <code>none</code>, <code>dumbbells</code>, or <code>full_gym</code>");
                return;
            }
            $inputs["equipment"] = $val;
            $sessions[$chat_id]["workout_step"] = "days";
            saveSessions($sessions, $sessionFile);
            sendMessage($chat_id, "📅 How many <b>Days per Week</b> can you train?\nOptions: <code>3</code>, <code>4</code>, <code>5</code>, <code>6</code>");
            break;

        case "days":
            $val = intval(trim($text));
            if (!in_array($val, [3, 4, 5, 6])) {
                sendMessage($chat_id, "⚠️ Please enter <code>3</code>, <code>4</code>, <code>5</code>, or <code>6</code> days.");
                return;
            }
            $inputs["days"] = $val;
            $sessions[$chat_id]["workout_step"] = "goal";
            saveSessions($sessions, $sessionFile);
            sendMessage($chat_id, "🎯 What is your <b>Workout Goal</b>?\n<code>muscle</code>, <code>fat_loss</code>, <code>strength</code>, <code>endurance</code>");
            break;

        case "goal":
            $val = strtolower(trim($text));
            if (!in_array($val, ["muscle", "fat_loss", "strength", "endurance"])) {
                sendMessage($chat_id, "⚠️ Please choose: <code>muscle</code>, <code>fat_loss</code>, <code>strength</code>, or <code>endurance</code>");
                return;
            }
            $inputs["goal"] = $val;
            $sessions[$chat_id]["workout_step"] = "duration";
            saveSessions($sessions, $sessionFile);
            sendMessage($chat_id, "⏱️ How long can you <b>Train per Session</b>?\nOptions: <code>30</code>, <code>45</code>, <code>60</code>, <code>90</code> minutes");
            break;

        case "duration":
            $val = intval(trim($text));
            if (!in_array($val, [30, 45, 60, 90])) {
                sendMessage($chat_id, "⚠️ Please choose: <code>30</code>, <code>45</code>, <code>60</code>, or <code>90</code> minutes.");
                return;
            }
            $inputs["duration"] = $val;
            $sessions[$chat_id]["workout_step"] = "generate";
            saveSessions($sessions, $sessionFile);

            $estimatedCost = getSettingInt('workout_plan_cost', 20);
            sendMessage($chat_id, "⚡ Generating your custom workout plan... Please wait ~30 seconds.\n💳 Estimated cost: <b>~{$estimatedCost} credits</b> (final cost may vary by plan complexity).");
            handleWorkoutFlow($chat_id, "__auto_generate__");
            return;

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

            $isSub = hasActiveSubscription($chat_id);

            if (!$isSub) {
                $cost    = getSettingInt('workout_plan_cost', 20);
                $credits = getUserCredits($chat_id);
                if ($credits < $cost) {
                    sendInsufficientCreditsMessage($chat_id, $cost, $credits);
                    unset($sessions[$chat_id]["workout_step"], $sessions[$chat_id]["workout_inputs"]);
                    saveSessions($sessions, $sessionFile);
                    return;
                }
            }

            $i      = $sessions[$chat_id]["workout_inputs"];
            $prompt = workoutPrompt($i["fitness_level"], $i["equipment"], $i["days"], $i["goal"], $i["duration"]);

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

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

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

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

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

            saveWorkoutPlanToDB($chat_id, json_encode($plan["json"], JSON_UNESCAPED_UNICODE));
            $sessions[$chat_id]["lastWorkout"] = $plan["json"];

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

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

            unset($sessions[$chat_id]["workout_step"], $sessions[$chat_id]["workout_inputs"]);
            saveSessions($sessions, $sessionFile);
            break;
    }

    saveSessions($sessions, $sessionFile);
}

/**
 * Format workout plan JSON as Telegram HTML text
 */
function formatWorkoutPlanText($json) {
    $msg = "💪 <b>Your Custom Workout Plan</b>\n\n";

    if (!empty($json["meta"]["label"])) {
        $msg .= "👤 {$json['meta']['label']}\n\n";
    }

    foreach ($json["schedule"] as $day) {
        $msg .= "📅 <b>{$day['day']}</b> — {$day['focus']}\n";
        if (!empty($day["warmup"])) $msg .= "🔥 Warmup: {$day['warmup']}\n";

        foreach ($day["exercises"] as $ex) {
            $msg .= "• <b>{$ex['name']}</b>: {$ex['sets']} sets × {$ex['reps']} reps | Rest: {$ex['rest']}\n";
            if (!empty($ex["notes"])) $msg .= "  📝 {$ex['notes']}\n";
        }

        if (!empty($day["cooldown"])) $msg .= "🧘 Cooldown: {$day['cooldown']}\n";
        $msg .= "\n";
    }

    if (!empty($json["rest_days"])) {
        $msg .= "😴 <b>Rest Days:</b> " . implode(", ", $json["rest_days"]) . "\n\n";
    }

    if (!empty($json["tips"])) {
        $msg .= "💡 <b>Tips</b>\n";
        foreach ($json["tips"] as $t) $msg .= "- {$t}\n";
        $msg .= "\n";
    }

    if (!empty($json["notes"])) {
        $msg .= "📌 <b>Notes:</b> {$json['notes']}\n";
    }

    return $msg;
}

/**
 * Save workout plan to DB
 */
function saveWorkoutPlanToDB($chat_id, $plan) {
    global $pdo;
    $pdo->prepare("INSERT INTO workout_plans (chat_id, plan) VALUES (?, ?)")->execute([$chat_id, $plan]);
}

/**
 * Retrieve and display saved workout plan
 */
function handleMyWorkoutCommand($chat_id) {
    global $pdo;

    $stmt = $pdo->prepare("SELECT plan, created_at FROM workout_plans WHERE chat_id = ? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$chat_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $header = "💪 Your saved workout plan (created on {$row['created_at']}):\n\n";
        sendLongMessage($chat_id, $header . formatWorkoutPlanText(json_decode($row["plan"], true)));
    } else {
        sendMessage($chat_id, "You don't have a saved workout plan yet. Type /workout to create one.");
    }
}

/**
 * Generate and send workout plan as PDF
 */
function sendWorkoutPlanPdf($chat_id, $json) {
    global $config;
    require_once __DIR__ . '/../vendor/autoload.php';

    $mpdf = new \Mpdf\Mpdf();
    $mpdf->SetWatermarkText("TextraHost");
    $mpdf->showWatermarkText  = true;
    $mpdf->watermarkTextAlpha = 0.1;

    $label = htmlspecialchars($json["meta"]["label"] ?? "Workout Plan");
    $html  = "<h2 style='color:#0ea5a4;'>{$label}</h2>";

    foreach ($json["schedule"] as $day) {
        $html .= "<h3>📅 {$day['day']} — " . htmlspecialchars($day['focus']) . "</h3>";
        if (!empty($day["warmup"])) $html .= "<p><b>Warmup:</b> " . htmlspecialchars($day['warmup']) . "</p>";
        $html .= "<table border='1' cellpadding='5' cellspacing='0' width='100%'>";
        $html .= "<tr><th>Exercise</th><th>Sets</th><th>Reps</th><th>Rest</th><th>Notes</th></tr>";
        foreach ($day["exercises"] as $ex) {
            $html .= "<tr><td>{$ex['name']}</td><td>{$ex['sets']}</td><td>{$ex['reps']}</td><td>{$ex['rest']}</td><td>" . htmlspecialchars($ex['notes'] ?? '') . "</td></tr>";
        }
        $html .= "</table>";
        if (!empty($day["cooldown"])) $html .= "<p><b>Cooldown:</b> " . htmlspecialchars($day['cooldown']) . "</p>";
    }

    if (!empty($json["rest_days"])) {
        $html .= "<p><b>Rest Days:</b> " . implode(", ", $json["rest_days"]) . "</p>";
    }
    if (!empty($json["tips"])) {
        $html .= "<h3>💡 Tips</h3><ul>";
        foreach ($json["tips"] as $t) $html .= "<li>" . htmlspecialchars($t) . "</li>";
        $html .= "</ul>";
    }
    if (!empty($json["notes"])) {
        $html .= "<p><b>Notes:</b> " . htmlspecialchars($json["notes"]) . "</p>";
    }

    $mpdf->WriteHTML($html);
    $filePath = __DIR__ . "/../workout_{$chat_id}.pdf";
    $mpdf->Output($filePath, \Mpdf\Output\Destination::FILE);

    $url  = "https://api.telegram.org/bot{$config['telegram_token']}/sendDocument";
    $post = [
        'chat_id'  => $chat_id,
        'document' => new CURLFile($filePath),
        'caption'  => "📄 {$label} (TextraHost)"
    ];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $post,
        CURLOPT_RETURNTRANSFER => true
    ]);
    curl_exec($ch);

    if (file_exists($filePath)) unlink($filePath);
}
