<?php
file_put_contents(__DIR__ . "/bot_debug.log", "[" . date("H:i:s") . "] Bot started\n", FILE_APPEND);

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$config = include "config.php";
global $config;
include_once "db.php";
include_once "prompts.php";
include_once "gemini.php";
include_once "chatgpt.php";
include_once __DIR__ . "/functions/credits.php";
include_once __DIR__ . "/functions/subscription.php";
include_once __DIR__ . "/functions/streak.php";
include_once __DIR__ . "/functions/referral.php";
include_once __DIR__ . "/functions/tools.php";
include_once __DIR__ . "/functions/workout_log.php";
include_once __DIR__ . "/functions/reports.php";
include_once __DIR__ . "/functions/diet.php";
include_once __DIR__ . "/functions/bmi.php";
include_once __DIR__ . "/functions/workout.php";
include_once __DIR__ . "/functions/progress.php";
include_once __DIR__ . "/functions/admin.php";
file_put_contents(__DIR__ . "/bot_debug.log", "[" . date("H:i:s") . "] Includes OK\n", FILE_APPEND);

// ==== TELEGRAM UPDATE ====
$update          = json_decode(file_get_contents("php://input"), true);
$update_id       = $update["update_id"] ?? null;
$chat_id         = $update["message"]["chat"]["id"] ?? ($update["callback_query"]["message"]["chat"]["id"] ?? null);
$text            = $update["message"]["text"] ?? null;
$callback_data   = $update["callback_query"]["data"] ?? null;
$callback_msg_id = $update["callback_query"]["message"]["message_id"] ?? null;
$callback_id     = $update["callback_query"]["id"] ?? null;
$first_name      = $update["message"]["from"]["first_name"] ?? null;

// ==== DEDUPLICATION ====
$updateCacheFile = __DIR__ . "/last_update_id.txt";
if ($update_id) {
    $last_id = @file_get_contents($updateCacheFile);
    if ($last_id == $update_id) {
        http_response_code(200);
        exit;
    }
    file_put_contents($updateCacheFile, $update_id);
}

// ==== SESSION STORE ====
$sessionFile = __DIR__ . "/sessions.json";
if (!file_exists($sessionFile)) file_put_contents($sessionFile, "{}");
$sessions = loadSessions($sessionFile);

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

// ==== /start (with optional referral param) ====
if ($text !== null && strpos($text, '/start') === 0) {
    file_put_contents(__DIR__ . "/bot_debug.log", "[" . date("H:i:s") . "] /start received\n", FILE_APPEND);
    $startParam = trim(substr($text, 6));
    if ($startParam !== '' && strpos($startParam, 'ref_') === 0) {
        processReferral($chat_id, $startParam);
    }
    // Save first_name if new user
    if ($first_name) {
        $pdo->prepare("INSERT INTO users (chat_id, first_name) VALUES (?, ?) ON DUPLICATE KEY UPDATE first_name = IF(first_name IS NULL, ?, first_name)")
            ->execute([$chat_id, $first_name, $first_name]);
    }
    sendMainMenu($chat_id);
    saveSessions($sessions, $sessionFile);
    exit;
}

// ==== /help ====
if ($text == "/help" || $callback_data == "help_menu") {
    $keyboard = [
        "inline_keyboard" => [
            [["text" => "🍽️ Diet Plan",    "callback_data" => "start_diet"],
             ["text" => "💪 Workout Plan", "callback_data" => "start_workout"]],
            [["text" => "📊 Check BMI",    "callback_data" => "bmi_start"],
             ["text" => "📈 My Status",    "callback_data" => "view_status"]],
            [["text" => "🗂️ My Diet",      "callback_data" => "view_diet"],
             ["text" => "🏋️ My Workout",   "callback_data" => "view_workout"]],
            [["text" => "⚖️ Log Weight",   "callback_data" => "log_weight_prompt"]],
            [["text" => "🏠 Main Menu",    "callback_data" => "main_menu"]],
        ]
    ];
    sendMessage($chat_id, "❓ <b>Help Menu</b>\n\nTap any feature to launch it:", $keyboard);
    exit;
}

