<?php
require_once '../../includes/functions.php';

$input = file_get_contents('php://input');
$update = json_decode($input, true);
if (!$update) {
    http_response_code(200);
    exit;
}

$stmt = $pdo->query("SELECT setting_key, setting_value FROM app_settings WHERE setting_key IN ('telegram_user_bot_enabled','telegram_user_bot_token','telegram_user_bot_channel_id','telegram_user_welcome_reward_coins')");
$settings = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

$isEnabled = ($settings['telegram_user_bot_enabled'] ?? '0') === '1';
$botToken = $settings['telegram_user_bot_token'] ?? '';
$requiredChannel = trim($settings['telegram_user_bot_channel_id'] ?? '');
$rewardCoins = max(0, (int)($settings['telegram_user_welcome_reward_coins'] ?? 100));

if (!$isEnabled || $botToken === '') {
    http_response_code(200);
    exit;
}

function tgApi($botToken, $method, $data = []) {
    $url = "https://api.telegram.org/bot{$botToken}/{$method}";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    $decoded = json_decode($res, true);
    return is_array($decoded) ? $decoded : ['ok' => false];
}

function sendMessage($botToken, $chatId, $text, $replyMarkup = null) {
    $payload = [
        'chat_id' => $chatId,
        'text' => $text,
        'parse_mode' => 'HTML'
    ];
    if ($replyMarkup) {
        $payload['reply_markup'] = json_encode($replyMarkup);
    }
    tgApi($botToken, 'sendMessage', $payload);
}

function buildMenu($linked, $showVerifyButton = true) {
    if ($linked) {
        $menu = [
            [['text' => '📦 My Orders', 'callback_data' => 'my_orders']],
            [['text' => '💎 My Coin Purchases', 'callback_data' => 'my_purchases']]
        ];
        if ($showVerifyButton) {
            $menu[] = [['text' => '✅ Verify Channel Membership', 'callback_data' => 'verify_channel']];
        }
        return ['inline_keyboard' => $menu];
    }
    return [
        'inline_keyboard' => [
            [['text' => 'ℹ️ How to Link', 'callback_data' => 'help_link']]
        ]
    ];
}

function decodeSyncCode($syncCode) {
    if (!is_numeric($syncCode)) return 0;
    $syncCode = (int)$syncCode;
    if ($syncCode <= 0 || $syncCode % 74596 !== 0) return 0;
    return (int)($syncCode / 74596);
}

function isChannelMember($botToken, $channelId, $telegramUserId) {
    if ($channelId === '') return true;
    $res = tgApi($botToken, 'getChatMember', [
        'chat_id' => $channelId,
        'user_id' => $telegramUserId
    ]);
    if (!($res['ok'] ?? false)) return false;
    $status = $res['result']['status'] ?? '';
    return in_array($status, ['creator', 'administrator', 'member'], true);
}

function grantWelcomeReward($pdo, $userId, $rewardCoins) {
    if ($rewardCoins <= 0) return true;
    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare("SELECT welcome_reward_claimed FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$userId]);
        $claimed = (int)$stmt->fetchColumn() === 1;
        if ($claimed) {
            $pdo->commit();
            return false;
        }
        // Initial welcome reward is added to regular coins.
        $stmt = $pdo->prepare("UPDATE users SET coins = coins + ?, welcome_reward_claimed = 1, welcome_reward_claimed_at = NOW() WHERE id = ?");
        $stmt->execute([$rewardCoins, $userId]);
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, coin_type, description) VALUES (?, 'bonus', ?, 'regular', ?)");
        $stmt->execute([$userId, $rewardCoins, 'Telegram welcome reward']);
        $pdo->commit();
        return true;
    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        return false;
    }
}