// ==== DIET CALLBACKS & COMMANDS ====
if ($callback_data == "start_diet" || $callback_data == "restart_diet") {
    handleDietFlow($chat_id, "start");
    exit;
}
if ($callback_data == "view_diet") {
    handleMyDietCommand($chat_id);
    exit;
}
if ($text == "/diet") {
    handleDietFlow($chat_id, "start");
    exit;
}
if ($text == "/mydiet") {
    handleMyDietCommand($chat_id);
    exit;
}
if ($callback_data == "download_pdf") {
    $plan = $sessions[$chat_id]["lastPlan"] ?? null;
    if ($plan) {
        sendDietPlanPdf($chat_id, $plan, $sessions[$chat_id]["inputs"]["name"] ?? "User");
    } else {
        sendMessage($chat_id, "❌ No diet plan found. Please generate one first with /diet.");
    }
    exit;
}

// ==== WORKOUT CALLBACKS & COMMANDS ====
if ($callback_data == "start_workout" || $callback_data == "restart_workout") {
    handleWorkoutFlow($chat_id, "start");
    exit;
}
if ($callback_data == "view_workout") {
    handleMyWorkoutCommand($chat_id);
    exit;
}
if ($text == "/workout") {
    handleWorkoutFlow($chat_id, "start");
    exit;
}
if ($text == "/myworkout") {
    handleMyWorkoutCommand($chat_id);
    exit;
}
if ($callback_data == "download_workout_pdf") {
    $plan = $sessions[$chat_id]["lastWorkout"] ?? null;
    if ($plan) {
        sendWorkoutPlanPdf($chat_id, $plan);
    } else {
        sendMessage($chat_id, "❌ No workout plan found. Please generate one first with /workout.");
    }
    exit;
}

// ==== BMI CALLBACKS & COMMANDS ====
if ($callback_data == "bmi_start" || $callback_data == "view_bmi") {
    file_put_contents(__DIR__ . "/bot_debug.log", "[" . date("H:i:s") . "] BMI callback triggered\n", FILE_APPEND);
    handleBMICommand($chat_id, "");
    saveSessions($sessions, $sessionFile);
    exit;
}
if ($callback_data == "re_bmi") {
    unset($sessions[$chat_id]["bmi_step"], $sessions[$chat_id]["bmi_inputs"]);
    saveSessions($sessions, $sessionFile);
    handleBMICommand($chat_id, "recalc");
    saveSessions($sessions, $sessionFile);
    exit;
}
if ($text == "/re_bmi" || strpos($text, "/bmi") === 0) {
    if ($text == "/re_bmi") {
        unset($sessions[$chat_id]["bmi_step"], $sessions[$chat_id]["bmi_inputs"]);
        saveSessions($sessions, $sessionFile);
        handleBMICommand($chat_id, "recalc");
    } else {
        handleBMICommand($chat_id, $text);
    }
    saveSessions($sessions, $sessionFile);
    exit;
}

// ==== NAVIGATION CALLBACKS ====
if ($callback_data == "main_menu") {
    sendMainMenu($chat_id);
    exit;
}
if ($callback_data == "log_weight_prompt") {
    $sessions[$chat_id]["log_step"] = "awaiting";
    saveSessions($sessions, $sessionFile);
    sendMessage($chat_id, "⚖️ <b>Log Your Weight</b>\n\nEnter your current weight in kg:\nExample: <code>72.5</code>");
    exit;
}

// ==== PROGRESS CALLBACKS & COMMANDS ====
if ($callback_data == "view_status") {
    handleStatusCommand($chat_id);
    exit;
}
if ($text == "/status") {
    handleStatusCommand($chat_id);
    exit;
}
if (strpos($text, "/log") === 0) {
    handleLogCommand($chat_id, $text);
    exit;
}

// ==== ADMIN COMMANDS ====
if (strpos($text, "/admin") === 0) {
    handleAdminCommand($chat_id, $text);
    exit;
}

// ==== ADMIN QUICK-GRANT CREDIT BUTTONS ====
if ($callback_data && preg_match('/^admin_grant_(\d+)_(\d+)$/', $callback_data, $m)) {
    if (isAdmin($chat_id)) {
        handleAdminGrantCredits($chat_id, (int)$m[1], (int)$m[2]);
    }
    exit;
}

// ==== SUBSCRIPTION ====
if ($text === '/sub' || $callback_data === 'show_subscription') {
    sendSubscriptionInfo($chat_id);
    exit;
}

// ==== REFERRAL ====
if ($text === '/referral' || $callback_data === 'show_referral') {
    sendReferralInfo($chat_id);
    exit;
}

// ==== FREE TOOLS MENU ====
if ($text === '/tools' || $callback_data === 'tools_menu') {
    sendToolsMenu($chat_id);
    exit;
}
if ($callback_data === 'tool_water') {
    $sessions[$chat_id]['tool_step'] = 'water';
    saveSessions($sessions, $sessionFile);
    promptWaterInput($chat_id);
    exit;
}
if ($callback_data === 'tool_cal') {
    $sessions[$chat_id]['tool_step'] = 'cal';
    saveSessions($sessions, $sessionFile);
    promptCalInput($chat_id);
    exit;
}
if ($callback_data === 'tool_1rm') {
    $sessions[$chat_id]['tool_step'] = '1rm';
    saveSessions($sessions, $sessionFile);
    prompt1RMInput($chat_id);
    exit;
}
if ($callback_data === 'tool_bfat') {
    startBodyFat($chat_id);
    exit;
}

// /water, /cal, /1rm shortcut commands
if ($text !== null && strpos($text, '/water ') === 0) {
    handleWaterLog($chat_id, trim(substr($text, 7)));
    exit;
}
if ($text !== null && strpos($text, '/cal ') === 0) {
    handleCalorieLookup($chat_id, trim(substr($text, 5)));
    exit;
}
if ($text !== null && strpos($text, '/1rm ') === 0) {
    handleOneRM($chat_id, trim(substr($text, 5)));
    exit;
}
if ($text === '/bfat') {
    startBodyFat($chat_id);
    exit;
}

// ==== WORKOUT LOGGER (button-based) ====
if ($callback_data === 'log_workout_today') {
    showWorkoutLogger($chat_id);
    exit;
}
if ($callback_data && preg_match('/^wlog_toggle_(\d+)$/', $callback_data, $m)) {
    if ($callback_id) answerCallback($callback_id);
    handleWorkoutLogToggle($chat_id, (int)$m[1], $callback_msg_id);
    exit;
}
if ($callback_data === 'wlog_all') {
    if ($callback_id) answerCallback($callback_id);
    handleWorkoutLogMarkAll($chat_id, $callback_msg_id);
    exit;
}
if ($callback_data === 'wlog_save') {
    if ($callback_id) answerCallback($callback_id, '✅ Workout saved!');
    handleWorkoutLogSave($chat_id, $callback_msg_id);
    exit;
}

// ==== WEEKLY REPORT ====
if ($text === '/report' || $callback_data === 'generate_report') {
    handleGenerateReport($chat_id);
    exit;
}

// ==== STEP HANDLERS (active conversation flows) ====
if (isset($sessions[$chat_id]["step"])) {
    handleDietFlow($chat_id, $text);
    exit;
}
if (isset($sessions[$chat_id]["bmi_step"])) {
    handleBMICommand($chat_id, $text);
    exit;
}
if (isset($sessions[$chat_id]["workout_step"])) {
    handleWorkoutFlow($chat_id, $text);
    exit;
}
if (isset($sessions[$chat_id]["log_step"]) && $sessions[$chat_id]["log_step"] === "awaiting") {
    unset($sessions[$chat_id]["log_step"]);
    saveSessions($sessions, $sessionFile);
    handleLogCommand($chat_id, "/log " . $text);
    exit;
}
if (isset($sessions[$chat_id]["bfat_step"])) {
    handleBodyFatStep($chat_id, $text);
    exit;
}
if (isset($sessions[$chat_id]["tool_step"])) {
    $toolStep = $sessions[$chat_id]["tool_step"];
    unset($sessions[$chat_id]["tool_step"]);
    saveSessions($sessions, $sessionFile);
    if ($toolStep === 'water')  { handleWaterLog($chat_id, $text); exit; }
    if ($toolStep === 'cal')    { handleCalorieLookup($chat_id, $text); exit; }
    if ($toolStep === '1rm')    { handleOneRM($chat_id, $text); exit; }
}