if (isset($update['message'])) {
    $message = $update['message'];
    $chatId = $message['chat']['id'];
    $from = $message['from'] ?? [];
    $text = trim($message['text'] ?? '');
    $telegramUserId = (string)($from['id'] ?? '');
    $telegramUsername = $from['username'] ?? null;
    $telegramFirstName = $from['first_name'] ?? null;

    if ($text === '/start' || strpos($text, '/start ') === 0) {
        $parts = explode(' ', $text, 2);
        $startPayload = $parts[1] ?? '';

        if ($startPayload !== '') {
            $userId = decodeSyncCode($startPayload);
            if ($userId > 0) {
                $stmt = $pdo->prepare("SELECT id, welcome_reward_claimed FROM users WHERE id = ? AND telegram_sync_code = ?");
                $stmt->execute([$userId, (int)$startPayload]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($user) {
                    $stmt = $pdo->prepare("
                        UPDATE users
                        SET telegram_user_id = ?, telegram_username = ?, telegram_first_name = ?, telegram_linked_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->execute([$telegramUserId, $telegramUsername, $telegramFirstName, $userId]);
                    $membershipOk = isChannelMember($botToken, $requiredChannel, $telegramUserId);
                    if ($membershipOk) {
                        $granted = grantWelcomeReward($pdo, (int)$userId, $rewardCoins);
                        $textOut = $granted
                            ? "🎉 <b>Welcome!</b>\nYour initial reward has been added successfully.\n\n💎 Reward: <b>{$rewardCoins} coins</b>\n📱 You can now place orders in the app."
                            : "✅ Your Telegram is already linked.\nYour welcome reward was already claimed before.";
                        sendMessage($botToken, $chatId, $textOut, buildMenu(true, false));
                    } else {
                        $joinHint = $requiredChannel !== '' ? "\n\nPlease join: <b>{$requiredChannel}</b>" : '';
                        $msg = "⚠️ Your account is linked, but final verification needs channel membership." . $joinHint . "\n\nAfter channel verification, <b>{$rewardCoins} initial free coins</b> will be added to your account.\n\nTap <b>Verify Channel Membership</b> after joining.";
                        sendMessage($botToken, $chatId, $msg, buildMenu(true, true));
                    }
                    http_response_code(200);
                    exit;
                }
            }
        }
        $stmt = $pdo->prepare("SELECT id, welcome_reward_claimed FROM users WHERE telegram_user_id = ? LIMIT 1");
        $stmt->execute([$telegramUserId]);
        $linkedUser = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($linkedUser && (int)($linkedUser['welcome_reward_claimed'] ?? 0) === 1) {
            $already = "✅ You have already received your initial reward.\n\nUse the buttons below to view your data.";
            sendMessage($botToken, $chatId, $already, buildMenu(true, false));
        } elseif ($linkedUser) {
            $linkedMsg = "✅ Your Telegram is linked to your app account.\nIf required, complete channel verification to receive your initial reward.";
            sendMessage($botToken, $chatId, $linkedMsg, buildMenu(true, true));
        } else {
            $help = "👋 <b>Welcome to MemberX User Bot</b>\n\nUse the link generated in the app to sync your account and claim your welcome reward.";
            sendMessage($botToken, $chatId, $help, buildMenu(false));
        }
        http_response_code(200);
        exit;
    }
}

if (isset($update['callback_query'])) {
    $callback = $update['callback_query'];
    $callbackId = $callback['id'];
    $chatId = $callback['message']['chat']['id'];
    $data = $callback['data'] ?? '';
    $telegramUserId = (string)($callback['from']['id'] ?? '');

    tgApi($botToken, 'answerCallbackQuery', ['callback_query_id' => $callbackId]);

    $stmt = $pdo->prepare("SELECT id, welcome_reward_claimed FROM users WHERE telegram_user_id = ? LIMIT 1");
    $stmt->execute([$telegramUserId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        sendMessage($botToken, $chatId, "❌ No linked app account found.\nPlease open the app and click the verification banner first.", buildMenu(false));
        http_response_code(200);
        exit;
    }

    if ($data === 'verify_channel') {
        $membershipOk = isChannelMember($botToken, $requiredChannel, $telegramUserId);
        if (!$membershipOk) {
            sendMessage($botToken, $chatId, "🚫 Verification failed.\nPlease join the required channel first, then tap verify again.", buildMenu(true, true));
            http_response_code(200);
            exit;
        }
        $granted = grantWelcomeReward($pdo, (int)$user['id'], $rewardCoins);
        $txt = $granted
            ? "🎉 <b>Great!</b> Your initial reward has been added.\n💎 Reward: <b>{$rewardCoins} coins</b>\n✅ You can now use it in the app."
            : "✅ Channel verification completed.\nYour reward was already claimed before.";
        sendMessage($botToken, $chatId, $txt, buildMenu(true, false));
    } elseif ($data === 'my_orders') {
        $stmt = $pdo->prepare("
            SELECT id, total_coins, quantity, status, created_at
            FROM orders
            WHERE user_id = ?
            ORDER BY created_at DESC
            LIMIT 10
        ");
        $stmt->execute([(int)$user['id']]);
        $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
        if (!$orders) {
            sendMessage($botToken, $chatId, "📦 You have no orders yet.");
        } else {
            $text = "📦 <b>Your Recent Orders</b>\n\n";
            foreach ($orders as $o) {
                $text .= "#{$o['id']} • {$o['quantity']} qty • {$o['total_coins']} coins • {$o['status']}\n";
            }
            sendMessage($botToken, $chatId, $text);
        }
    } elseif ($data === 'my_purchases') {
        $stmt = $pdo->prepare("
            SELECT id, coins, price, status, created_at
            FROM coin_purchases
            WHERE user_id = ?
            ORDER BY created_at DESC
            LIMIT 10
        ");
        $stmt->execute([(int)$user['id']]);
        $purchases = $stmt->fetchAll(PDO::FETCH_ASSOC);
        if (!$purchases) {
            sendMessage($botToken, $chatId, "💎 You have no coin purchases yet.");
        } else {
            $text = "💎 <b>Your Coin Purchases</b>\n\n";
            foreach ($purchases as $p) {
                $text .= "#{$p['id']} • +{$p['coins']} coins • {$p['price']} • {$p['status']}\n";
            }
            sendMessage($botToken, $chatId, $text);
        }
    } else {
        $showVerify = ((int)($user['welcome_reward_claimed'] ?? 0) !== 1);
        sendMessage($botToken, $chatId, "ℹ️ Use the menu buttons below.", buildMenu(true, $showVerify));
    }
}

http_response_code(200);
?>