// ==== HELPERS ====
function sendMainMenu($chat_id) {
    $isSub   = hasActiveSubscription($chat_id);
    $subText = $isSub ? "⭐ My Subscription" : "⭐ Go Premium";

    $keyboard = [
        "inline_keyboard" => [
            [["text" => "🍽️ Diet Plan",      "callback_data" => "start_diet"],
             ["text" => "💪 Workout Plan",   "callback_data" => "start_workout"]],
            [["text" => "📊 Check BMI",      "callback_data" => "bmi_start"],
             ["text" => "📈 My Status",      "callback_data" => "view_status"]],
            [["text" => "📝 Log Workout",    "callback_data" => "log_workout_today"],
             ["text" => "⚖️ Log Weight",     "callback_data" => "log_weight_prompt"]],
            [["text" => "🛠️ Free Tools",     "callback_data" => "tools_menu"],
             ["text" => $subText,            "callback_data" => "show_subscription"]],
            [["text" => "👥 Refer &amp; Earn", "callback_data" => "show_referral"],
             ["text" => "❓ Help",            "callback_data" => "help_menu"]],
        ]
    ];
    sendMessage($chat_id, "👋 Welcome to <b>TextraHost Gym Bot</b>! 💪\n\nChoose an option to get started:", $keyboard);
}

function answerCallback($callback_id, $text = '') {
    global $config;
    $url = "https://api.telegram.org/bot{$config['telegram_token']}/answerCallbackQuery";
    $data = ['callback_query_id' => $callback_id];
    if ($text !== '') $data['text'] = $text;
    $ch = curl_init($url);
    curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => $data]);
    curl_exec($ch);
}

function sendMessage($chat_id, $text, $keyboard = null) {
    global $config;
    $url  = "https://api.telegram.org/bot{$config['telegram_token']}/sendMessage";
    $data = [
        "chat_id"    => $chat_id,
        "text"       => $text,
        "parse_mode" => "HTML"
    ];
    if ($keyboard) $data["reply_markup"] = json_encode($keyboard);

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

/**
 * Split and send long messages at newline boundaries (avoids breaking HTML tags).
 */
function sendLongMessage($chat_id, $text, $keyboard = null) {
    $limit = 4000;

    if (mb_strlen($text) <= $limit) {
        sendMessage($chat_id, $text, $keyboard);
        return;
    }

    $chunks = [];
    while (mb_strlen($text) > $limit) {
        $slice  = mb_substr($text, 0, $limit);
        $cutAt  = mb_strrpos($slice, "\n");
        if ($cutAt === false) $cutAt = $limit;
        $chunks[] = mb_substr($text, 0, $cutAt);
        $text     = ltrim(mb_substr($text, $cutAt), "\n");
    }
    if ($text !== '') $chunks[] = $text;

    foreach ($chunks as $index => $chunk) {
        $markup = ($index === count($chunks) - 1) ? $keyboard : null;
        sendMessage($chat_id, $chunk, $markup);
        usleep(200000);
    }
}

function loadSessions($file) {
    $fp      = fopen($file, 'c+');
    flock($fp, LOCK_SH);
    $content = stream_get_contents($fp);
    flock($fp, LOCK_UN);
    fclose($fp);
    return json_decode($content ?: '{}', true) ?? [];
}

function saveSessions($sessions, $file) {
    $fp = fopen($file, 'c+');
    flock($fp, LOCK_EX);
    ftruncate($fp, 0);
    fwrite($fp, json_encode($sessions));
    flock($fp, LOCK_UN);
    fclose($fp);
}

function formatDietPlanText($json, $userName = "User") {
    $firstName = ucfirst(explode(" ", trim($userName))[0]);
    $msg = "📋 <b>{$firstName}'s Custom Gym Diet Plan</b>\n\n";

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

    foreach ($json["meals"] as $meal) {
        $msg .= "🍽️ <b>{$meal['name']}</b>";
        if (!empty($meal['time'])) $msg .= " ({$meal['time']})";
        $msg .= "\n";
        if (!empty($meal["items"])) {
            foreach ($meal["items"] as $item) {
                $msg .= "- {$item['food']} ({$item['qty']}) — P:{$item['protein']}g C:{$item['carbs']}g F:{$item['fat']}g {$item['kcal']} kcal\n";
            }
        }
        if (!empty($meal["mealTotals"])) {
            $msg .= "➡️ Totals: P:{$meal['mealTotals']['protein']}g C:{$meal['mealTotals']['carbs']}g F:{$meal['mealTotals']['fat']}g {$meal['mealTotals']['kcal']} kcal\n";
        }
        if (!empty($meal["alternatives"])) {
            $msg .= "🔄 Alternatives: " . implode("; ", $meal["alternatives"]) . "\n";
        }
        $msg .= "\n";
    }

    if (!empty($json["totals"])) {
        $msg .= "🔥 <b>Daily Totals</b>\nCalories: {$json['totals']['kcal']} kcal\n\n";
        $msg .= "Protein: {$json['totals']['protein']}g | Carbs: {$json['totals']['carbs']}g | Fat: {$json['totals']['fat']}g\n\n";
    }

    if (!empty($json["supplements"])) {
        $msg .= "💊 <b>Supplements (optional)</b>\n";
        foreach ($json["supplements"] as $s) $msg .= "- {$s}\n";
        $msg .= "\n";
    }

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

    return $msg;
}

function sendDietPlanPdf($chat_id, $json, $userName = "User") {
    global $config;
    require_once __DIR__ . '/vendor/autoload.php';

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

    $firstName = explode(" ", trim($userName))[0];
    $safeFirst = preg_replace('/[^a-zA-Z0-9_-]/', '', $firstName) ?: 'User';
    $pdfTitle  = htmlspecialchars($firstName) . "'s Custom Diet Plan";

    $html = "<h2 style='color:#0ea5a4;'>{$pdfTitle}</h2>";
    if (!empty($json['meta']['label'])) $html .= "<p><b>{$json['meta']['label']}</b></p>";

    foreach ($json["meals"] as $meal) {
        $html .= "<h3>🍴 {$meal['name']} " . (!empty($meal['time']) ? "({$meal['time']})" : "") . "</h3><ul>";
        foreach ($meal["items"] as $item) {
            $html .= "<li>{$item['food']} ({$item['qty']}) — P:{$item['protein']}g C:{$item['carbs']}g F:{$item['fat']}g {$item['kcal']} kcal</li>";
        }
        $html .= "</ul>";
        if (!empty($meal["mealTotals"])) {
            $html .= "<p><i>Totals: Protein {$meal['mealTotals']['protein']}g | Carbs {$meal['mealTotals']['carbs']}g | Fat {$meal['mealTotals']['fat']}g | {$meal['mealTotals']['kcal']} kcal</i></p>";
        }
        if (!empty($meal["alternatives"])) {
            $html .= "<p><b>Alternatives:</b> " . implode("; ", $meal["alternatives"]) . "</p>";
        }
    }

    if (!empty($json["totals"])) {
        $html .= "<hr><h3>🔥 Daily Totals</h3>";
        $html .= "<p>Calories: {$json['totals']['kcal']} kcal<br>Protein: {$json['totals']['protein']}g | Carbs: {$json['totals']['carbs']}g | Fat: {$json['totals']['fat']}g</p>";
    }
    if (!empty($json["supplements"])) {
        $html .= "<h3>💊 Supplements</h3><ul>";
        foreach ($json["supplements"] as $s) $html .= "<li>{$s}</li>";
        $html .= "</ul>";
    }
    if (!empty($json["tips"])) {
        $html .= "<h3>💡 Tips</h3><ul>";
        foreach ($json["tips"] as $t) $html .= "<li>{$t}</li>";
        $html .= "</ul>";
    }

    $mpdf->WriteHTML($html);
    $filePath = __DIR__ . "/{$safeFirst}_dietplan_{$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'  => "📄 {$pdfTitle} (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);
}
